0

I've a question about my SQL CTE construction. I'm working with Azure Data Factory and a Stored Procedure in my database. What I want to do is:

  1. Return my data from my view to Azure Data Factory in JSON format.
  2. Return the data filtered dynamically in the WHERE clause based on my ObjectCode in my view in JSON format. -> To test step 2 I tried with a statical declared ObjectCode

But the single quote does not work right in the WHERE clause. I tried some things with REPLACE, CHAR(39) and double the quotes. Like they said here, here and here

Step 1 I've finished succesfull with this code:

BEGIN

            DECLARE @TABLE TABLE(RESULT NVARCHAR(MAX))
            DECLARE @QUERY NVARCHAR(MAX) = '

            ;WITH x(Params) as 
            (
            SELECT * FROM [Schema].[View] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
            )
            Select * from x  
            '
            Insert @TABLE
            EXEC (@QUERY)

            Select ',"pipelineParameters": ' + LEFT(RESULT,LEN(RESULT)-1) + '}' as Params from @TABLE;


        END

This query above gave me the right result. But, now I need to make a change for Step 2. I need to filter with the WHERE clause in the query.

So, I tried:

DECLARE @TABLE TABLE(RESULT NVARCHAR(MAX))
            DECLARE @ObjectCode NVARCHAR(MAX) = 'Objectname'
            DECLARE @QUERY NVARCHAR(MAX) = '

            ;WITH x(Params) as 
            (
            SELECT * FROM [Schema].[View] 
            WHERE Objectcode = REPLACE(@ObjectCode, '''', '')
            FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
            )
            Select * from x  
            '
            Insert @TABLE
            EXEC (@QUERY)
            Select ',"pipelineParameters": ' + LEFT(RESULT,LEN(RESULT)-1) + '}' as Params from @TABLE;

But when I run these query I get this error:

Query Error

Does anyone know what I can improve here so I can get it working?

haassiej
  • 55
  • 1
  • 10

2 Answers2

0

Does this do what you want?

Insert @TABLE
    exec sp_executesql @QUERY, N'@ObjectCode nvarchar(max)', @ObjectCode=@ObjectCode;

As written, I would expect a syntax error when the query is run because of this WHERE clause:

WHERE Objectcode = REPLACE(@ObjectCode, '', ')

I think you intend:

DECLARE @QUERY NVARCHAR(MAX) = '
WITH x(Params) as  (
      SELECT *
      FROM [Schema].[View] 
      WHERE Objectcode = REPLACE(@ObjectCode, '''''''', '''')
      FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
     )
Select * 
from x';

Quoting things in dynamic SQL is always verbose. You can print out @Query to see if it is really what you intend.

'

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Thanks Gordon, the first one works for me:

Insert @TABLE
    exec sp_executesql @QUERY, N'@ObjectCode nvarchar(max)', @ObjectCode=@ObjectCode;
haassiej
  • 55
  • 1
  • 10