简体   繁体   中英

SQL query not working as expected

I am using the standard ASP.NET Membership table structure in SQL Server and was doing a bit of manually querying in Management studio and ran this query

SELECT *
FROM [aspnet_Users]
WHERE UserId = '2ac5dd56-2630-406a-9fb8-d4445bc781da&cID=49'

Notice the &cID=49 at the end - I copied this from a querystring and forgot to remove that part.

However, to my surprise it returned the data correctly (there is a user with the ID 2ac5dd56-2630-406a-9fb8-d4445bc781da) - any idea why this works? To my mind it should not match or probably more likely throw an error as it shouldn't be able to convert to a Guid?

The uniqueidentifier type is considered a character type for the purposes of conversion from a character expression, and therefore is subject to the truncation rules for converting to a character type. That is, when character expressions are converted to a character data type of a different size, values that are too long for the new data type are truncated .

Because the uniqueidentifier type is limited to 36 characters , the characters that exceed that length are truncated.

Note that above is quoted from MSDN

The parser is (remarkably) lenient when converting string literals to guid literals, apparently:

SELECT CAST('E63F4FFC-8574-428B-B6B8-95CFCA05ED52' AS uniqueidentifier)
SELECT CAST('E63F4FFC-8574-428B-B6B8-95CFCA05ED52a' AS uniqueidentifier)
SELECT CAST('E63F4FFC-8574-428B-B6B8-95CFCA05ED52-!' AS uniqueidentifier)
SELECT CAST('E63F4FFC-8574-428B-B6B8-95CFCA05ED52~#5' AS uniqueidentifier)
SELECT CAST('E63F4FFC-8574-428B-B6B8-95CFCA05ED52$3%] ' AS uniqueidentifier)

all give the same result, no errors.

This is documented behaviour , so we can't really complain:

The following example demonstrates the truncation of data when the value is too long for the data type being converted to. Because the uniqueidentifier type is limited to 36 characters, the characters that exceed that length are truncated.

 DECLARE @ID nvarchar(max) = N'0E984725-C51C-4BF4-9960-E1C80E27ABA0wrong'; SELECT @ID, CONVERT(uniqueidentifier, @ID) AS TruncatedValue; 

Here is the result set.

 String TruncatedValue -------------------------------------------- ------------------------------------ 0E984725-C51C-4BF4-9960-E1C80E27ABA0wrong 0E984725-C51C-4BF4-9960-E1C80E27ABA0 (1 row(s) affected) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM