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
精彩评论