根據變量值,我需要在SQL查詢的where子句中包含一個列名。 例如, 1.如果我有一個變量,比如@test,並且我賦值變量的值爲1/0。 2.我有一個表,比如說,表1與2列名稱col1,col2。現在如何在case語句中包含列名
,我寫的查詢被包括在同一時間只有一列以獲取表中的某些數據依賴於@Test變量(早些時候宣佈),即我需要包括COL1在where子句中查詢如果@test爲1和COL2如果@test爲0
請讓我儘快知道解決的辦法。
在此先感謝
根據變量值,我需要在SQL查詢的where子句中包含一個列名。 例如, 1.如果我有一個變量,比如@test,並且我賦值變量的值爲1/0。 2.我有一個表,比如說,表1與2列名稱col1,col2。現在如何在case語句中包含列名
,我寫的查詢被包括在同一時間只有一列以獲取表中的某些數據依賴於@Test變量(早些時候宣佈),即我需要包括COL1在where子句中查詢如果@test爲1和COL2如果@test爲0
請讓我儘快知道解決的辦法。
在此先感謝
declare @tbl table
(
col1 int,
col2 int
)
insert into @tbl select 10, 20
declare @test int
set @test = 1
select *
from @tbl
Where Case When @test = 1 Then Col1 Else Col2 End = 10
如果數據類型是不同的
select *
from @tbl
Where Case when @test = 1 Then Col1 end = 10
OR
Case when @test = 2 Then Col2 end = 'sometext'
Select *
From dbo.MyTable
Where Case When @Test = 1 Then Col1 Else Col2 End > 100
稍微不同的方法:
Select *
From dbo.MyTable
Where Col1 = Case When @Test = 1 Then 10 Else Col1 End and
Col2 = Case When @Test = 0 Then 'sometext' Else Col2 End
這個版本的查詢可能是sargable。
這兩列是不同的數據類型。那該怎麼辦? – ASD 2010-09-20 09:17:18