Not able to compare columns in SQL Server

柔情痞子 提交于 2020-01-16 10:03:27

问题


I am using the following SQL code to compare two nvarchar columns. But the code is showing incorrect results:

SELECT 
    DP.NAME, DP.sid, SU.sid,
    CASE 
       WHEN DP.sid = SU.sid  
          THEN 'TRUE' 
          ELSE 'FALSE' 
    END AS DESDIREDRESULT
FROM 
    #SQLLOGINS DP
INNER JOIN 
    SYS.sysusers SU ON DP.name COLLATE DATABASE_DEFAULT = SU.name COLLATE DATABASE_DEFAULT

In the code, I am doing a inner join of a temp table, #SQLLOGINS, with sys.sysusers. This temp table includes NAME and SID of sys.sqllogins.

I am facing an issue, while both the SID is same, it should be 'TRUE' in the output. Screenshot attached. But it's returning FALSE.

I am not sure where I am wrong here in comparing the SID columns.


回答1:


You are mixing the types. Try this out:

DECLARE @mockupTable TABLE(ID INT IDENTITY,SomeString VARCHAR(100),SomeBinary VARBINARY(100));

INSERT INTO @mockupTable VALUES('0x1234',0x1234);
INSERT INTO @mockupTable VALUES(0x6565,0x6565); --implicit cast!
INSERT INTO @mockupTable VALUES('ee', CAST('ee' AS VARBINARY(100))) --explicit cast!

SELECT *, CASE WHEN SomeString=SomeBinary THEN 'TRUE' ELSE 'FALSE' END FROM @mockupTable;

The result

+----+------------+------------+--------------------+
| ID | SomeString | SomeBinary |                    |
+----+------------+------------+--------------------+
| 1  | 0x1234     | 0x1234     | FALSE              |
+----+------------+------------+--------------------+
| 2  | ee         | 0x6565     | TRUE               |
+----+------------+------------+--------------------+
| 3  | ee         | 0x6565     | TRUE               |
+----+------------+------------+--------------------+

What happens here?

The first row looks the same, but isn't, while the 2 and 3 are obviously different but return they are the same?

The reason: The binary value 0x1234 and the string 0x1234 are not the same, although the look as if they were.

Just try SELECT CAST('0x1234' AS VARBINARY(100)). The result is 0x307831323334 which is - obviously! - not the same as 0x1234. It is a list of codes actually: 30 (0), 78 (x), 31 (1), 32 (2), 33 (3), 34 (4).

But in row 2 and 3 you can see, that the binary value of a string can be compared with a real binary. Doing this, you can see that the string ee has two small letter e, with the ASCII code 65. So 0x6565 translates to ee.




回答2:


There are typically 3 causes of things like this:

  1. Hidden characters (line feeds etc)

  2. Incompatible data types or code pages

  3. Trailing spaces

I suggest you cast/convert both attributes and throw a trim in for good measure.



来源:https://stackoverflow.com/questions/57982071/not-able-to-compare-columns-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!