Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nvarchar concatenation problem

Tags:

sql

nvarchar

I am probably trying to do a simple thing after dealing with all the hard stuff but seems like this is giving me a headache. I am trying to concatenate text into variable @strXml which is an nvarchar variable to build Xml element, but @strXml returns null. Please help. I am posting my code below.

DECLARE @strXml nvarchar(max) = ''
SET @strXml = '<PromoName>' + (Select PromoName From #Temp) + '</PromoName>' 
SET @strXml = @strXml + '<PromoDesc>' + (Select PromoDesc From #Temp) + '</PromoDesc>'
SET @strXml = @strXml + '<PromoCode>' + (Select PromoCode From #Temp) + '</PromoCode>' 
SET @strXml = @strXml + '<BeginDate>' + (Select Convert(nvarchar, BeginDate) From #Temp) + '</BeginDate>'
SET @strXml = @strXml + '<EndDate>' + (Select Convert(nvarchar, EndDate) From #Temp) + '</EndDate>'
SET @strXml = @strXml + '<RawHtml>' + (Select RawHtml From #Temp) + '</RawHtml>'
SET @strXml = @strXml + '<FocusPromoInd>' + Convert(nvarchar, 0) + '</FocusPromoInd>'
SET @strXml = @strXml + '<ParentPromoCode>' + (Select ParentPromoCode From #Temp) + '</ParentPromoCode>'
SET @strXml = @strXml + '<ActiveInd>' + (Select Case When ActiveInd=1 Then '1' Else '0' End From #Temp) + '</ActiveInd>'
SET @strXml = @strXml + '<AreaID>' + (Select Convert(nvarchar, AreaID) From #Temp) + '</AreaID>'
SET @strXml = '<PromoData><Promotion>' + @strXml + '</Promotion></PromoData>'
Select @strXml as strXML

And when I run the last query it returns null. Even in debug mode I cannot see @strXml updated with value on each line. Please help! Thanks.

like image 627
Ashar Syed Avatar asked Jun 26 '26 00:06

Ashar Syed


1 Answers

One of the fields that you are concatenating is null.

Anytime you concatenate a string and a null value in SQL, the result is null.

You can use the COALESCE command to fix that:

declare @strXml nvarchar(max) = ''
set @strXml = '<PromoName>' + (select coalesce(PromoName, '') from #Temp) +
    '</PromoName>'
-- and so on
like image 181
Justin Niessner Avatar answered Jun 27 '26 20:06

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!