This is my test table:
CREATE TABLE [General].[Test]
(
[Name] NVARCHAR(20) NOT NULL,
[SSN] CHAR(10) NOT NULL,
CONSTRAINT [UK_Test_SSN]
UNIQUE NONCLUSTERED ([SSN]) WITH (IGNORE_DUP_KEY = OFF),
)
And I inserted some values:
INSERT INTO [General].[Test] ([SSN], [Name]) VALUES (N'901223476', N'Lol1');
INSERT INTO [General].[Test] ([SSN], [Name]) VALUES (N'2591830061', N'Lol2');
INSERT INTO [General].[Test] ([SSN], [Name]) VALUES (N'4431776273', N'Lol3');
INSERT INTO [General].[Test] ([SSN], [Name]) VALUES (N'987654321', N'Lol4');
INSERT INTO [General].[Test] ([SSN], [Name]) VALUES (N'123456789', N'Lol5');
INSERT INTO [General].[Test] ([SSN], [Name]) VALUES (N'0123456789', N'Lol6');
INSERT INTO [General].[Test] ([SSN], [Name]) VALUES (N'0012345678', N'Lol7');
INSERT INTO [General].[Test] ([SSN], [Name]) VALUES (N'123', N'Lol8');
And the first SELECT query:
SELECT
CASE
WHEN [T].[SSN] LIKE REPLICATE('[0-9]',10) THEN [T].[SSN]
ELSE 1000000000 + ROW_NUMBER() OVER(ORDER BY [T].[Name]) END AS [SSN]
FROM [General].[Test] AS [T];
GO
And the second query:
SELECT [T].[SSN] FROM [General].[Test] AS [T];
The ambiguity that I can’t understand is about rows 6 and 7 whose [SSN] values start with 0
So for example about 6th row the first query returns 123456789 and second query return 0123456789, can anyone explain why? And I really need to get the real value of 0123456789 in the first query, what can I do?
You have two different datatypes being returned from your first column in the first query – in the first case, the
CHAR(10)of the[SSN]is returned, in theELSEcase a large INT number. That’s why SQL Server needs to convert one of the two datatypes to the other.What you need to do, if you want to get back the
CHAR(10), is toCASTthe second expression to that datatype:Then you get back your
CHAR(10)values – and nothing gets converted to a INT (or BIGINT) and thus looses it’s leading zeroes: