sp_executesql抛出错误,但简单的EXEC()工作

时间:2016-12-23 11:02:33

标签: sql-server-2008 dynamic-sql sp-executesql

我需要以动态方式创建用户定义的类型,但

exec()方式:

-- This works
DECLARE @column NVARCHAR(MAX) = 'Id INT'
EXEC ('CREATE TYPE dbo.MyDataType AS TABLE ('+ @column +')')

sp_executesql方式:

-- This does not work
DECLARE @column NVARCHAR(MAX) = 'Id INT'
EXECUTE sp_executesql N'CREATE TYPE dbo.MyDataType AS TABLE ( @column )', @column;  

错误:

  

Msg 102,Level 15,State 1,Line 1
  'Id'附近的语法不正确。

     

Msg 102,Level 15,State 1,Line 1
  '@column'附近的语法不正确。

我错过了什么?

1 个答案:

答案 0 :(得分:4)

即使采用sp_executesql方法,您也需要使用动态SQL:

DECLARE @column NVARCHAR(MAX) = N'Id INT'
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'CREATE TYPE dbo.MyDataType AS TABLE ( ' + @column + ')'
EXECUTE sp_executesql @sql

您可以将参数定义和值传递到sp_executesql,如下所示:

DECLARE @IntVariable int;  
DECLARE @SQLString nvarchar(500);  
DECLARE @ParmDefinition nvarchar(500);  

/* Build the SQL string one time.*/  
SET @SQLString =  
     N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID  
       FROM AdventureWorks2012.HumanResources.Employee   
       WHERE BusinessEntityID = @BusinessEntityID';  
SET @ParmDefinition = N'@BusinessEntityID tinyint';  

/* Execute the string with the first parameter value. */  
SET @IntVariable = 197;  
EXECUTE sp_executesql @SQLString, @ParmDefinition,  
                      @BusinessEntityID = @IntVariable;  

/* Execute the same string with the second parameter value. */  
SET @IntVariable = 109;  
EXECUTE sp_executesql @SQLString, @ParmDefinition,  
                      @BusinessEntityID = @IntVariable; 

(来自sp_executesql上的MSDN page

但我认为这不适合您的使用案例。