我想分配一个带有返回的变量和“exec(string)”,但我正在努力学习语法。下面是一些工作代码......
declare @iGeographyLevel int = 2
declare @iGeographyLevelID int = 64
declare @sGeographyName varchar(30)
declare @sSQL nvarchar(max)
set @sSQL = '
select Name
from GeographyLevel'+ cast(@iGeographyLevel as varchar(5))+'
where GeographyLevel'+ cast(@iGeographyLevel as varchar(5)) + 'ID = '+ cast(@iGeographyLevelID as varchar(5))
exec (@sSQL)
我想做点像......
set @sGeographyName = exec (@sSQL)
答案 0 :(得分:6)
sp_executesql
是最好的方法。
DECLARE @iGeographyLevel INT = 2
DECLARE @iGeographyLevelID INT = 64
DECLARE @sGeographyName VARCHAR(30)
DECLARE @sSQL NVARCHAR(max)
SET @sSQL = '
SELECT @sGeographyName = Name
FROM GeographyLevel' + cast(@iGeographyLevel AS VARCHAR(5)) + '
WHERE GeographyLevel' + cast(@iGeographyLevel AS VARCHAR(5)) + 'ID = @iGeographyLevelID'
EXEC sp_executesql
@sSQL,
N'@iGeographyLevelID INT, @sGeographyName VARCHAR(30) OUTPUT',
@iGeographyLevelID,
@sGeographyName OUTPUT
SELECT @sGeographyName
这里对动态SQL的要求有点臭。不确定为什么你不只有一个带有Geography
列的Level
表(如果表必须分开,可能还有一个分区视图)也是变量名的匈牙利表示法现在是widely discouraged。