4

I wonder if can I define some parts of the my sql query as a string.

I worked on the code below but I could not manage to concat that pre-defined string part to the existing query.

Actually @sirketid, @uzman, @basvurukodu params works well, however the @ORA_BASVURU_KESIN_KOSUL param is causing a problem.

I think because it has some sql-spesific expression like and, it is treated diffrently than simple variables used for comparison or assigning such as @sirket_id.

It does not throw any error message, the code simply does not excute the operation.

SET @ORA_BASVURU_KESIN_KOSUL = 'and akftif = 1';

UPDATE basvuru 
SET sirket = @sirketid,
    talep_gorevlendirme_rapor = 'G',
    birimi = 'SS', 
    uzman = @uzman,
WHERE
    kod = @basvurukodu + ' ' + @ORA_BASVURU_KESIN_KOSUL; 

Can I concat query parts like this, if so, how?

Thanks

4
  • you will need dynamic sql. first concatenate the whole SQL you want to execute and finally execute the SQL with EXEC Commented Aug 7, 2017 at 12:57
  • You cannot concat e new condition on like that. To do that you have to make the query dynamic Commented Aug 7, 2017 at 12:57
  • Background material for your perusal, and also this more in general for dynamic SQL. There's a lot to say about this topic. Passing in arbitrary SQL as a parameter is almost never a good approach, due to the risk of injection involved. Commented Aug 7, 2017 at 13:01
  • This is really complicated than I thoght :) Commented Aug 7, 2017 at 13:04

1 Answer 1

5

Your query should work like:

  1. Concatenate the whole Query
  2. Execute the query with EXEC

of course you have to declare the other variables too:

SET @ORA_BASVURU_KESIN_KOSUL = 'and akftif = 1';

DECLARE @MyExecSQL varchar(2000) =
    'UPDATE basvuru 
        SET sirket = @sirketid
           ,talep_gorevlendirme_rapor = ''G''
           ,birimi = ''SS''
           ,uzman = ' + @uzman + 
     ' WHERE kod = ' + @basvurukodu + 
        ' ' + @ORA_BASVURU_KESIN_KOSUL + ''
;     
EXEC @MyExecSQL
Sign up to request clarification or add additional context in comments.

2 Comments

Use NVARCHAR(MAX), there's no reason to settle for anything less. @sirketid will be undefined. Concatenating string parameters this way won't work, they'll need to be escaped. Using EXEC rather than sp_executesql with parameters may cause a lot of query plan cache pollution. With dynamic SQL, the devil's in the details.
I had to use EXEC (@MyExecSQL)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.