2016-08-24 100 views
1

如何创建一次指定的变量,然后在脚本中稍后用于查询中?这些变量可以在查询中多次使用,也可以在脚本中使用多次查询。在下面的例子中,我使用@x作为这样一个变量。SQL将变量添加到查询中

我想要做的是一样的东西:

Declare @Query nvarchar(1000) 
Declare @x nvarchar(40) 

Set @x = 'test' 
Set @Query = 'Select [Name] 
        , ' + @x + ' as [TestCase] 
       From mytable' 

Exec (@Query) 

-- returns "Invalid column name 'test'" 

它返回上面提到的错误。我想它实现相当于:

Declare @Query nvarchar(1000) 
Declare @x nvarchar(40) 

Set @x = 'test' 
Set @Query = 'Select [Name] 
        , ''test'' as [TestCase] 
       From mytable' 

Exec (@Query) 

-- Returns e.g. 
-- Name TestCase 
-- Alice Test 
-- Bob Test 

我也注意到以下不工作,并返回相同的错误第一:基于错误,因为我

Declare @Query nvarchar(1000) 
Declare @x nvarchar(40) 

Set @x = 'test' 
Set @Query = 'Select [Name] 
        , ' + 'test' + ' as [TestCase] 
       From mytable' 

Exec (@Query) 

-- returns "Invalid column name 'test'" 

我没有试图使用@x作为列名,而只是作为一个变量,我假设我正在使用变量的无效实现。

回答

2

既然你不能试图用一个变量作为列名,你不需要使用动态SQL。

一个简单的(这是一个好东西(TM)由于动态SQL应谨慎大量使用,由于它是一个伟大的攻击面。):

declare @x nvarchar(40) 

set @x = 'test' 

select [Name], @x as TestCase 
from mytable 

会做。


话虽这么说,如果你有一个动态SQL的使用情况(再次在这里的问题不但或许一个即席查询被传递给该过程的特定查询),该做的事将通过sp_executesql将您的变量作为参数传递给查询。这类似于创建具有参数的存储过程:

declare @x nvarchar(40) 
declare @query nvarchar(1000) 

set @x = 'test' 

set @query = 'select [Name], @x as TestCase from mytable' 

exec sp_executesql @query, N'@x nvarchar(1000)', @x 
+0

哦,非常好,谢谢!这按预期工作。 – conor

+0

接受这个答案,因为它最彻底地回答我的问题,并简化它 - 在这种情况下,我实际上并不需要动态SQL。 – conor

+2

我很高兴它有帮助。要回答你的问题的后半部分,你可以尝试'select @ query'来查看正在组成的查询。你会看到'select [Name],test as ...'将“test”视为列名。你需要用引号包装 - 正如其他答案显示的那样。但是接下来你会介绍“如果@ x引用了它会发生什么事情”的问题,这说明了动态SQL的危险。例如,尝试'set @x ='test'',Name,Name,Name,''hahaha''以及其他答案的查询之一! –

1
Declare @Query nvarchar(1000) 
Declare @x nvarchar(40) 

Set @x = 'test' 
Set @Query = 'Select [Name],'++''''[email protected]+''''+ ' as [TestCase] 
       From mytable' 

print @query 

输出:
选择[名], '测试' 为[TestCase的] 从MYTABLE

+0

这工作,但我不明白额外的'+'和单引号做什么。你能否添加一个解释? – conor

+0

@conor:试试这个..请选择'','''','''''' – TheGameiswar

2

您错过了引号。而已。尝试下面的代码。

Declare @Query nvarchar(1000) 
    Declare @x nvarchar(40) 

    Set @x = 'test' 
    Set @Query = 'Select [Name] 
         , ''' + @x + ''' as [TestCase] 
        From mytable' 

    Exec (@Query) 
+0

谢谢@Ranjana。为什么你需要三个单引号围绕这个?我知道两个行为是逃避,但不知道三个人做了什么。 – conor

+0

简单的想法是你已经创建了对列名为test的搜索的select查询,因为它不存在,它会引发错误。既然这是列值,所以你应该把它作为'测试'来传递。用'''生成一个报价,所以'''+ @ x +'''变成'测试'。与您的查询它会是:'+ @ x +' - >测试。由于测试不是列名,所以发生错误 –