Sami
Sami

Reputation: 3976

Column name as variable in select

I want to acheive the functionality like this how can i do this.

DECLARE @filterByDate VARCHAR(20)

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

SELECT @filterByDate AS Date
FROM TableName

Thanks.

Upvotes: 2

Views: 2815

Answers (2)

BonyT
BonyT

Reputation: 10940

 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

Upvotes: 1

gbn
gbn

Reputation: 432200

SQL Standard, works on most RDBMS

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

Upvotes: 4

Related Questions