2

I have problem with dynamic sql (yeah only one ;) )

Inside stored procedure I declared a local variable like this :

DECLARE @cmd nvarchar(max) Later in the code I have this line with a lots of input parameters my sp recieved (sorry for the mess didn't succeed in organizing it) :

SET @cmd = 'INSERT INTO dbo.' + @ArchiveTableName + '(' + @ArchiveFieldsName + ',' + @ArchiveEntityMainIdentifierField + ')
    SELECT ' + @EntityFieldsName + ',' + '' + @EntityMainIdentifierField + '' +
       ' FROM [' + @OrganizationName + '].[dbo].[' + @EntityName + '] ent
        left join dbo.' + @ArchiveTableName + ' arc on arc.' + @ArchiveEntityMainIdentifierField + ' = ent.' + @EntityMainIdentifierField + '
        where ent.' + @EntityMainIdentifierField + ' = ''' + @ParentId + ''' and arc.' + @ArchiveEntityMainIdentifierField + ' is null'

After I debugged it, I found something weird. After running this @cmd stays empty.

Can anyone please give me a clue of why this might be happening?

3
  • 4
    If one variable is NULL then the entire string will become NULL Commented Jan 11, 2017 at 14:38
  • oh didnt know it , i will check it out now. Commented Jan 11, 2017 at 14:39
  • yep thats the thing , thank you! Commented Jan 11, 2017 at 14:45

1 Answer 1

6

I bet one of your other variables is NULL. 'Something' + NULL = NULL. You can use CONCAT(sql server 2012+), it will turn NULL into an empty string. Better is to use COALESCE(sql server 2008+) as well (and make sure the essential variables aren't NULL).

Sign up to request clarification or add additional context in comments.

Comments

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.