1

What a want to do is something like that:

declare @id int
set @id = (select ID from tbUsers where Name = 'John_Stack')

declare @xml xml
set @xml = '<users> <user id = "' + @id + '"/></users>'

The server aborted saying

Operand type clash: int is incompatible with xml.

What is the best way to do this?

I'm working with SQL Server 2005.

Thanks in advance.

4

2 回答 2

4
declare @id int
set @id = (select ID from tbUsers where Name = 'John_Stack')

declare @xml xml
set @xml = '<users> <user id = "' + CONVERT(varchar,@id) + '"/></users>'
于 2012-06-22T18:16:31.327 回答
2

You may wish to avoid constructing your own XML from scratch with string concatenation. It feels unclean, at least to me, particularly when you have better tools already available to you. For instance, in SQL Server 2005, you could do this and get your desired result:

Declare @xml xml;
Set @xml = (
    Select id As [@id]
    From tbUsers
    Where Name = 'John_Stack'
    For XML Path('user'), Root('users'), Type);

Or, if you think tbUsers will not have your user, but you still want a root <users /> element even if no rows are returned, you could use this variation:

Declare @xml xml;
Set @xml = (
    Select (
        Select id As [@id]
        From tbUsers
        Where Name = 'John_Stack'
        For XML Path('user'), Type)
    For XML Path('users'), Type);
于 2012-06-22T23:50:58.740 回答