3

I have a set of dynamic queries which return XML as varchars, see below.

Example query:

set @sqlstr = 'Select ''<?xml version="1.0" encoding="windows-1252" ?>'' + ''<File_Name><Location>'' + (Select a,b,c from table for xml path(''Row'')) + </Location></File_name>'''

exec(@sqlstr)

This works a treat until the select a,b,c ... query is NULL. Then I don't receive the outside elements as you'd expect like:

<?xml version="1.0" encoding="windows-1252"><File_Name><Location><Row></Row></Location></File_name>

All I receive is NULL

After a bit of Googling I find the issue is the concatenation of NULL results is a complete NULL Result. However I cannot find one solution gives me what I'd expect to be the result.

I've tried (not to say I have tried correctly)

IsNull(Exec(@sqlstring),'*blank elements*')
xsnil (doesn't seem to work in dynamic queries)
@result = exec(@sqlstring) then isnull and select

Anyone have a better solution? (preferably small due to multiple such queries)

1 Answer 1

1

I think you need something like this:

set @sqlstr = 'Select ''<?xml version="1.0" encoding="windows-1252" ?><File_Name><Location>'' + (Select IsNull(a, '') as a, IsNull(b, '') as b,IsNull(c, '') as c from table for xml path(''Row'')) + </Location></File_name>'''

exec(@sqlstr)
Sign up to request clarification or add additional context in comments.

4 Comments

That's my mistake, I did a,b,c for the example its actually * as its in some cases 20 fields. your answer will work and if there is not a shorter method then having to list each one then I will accept as an answer thank you
If there is a shorter way, let me know so I can learn too @LRiley
Will do i'll post whatever answer I find
Seems there are no other options Thanks

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.