我有一个我从select语句(@ENTY_TABLE_NAME)填充的变量:
DECLARE @ENTY_TABLE_NAME varchar(500)
DECLARE @ENTY_ID INT;
DECLARE @FIELD_ID INT;
DECLARE @VALUE VARCHAR(50);
SET @ENTY_ID = 1
SET @FIELD_ID = 90
SET @VALUE = '0'
SET @ENTY_TABLE_NAME =
(SELECT TOP 1 ENTY_TABLE_NAME
FROM ENTY
WHERE ENTY.ENTY_ID=@ENTY_ID);
SELECT DISTINCT ATTR_VAL
FROM @ENTY_TABLE_NAME _ATTR
WHERE FIELD_ID= @FIELD_ID AND ATTR_VAL LIKE'%' + @VALUE + '%'
ORDER BY ATTR_VAL
在我尝试使用另一个select语句但它返回错误后:
Msg 1087, Level 16, State 1, Line 26
Must declare the table variable "@ENTY_TABLE_NAME".
为什么说我没有声明一个我声明了事实的变量?我该如何解决这个问题?
答案 0 :(得分:6)
问题不在于未声明变量。问题是你不能在常规SQL语句中使用变量作为表名(除非变量是表变量)。
如果表名必须是变量,则使用动态SQL:
declare @sql nvarchar(max);
set @sql = '
SELECT DISTINCT ATTR_VAL
FROM @ENTY_TABLE_NAME _ATTR
WHERE FIELD_ID = @FIELD_ID AND ATTR_VAL LIKE ''%'' + @VALUE + ''%'''
ORDER BY ATTR_VAL';
set @sql = replace(@sql, '@ENTY_TABLE_NAME', ENTY_TABLE_NAME);
exec sp_executesql @sql, N'@FIELD_ID int, @VALUE varchar(50)', @FIELD_ID = @FIELD_ID, @VALUE = @VALUE;