5

我想用从“exec(字符串)”返回的内容分配一个变量,但在语法上遇到了困难。下面是一些工作代码...

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)
4

1 回答 1

8

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分开,则可能是分区视图)此外,这些天广泛不鼓励使用匈牙利表示法来表示变量名。

于 2013-01-12T14:27:33.383 回答