我有以下exec查询:
EXEC (
'SELECT (SELECT Count(*) AS Count_Id FROM ns_customer WHERE external_id IN (
' RW00363075 ',' RW00336566 ',' RW00365438 ',' RW00343570 ') ) AS Count_Id,
ACH_allowed, CC_allowed, DD_allowed FROM ns_customer
WHERE external_id IN (' RW00363075 ',' RW00336566 ',' RW00365438 ',
' RW00343570 ')'
);
执行后我收到错误:
SQL语句:'RW00363075'附近的语法不正确。引起: 'RW00363075'附近的语法不正确。
我该如何解决这个问题?
由于
答案 0 :(得分:8)
使用两个单引号转义单引号
EXEC('SELECT (SELECT Count(*) AS Count_Id FROM ns_customer WHERE external_id IN (''RW00363075'',''RW00336566'',''RW00365438'',''RW00343570'') ) AS Count_Id, ACH_allowed, CC_allowed, DD_allowed FROM ns_customer
WHERE external_id IN (''RW00363075'',''RW00336566'',''RW00365438'',''RW00343570'')');
答案 1 :(得分:3)
您的具体问题的答案是加倍单引号。但是,(假设您使用的是SQL Server),您的查询将更简单地写为:
SELECT COUNT(*) OVER () as Count_Id, ACH_allowed, CC_allowed, DD_allowed
FROM ns_customer
WHERE external_id IN ('RW00363075', 'RW00336566', 'RW00365438', 'RW00343570')
或者,根据我的喜好,使用sp_executesql
:
declare @sql nvarchar(max);
set @sql = '
SELECT COUNT(*) OVER () as Count_Id, ACH_allowed, CC_allowed, DD_allowed
FROM ns_customer
WHERE external_id IN (''RW00363075'', ''RW00336566'', ''RW00365438'', ''RW00343570'')';
exec sp_executesql @sql;
如果您要学习如何做到这一点,您也可以学习正确的方法。 sp_executesql
优于exec()
,因为它允许您将参数传入和传出查询。首先学习使用它比以后学习更简单。