Writing a SQL Server database object, I was faced with the problem of to serialize some data to XML and to get the count of rows being serialized.
I wrote something like this using a CTE:
-- Way III
begin
declare @TmpUno as table (
uno int, dos varchar(max)
)
declare @RC int
declare @XmlSerializedData xml
insert into @TmpUno (uno, dos)
values (1, 'uno'), (2, 'dos')
-- Way III :
-- * Serialization data is stored in a local variable
-- * Rows count is stored in a local variable
;with c1 as
(
select uno, dos
from @TmpUno
)
select
@XmlSerializedData = (select * from c1 for xml path('row')),
@RC = (select count(1) from @TmpUno)
-- But is this the optimal way?
select 'Way III:' as way,
@XmlSerializedData as [@XmlSerializedData],
@RC as [@RC]
end
For a small table and low number of requests, that would be enough to solve the problem, but consider now to evaluate if this is this the optimal way. Execution plan look like this
Showing that, in effect two table scans are performed (circled blue)
For optimization, my question: ¿Is there a way to serialize and to count the rows being serialized, and store both results (the xml, and the rouwcount) into script local variables using only one statement, or performing only one table scan?


Simply use @@rowcount. eg
This will send an XML stream to the client followed by a single-row single-column resultset.