开发者

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 = 'ActualStartD开发者_StackOverflowate'

SELECT @filterByDate AS Date
FROM TableName

Thanks.


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


 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜