提问人:Hannah 提问时间:12/10/2022 最后编辑:Dale KHannah 更新时间:12/10/2022 访问量:153
消息 102,级别 15,状态 1,第 4 行“4”附近的语法不正确
Msg 102, Level 15, State 1, Line 4 Incorrect syntax near '4'
问:
declare @table_name varchar(50) = '' ;
select
@table_name = iif((@YEAR is null) AND (@WEEK is null), 'table1', 'table2')
declare @cmmnd varchar(max) = '' ;
set @cmmnd = 'SELECT B.*
INTO #temptable
FROM [schema1].' + @table_name + ' B WITH (READUNCOMMITTED)
WHERE B.Start <= CAST(' + CAST(@DATE AS varchar(30)) + ' AS DATETIME)
AND ISNULL(B.End, IIF(B.CrntR = 1, CAST(' + CAST(@DATE AS varchar(30)) + ' AS DATETIME) + 1, CAST('
+ CAST(@DATE AS varchar(30)) + ' AS DATETIME) - 1)) > CAST(' + CAST(@DATE AS varchar(30)) + ' AS DATETIME)';
EXEC (@cmmnd);
为什么我会收到这个错误?
消息 102,级别 15,状态 1,第 4
行“4”附近的语法不正确
我正在使用 SQL Server 2014 版本
我尝试更改代码,但仍然收到相同的错误。
答:
1赞
Dale K
12/10/2022
#1
使用 PRINT 语句调试动态 SQL 以打印将要运行的 SQL,然后可以将其调试为静态 SQL。打印您的对帐单可以:
SELECT B.*
INTO #temptable
FROM [schema1].table1 B WITH (READUNCOMMITTED)
WHERE B.Start <= CAST(2022-12-10 AS DATETIME)
AND ISNULL(B.End, IIF(B.CrntR = 1, CAST(2022-12-10 AS DATETIME) + 1, CAST(2022-12-10 AS DATETIME) - 1)) > CAST(2022-12-10 AS DATETIME)
如果粘贴到 SSMS 中,则会显示大量语法错误。
- 你没有引用你的日期字符串
- 您没有转义用作列名的关键字,例如 正确的查询是:
Start
End
set @cmmnd = 'SELECT B.*
INTO #temptable
FROM [schema1].' + @table_name + ' B WITH (READUNCOMMITTED)
WHERE B.[Start] <= CAST(''' + CAST(@DATE AS varchar(30)) + ''' AS datetime)
AND ISNULL(B.[End], DATEADD(day, IIF(B.CrntR = 1, 1, -1), CAST(''' + CAST(@DATE AS varchar(30)) + ''' AS datetime))) > CAST(''' + CAST(@DATE AS varchar(30)) + ''' AS datetime)';
这解决了这两个问题并简化了语句中的逻辑,同时使用正确的日期时间函数来添加天数,而不是依赖于知道指的是天数。这将返回:IIF
+/-1
SELECT B.*
INTO #temptable
FROM [schema1].table1 B WITH (READUNCOMMITTED)
WHERE B.[Start] <= CAST('2022-12-10' AS datetime)
AND ISNULL(B.[End], DATEADD(day, IIF(B.CrntR = 1, 1, -1), CAST('2022-12-10' AS datetime))) > CAST('2022-12-10' AS datetime)
它至少可以解析 - 但我无法进一步测试它。
注意:我不相信你的逻辑是有道理的,对于某个输入 (),您正在检查“2022-12-10”的恒定日期(减去一天)是否大于它本身 - 但如果这是一个问题,它需要另一个问题。B.CrntR <> 1
评论