Declaring SQL Variables - SQL Server

Can anyone check my expression ...

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 mistake...

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

What I want to do is get the table name in the variable @tblNameand insert some data into the variable@strSQL

For example, the result in @tblNameisCustomerInfo

then in @strSQLi'm going to use the result in @tblNameas the name of my table in my insert command.

So the variable @strSQLwill be;

INSERT INTO CustomerInfo VALUES(......)
+5
source share
3 answers

Try this from my answer to another 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)

SQL Server, . SQL Server 2005 sysobjects sysindexes - sys, , .

. [MSDN: SQL Server] [1] , sys , !

+2

DECLARE, ( ):

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

- :

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

SET @tblName =  (SELECT DISTINCT TOP 1  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)

, , , , sql , ,

+1

All Articles