为什么这个Dynamic Sql语句失败了?

时间:2013-06-04 00:33:41

标签: sql sql-server

这没有任何问题:

select COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,IS_NULLABLE 
from [AdventureWorks2012].INFORMATION_SCHEMA.COLUMNS WHERE table_name='employee';

但是,当它转移到动态语句时,它总是失败:

begin
DECLARE @sqlstatement VARCHAR(MAX);
DECLARE @TableName varchar(max)='employee';

set @sqlstatement='select COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,IS_NULLABLE
from [AdventureWorks2012].INFORMATION_SCHEMA.COLUMNS WHERE table_name='+@TableName;
print (@sqlstatement);
EXECUTE(@sqlstatement);

end

错误说:列名'employee'无效

2 个答案:

答案 0 :(得分:9)

你应该用单引号包装它,因为列table_name是字符串,

set @sqlstatement='select COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,IS_NULLABLE
from [AdventureWorks2012].INFORMATION_SCHEMA.COLUMNS WHERE table_name='''+@TableName+'''';

答案 1 :(得分:2)

使用sys.sp_executesql更希望执行动态SQL,所以试试这个 -

DECLARE @SQL NVARCHAR(MAX);
DECLARE @TableName SYSNAME = 'Employee';

SELECT @SQL = '
USE [AdventureWorks2012];
SELECT 
      COLUMN_NAME = c.name
    , DATA_TYPE = TYPE_NAME(c.user_type_id)
    , CHARACTER_MAXIMUM_LENGTH = c.max_length
    , IS_NULLABLE = c.is_nullable
FROM sys.columns c
JOIN sys.objects o ON c.[object_id] = o.[object_id]
WHERE o.name = ''' + @TableName + '''';

PRINT @SQL;
EXEC sys.sp_executesql @SQL;