使用动态 SQL 的列名无效

Invalid Column Name using Dynamic SQL

我第一次尝试使用 Dynamic SQL - 现在我在一定程度上理解了它的要点,但是尝试使用 Dynamic [=22] 将参数输入到临时 table =] 我得到 "Invalid Column name" 当我只是尝试将其作为文本输入而不打算成为一列时。

顺便提一下,我 运行 在 SQL Server 2005 上进行此操作。

这是我正在执行的查询

SELECT ARCHV_FLAG,PATNT_REFNO,ACTIVE_NAMES,AINPT_REFNO INTO #TEMP FROM ACTIVE_NAMES WHERE PATNT_REFNO = 1 AND ARCHV_FLAG = 'C'

Fix SET @SQL = 'SELECT ARCHV_FLAG,PATNT_REFNO,'''+@TABLE +''' AS      [ACTIVE_NAMES],'+ @PK + ' INTO #TEMP FROM ' + @TABLE + ' WHERE PATNT_REFNO = '+ CAST(@PATNT AS VARCHAR (100))+ ' AND ARCHV_FLAG = ''C'''

非常感谢。

DECLARE
    @SQL NVARCHAR(4000),
    @SQL1 NVARCHAR(4000),
    @TABLE VARCHAR (100),
    @PK VARCHAR (50),
    @PATNT INT

SET @PATNT = 1

CREATE TABLE #TEMP
(
    ARCHV_FLAG VARCHAR (1),
    PATNT_REFNO INT,
    TABLE_NAME VARCHAR (100),
    PRIMARY_KEY INT
)

 CREATE TABLE #TABLE
 (NAME VARCHAR (100))

 INSERT INTO #TABLE (NAME) VALUES ('ACTIVE_NAMES')

SELECT * FROM #TABLE

 DECLARE Cur CURSOR FOR
 SELECT NAME FROM #TABLE

OPEN Cur

FETCH NEXT FROM Cur INTO @TABLE
WHILE @@FETCH_STATUS = 0
BEGIN

SET @PK = (SELECT C.NAME FROM SYS.COLUMNS C 
       JOIN SYS.tables T ON C.object_id = T.object_id 
       WHERE T.name = @TABLE AND C.is_identity = 1)

SET @SQL = 'SELECT ARCHV_FLAG,PATNT_REFNO,'+@TABLE +','+ @PK + ' INTO #TEMP FROM ' + @TABLE + ' WHERE PATNT_REFNO = '+ CAST(@PATNT AS VARCHAR (100))+ ' AND ARCHV_FLAG = ''C'''
EXEC SP_EXECUTESQL @SQL

select @sql

FETCH NEXT FROM Cur INTO @TABLE
END
CLOSE Cur
DEALLOCATE Cur

SELECT * FROM #TEMP
DROP TABLE #TEMP
DROP TABLE #TABLE

如果您希望动态 SQL 将您的变量视为文字字符串而不是列名,您必须将其用单引号引起来:

SET @SQL = 'SELECT ARCHV_FLAG,PATNT_REFNO,'''+@TABLE +''' AS [ACTIVE_NAMES],'+ @PK + ' INTO #TEMP FROM ' + @TABLE + ' WHERE PATNT_REFNO = '+ CAST(@PATNT AS VARCHAR (100))+ ' AND ARCHV_FLAG = ''C'''
EXEC SP_EXECUTESQL @SQL