5

I would like to assign a variable with what is returned from and "exec (string)" but am struggling with syntax. Below is some working code...

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)

I would like to do something like...

set @sGeographyName  = exec (@sSQL)
wildplasser
  • 43,142
  • 8
  • 66
  • 109
Mead3000
  • 581
  • 2
  • 5
  • 18
  • Some might say it is a duplicate of http://stackoverflow.com/questions/2245691/how-to-assign-an-exec-result-to-a-sql-variable which may be the case, but I want to avoid creating an SP – Mead3000 Jan 12 '13 at 11:50

1 Answers1

8

sp_executesql is the best way of doing this.

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 

The requirement for dynamic SQL here is a bit smelly though. Not sure why you don't just have one Geography table with a Level column (or possibly a partitioned view if the tables must be separate) Also Hungarian notation for variable names is widely discouraged these days.

Community
  • 1
  • 1
Martin Smith
  • 438,706
  • 87
  • 741
  • 845