2011-06-21 86 views
1

我想獲得像這樣的功能我該如何做到這一點。列名作爲變量在選擇

DECLARE @filterByDate VARCHAR(20) 

IF(@filterByDate = 'expectedDate') 
    SET @filterByDate = 'ExpectedStartDate' 
ELSE 
    SET @filterByDate = 'ActualStartDate' 

SELECT @filterByDate AS Date 
FROM TableName 

謝謝。

回答

1
DECLARE @filterByDate VARCHAR(20) 

IF(@filterByDate = 'expectedDate') 
    SET @filterByDate = 'ExpectedStartDate' 
ELSE 
    SET @filterByDate = 'ActualStartDate' 

Declare @Sql varchar(max) 

SET @SQL = 'SELECT @Filter AS DATE FROM TableName' 
DECLARE @ParmDefinition nVARCHAR(20) 
SET @ParmDefinition = N'@filter nvarchar(20)' 
exec sp_executesql @SQL, @ParmDefinition, @Filter = @filterByDate 
+0

感謝,這是有益的** DECLARE @filterByDate VARCHAR(20) SET @filterByDate = 'ExpectedStartDate' 聲明@sql VARCHAR(最大值) SET @SQL = 'SELECT' + @filterByDate + '日期,insertDate從工作表' EXEC(@SQL)** – Sami

+0

IF @filterByDate沒有被清除掉,你有一個SQL注入風險 – gbn

+0

沒有注射在這裏 - 只有paramete r傳入sp_executesql是在usp中聲明並設置的。作爲參數傳入也沒有好處。 – BonyT

3

SQL標準,適用於大多數RDBMS

SELECT CASE @filterByDate 
     WHEN 'ExpectedStartDate' THEN ExpectedStartDate 
     WHEN 'ActualStartDate' THEN ActualStartDate 
     ELSE NULL 
     END as mydate 
     --optional , @filterByDate AS ColumnName 
FROM 
    MyTable