0

In this SQL query

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'"');

There is the problem that SQL Server can't handle the 'R' and 'DE' and 'EL' inside of the "AND worst_status='R' AND country='DE' AND commodity='EL'"'

This error occurs:

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

Is there another syntax I have to use inside the quote to let SQL Server see it just as a quote? I am using Microsoft SQL Server Management Studio 2017

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mad Scientist
  • 857
  • 4
  • 16
  • 43

2 Answers2

3

You need to double-up the single quotes :

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'' "');
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
1

In a real world environment you are unlikely to write those values literally. If you really do, then you would need your single quotes doubled. For the real world scenario however, you would be using parameters which also take care of this issue:

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);
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39