1

这是我的代码:

DECLARE @1day AS VARCHAR(MAX), @sqlText AS NVARCHAR(MAX), @firstdate AS DATETIME

SET @firstdate = DATEADD(dd,-(DAY(GETDATE())-1),GETDATE()) 
SET @1day = CONVERT(VARCHAR(MAX), @firstdate, 103)

SET @sqlText = 'SELECT ' + 'Dummy' + ' AS ' + @1day

EXEC (@sqlText)

我收到错误消息:[Err] 42000 - [SQL Server]'01' 附近的语法不正确。

预期结果是:

01/06/2013
==========
Dummy

感谢帮助。

4

2 回答 2

1

您必须用单引号括起来Dummy,否则列别名的语法不正确,并被解释为列名。@1day@1dayDummy

有效的 SQL:

DECLARE @1day AS VARCHAR(MAX), @sqlText AS NVARCHAR(MAX), @firstdate AS DATETIME

SET @firstdate = DATEADD(dd,-(DAY(GETDATE())-1),GETDATE())
SET @1day = CONVERT(VARCHAR(MAX), @firstdate, 103)

SET @sqlText = 'SELECT ' + '''Dummy''' + ' AS ''' + CAST(@1day as nvarchar) + ''''

exec (@sqlText)
于 2013-06-20T06:46:40.933 回答
1

尝试这个 :

DECLARE @1day VARCHAR(MAX), @sqlText NVARCHAR(MAX), @firstdate DATETIME

SET @firstdate = DATEADD(dd,-(DAY(GETDATE())-1),GETDATE()) 
SET @1day = CONVERT(VARCHAR(MAX), @firstdate, 103)

SET @sqlText = 'SELECT ' + '''Dummy''' + ' AS [' + @1day + ']'

EXEC (@sqlText)
于 2013-06-20T06:53:41.047 回答