' ' 在 SQL 服务器中的“”内

' ' inside of " " in SQL Server

在此SQL查询中

INSERT INTO RESULT_FILTER (RESULT_FILTER_NAME, RESULT_FILTER_SQL)
VALUES ('German Power Trades flagged red', 
        '" AND worst_status = 'R' AND country = 'DE' AND commodity = 'EL'"');

问题是SQL服务器无法处理"AND worst_status='R' AND country='DE' AND commodity='EL'"'[=14=里面的'R'和'DE'和'EL' ]

发生此错误:

Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'R'.

我是否必须在引号内使用另一种语法才能让 SQL 服务器将其视为引号?我正在使用 Microsoft SQL Server Management Studio 2017

您需要将单引号加倍:

INSERT INTO RESULT_FILTER (RESULT_FILTER_NAME, RESULT_FILTER_SQL)
        VALUES('German Power Trades flagged red', '" AND worst_status=''R''
                 AND country=''DE'' AND commodity=''EL'' "');

在现实世界环境中,您不太可能按字面意思写出这些值。如果你真的这样做,那么你需要将你的单引号加倍。然而,对于现实世界的场景,您将使用也可以解决此问题的参数:

declare @filterName nvarchar(200) = N'German Power Trades flagged red'
declare @filterSQL nvarchar(4000) = N'AND worst_status=''R''
      AND country=''DE'' 
      AND commodity=''EL''' 
-- @filterName and @filterSQL would come from client
INSERT INTO RESULT_FILTER (RESULT_FILTER_NAME, RESULT_FILTER_SQL)
VALUES (@filterName, @filterSQL);