如何在sql中使用exec字符串赋值变量?

时间:2013-01-12 11:49:09

标签: sql-server

我想分配一个带有返回的变量和“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)

1 个答案:

答案 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