开发者

Column name as variable in select

开发者 https://www.devze.com 2023-03-14 14:36 出处:网络
I want to acheive the functionality like this how can i do this. DECLARE @filterByDate VARCHAR(20) IF(@filterByDate = \'expectedDate\')

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

精彩评论

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

关注公众号