If there is a variable in the script we run and we have not declared this variable, we will get this error.
For example, with the help of the following script, let’s create a table named “databaseandlogins” in the “TestDB” database.
1 2 3 4 5 6 |
USE [TestDB] GO CREATE TABLE [dbo].[databaseandlogins]( [database_name] [varchar](10) NULL, [login_name] [varchar](10) NULL, ) ON [PRIMARY] |
Then try to add data to this table as follows.
1 2 3 4 5 6 |
INSERT INTO [TestDB].[dbo].[databaseandlogins] ([database_name] ,[login_name]) VALUES (@loginname,@databasename) GO |
When we try to add data in this way, we will get an error as follows.
After we declare and set the required variables, you will see that the problem is solved when we run it again.
You can learn more about declaring variable in the artilce “Declare Variables in SQL Server(TSQL)”
1 2 3 4 5 6 7 8 9 10 11 |
DECLARE @loginname varchar(50) DECLARE @databasename varchar(50) SET @loginname =(select top 1 name from sys.sql_logins) SET @databasename = (select top 1 name from sys.databases) INSERT INTO [TestDB].[dbo].[databaseandlogins] ([database_name] ,[login_name]) VALUES (@loginname,@databasename) GO |