Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring SQL variables - SQL Server

Can anyone check on my statement...

DECLARE @tblName varchar(MAX), 
        @strSQL varchar(MAX)

SET @tblName ='SELECT DISTINCT o.name as TableName 
                 FROM sysobjects o 
                 JOIN sysindexes x on o.id = x.id  
                WHERE o.name LIKE ''%empty%'''  

SET @strSQL = 'INSERT INTO @tblName VALUES(''trylng'', ''1'')'
EXEC (@strSQL)

my error is...

Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "@tblName".

What I want to do is get the table name on the variable @tblName and insert some data in @strSQL variable

For example... the result in @tblName is CustomerInfo

then in @strSQL I will going to use the result in @tblName as my table name in my Insert Command.

So the @strSQL variable will be;

INSERT INTO CustomerInfo VALUES(......)
like image 445
Argel Joseph Avatar asked Feb 23 '12 06:02

Argel Joseph


People also ask

How do you DECLARE a variable in SQL Server?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.

How do I DECLARE a variable in a SQL table?

To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign. The TABLE keyword defines that used variable is a table variable. After the TABLE keyword, define column names and datatypes of the table variable in SQL Server.

How do you DECLARE a variable number in SQL?

Finally, let's look at how to declare an INT variable in SQL Server and assign an inital value. For example: DECLARE @site_value INT = 10; This variable declaration example would declare a variable called @site_value that is an INT datatype.

Can we DECLARE variables in view in SQL Server?

You can't declare variables in a view.


1 Answers

Try this from my answer to your other question:

 SELECT TOP 1 @tblName = t.name
 FROM sys.tables t
 INNER JOIN sys.indexes i on i.object_id = t.object_id  
 WHERE t.name LIKE '%empty%'

 SET @strSQL = 'INSERT INTO ' + @tblName  + ' VALUES(''trylng'', ''1'')'
 EXEC (@strSQL)

You're still not mentioning the SQL Server version you're using. But as of SQL Server 2005 or newer, you should stop using sysobjects and sysindexes - instead, use the new sys schema that contains more or less the same information - but more easily available.

See [MSDN: Querying the SQL Server System Catalog][1] for a lot more information on what's available in the new sys schema and how to make the most of it!

like image 53
marc_s Avatar answered Sep 16 '22 17:09

marc_s