我正在尝试编写一个动态查询,它产生与以下相同的结果,但用一个变量替换固定的表名。
SELECT *
WHERE tableName = 'Table2A'
工作正常,但
DECLARE @tablename AS NVARCHAR(100)
SET @tablename = N'Table2A'
DECLARE @execquery AS NVARCHAR(MAX)
SET @execquery = N'
SELECT *
WHERE tableName = ''' + QUOTENAME(@tablename) + N''''
EXECUTE sp_executesql @execquery
不返回任何记录。我做错了什么?
答案 0 :(得分:0)
除了SQL语句无效之外,QUOTENAME()只是在提供的变量周围放置括号“[]”。用PRINT语句替换EXECUTE语句,您将得到以下结果:
DECLARE @tablename AS NVARCHAR(100)
SET @tablename = N'Table2A'
DECLARE @execquery AS NVARCHAR(MAX)
SET @execquery = N'
SELECT *
WHERE tableName = ''' + QUOTENAME(@tablename) + N''''
PRINT @execquery
--EXECUTE sp_executesql @execquery
结果:
SELECT *
WHERE tableName = '[Table2A]'