Solibulo

Uninteresting things

uniqueidentifier in SQL xml type are upper case strings but C# Guid are lower case strings

by softlion 20. November 2008 10:00

A modern way to put a list of IDs in a stored procedure parameter is to type the parameter as xml (instead of the conventional CSV like varchar). With the nodes() method you can inner join directly the xml 'table' with one of your database table without first filling a temporary table. And building the xml fragment with LINQ TO XML (ie: XDocument class) is a piece of cake.

 

If these ids are C# Guids (or tsql uniqueidentifier) and you optimize your query (like msdn tells you), you may fall in the uppercase/lowercase trap.

 

-- Optimized query (working)
select * from MyGames a
left join MyUsers b on a.Winners.exist('//winner[upper-case(@userId)=sql:column("b.UserId")]')=1

 

In this XQuery optimized comparison, T-SQL converts a uniqueidentifier to an upper case string. The Winners xml column has been filled using C# XDocument, which uses by default the C# method Guid.ToString() to convert a guid ... to lowercase.

 

So we have SQL converting by default uniqueidentifier to uppercase, and C# converting by default Guid to lowercase.
If you rely on defaults any comparison done between uniqueidentifier in this cutting edge xml/sql technology then it will not work.



Notes:
The xml type is a new native type available since SQL Server 2005. I use it essentially to simplify the model for 1-N relations by storing ids of the N table in a field of the 1 table instead of creating this dummy relationship table I always hated. This without giving up performance, as long as you setup the new special xml indexes for the xml typed field and provide the XSD schema to SQL. See references below for the full documentation.


A uniqueidentifier is a 16 bytes (128 bits) value which is used by the default implementation of User/Membership provider of the ASP.NET framework for all unique IDs.



With the xml data type, SQL 2005 introduced "methods" that can be used to efficiently query the xml data and use it as if it was a normal table : exists(..), value(..), ...
A common parameter for these methods is an XQuery string, where XQuery is a SQL Server specific language based on XPath, with at least 2 useful efficients extensions in the sql namespace:
sql:variable(..) which is replaced by the value of an existing variable
sql:column(..) which is replaced by the value of any table row available in the t-sql query




References:
SQL Server xml data type

XML indexes
XML type query methods
XQuery language reference

 

Tags: ,