如何在exec语句中格式化sql

时间:2014-09-18 10:30:11

标签: sql sql-server datetime sql-server-2008-r2 exec

当我运行以下代码时

declare @startDT datetime
declare @endDT datetime
set @startDT = '2014-09-18 09:28:15.650'
set @endDT = N'2014-09-18 09:28:15.650'

declare @tstamp datetime
set @tstamp = '05/06/2014  15:08:00'

exec('if ' + @startDT + ' <= ' + @tstamp + '
begin
select ''less than''
end
else
begin
select ''greater than''
end')

我收到以下错误

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '18'.
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'else'.

然而,当我删除exec它工作正常。我做错了什么?

2 个答案:

答案 0 :(得分:0)

declare @startDT datetime
declare @endDT datetime
set @startDT = '2014-09-18 09:28:15.650'
set @endDT = N'2014-09-18 09:28:15.650'

declare @tstamp datetime
set @tstamp = '05/06/2014  15:08:00'

exec('if ' +'"'+ @tstamp +'"'+ ' <= ' +'"'+ @tstamp +'"'+ '
begin
select ''less than''
end
else
begin
select ''greater than''
end')

当这个函数返回带有语法错误的SQL Query时会发生这种情况,当你解析它应该在'.try中解析的sql日期时,用这个代码修改你的查询。

答案 1 :(得分:0)

您需要在字符串中形成完整的SQL查询,然后将其作为参数传递。因此,字符串需要日期时间值作为字符串,直到执行@SQL参数。在@SQL的一侧,然后使用convert(datetime ...)来确保所需的比较作为日期时间进行。

DECLARE @sql     nvarchar(max)
DECLARE @startDT nvarchar(23)
DECLARE @endDT   nvarchar(23)

SET @startDT = N'2014-09-18 09:28:15.650'
SET @endDT   = N'2014-09-18 09:28:15.650'

DECLARE @tstamp nvarchar(23)
SET @tstamp = N'2014-05-06 15:08:00'


SET @sql = N'if convert(datetime,'''
           + @startDT
           + ''',121) <= convert(datetime,'''
           + @tstamp 
           + ''',121) begin
 select ''less than''
 end
 else
 begin
 select ''greater than''
 end'

-- SELECT @sql
-- if convert(datetime,'2014-09-18 09:28:15.650',121) <= convert(datetime,'2014-05-06 15:08:00',121) begin select 'less than' end else begin select 'greater than' end

EXEC(@SQL)

使用select @sql检查动态查询字符串,其中包含一个样本。

See this SQLFidde demo

格式化生成的字符串如下所示:

IF CONVERT(datetime, '2014-09-18 09:28:15.650', 121) <=
      CONVERT(datetime, '2014-05-06 15:08:00', 121)
BEGIN
      SELECT
            'less than'
END
ELSE
BEGIN
      SELECT
            'greater than'
END