2011-10-13 84 views
1

基於相同我是MSSQL的新手。我需要改變在條件基於相同的選擇語句中的條件。 我嘗試將Where子句Conditions存儲在一個變量中,並將該變量分配到select語句where子句中。在select語句中的條件基於條件

這樣的..

declare @test varchar(max); 
declare @test1 varchar(max); 
set @test=' id = 14'; 
select FirstName from tblUser where @test; 

不過這樣一些錯誤。

像:

Msg 4145, Level 15, State 1, Line 4 
An expression of non-boolean type specified in a context where a condition is expected, near ';'. 

請告訴我任何其他方式實現這一流程...

謝謝...

回答

0

你可以使用動態SQL做到這一點。欲瞭解更多信息,請參閱從Obed的答案鏈接

declare @test nvarchar(max); 
    create table tblUser (id int, FirstName varchar(10)) 
    set @test=N' id = 14'; 
    set @test=N'select FirstName from tblUser where '[email protected] 
    exec sp_executesql @test; 

    drop table tblUser 
+0

我們可以不使用exec註釋??? –

+0

我認爲,沒有。也許,別人會爲你提供更好的解決方案。 –

1

不能存儲在執行變量整體條件,特別是如果它們包含列名稱。

你可以做到這一點,如果你要使用動態SQL,但隨之而來的自己的一套併發症。文章很好的閱讀關於動態SQL(動態SQL的詛咒和祝福)。

但是,我會質疑你需要這樣做。