As I understand, in the query below, the value of an existing column should remain if the first value in NULLIF
is an empty string. In my actual query, those are variables, but I have placed actual values in the query to make it shorter.
ISNULL(NULLIF(N'', N''), Pwd) => ISNULL(NULL, Pwd) => Pwd
Instead, what is happening is the first character is being set as the value. Run query below and keep an eye on the value of Pwd.
DECLARE @tblHello TABLE (
UserID INT NOT NULL IDENTITY(1,1),
FirstName VARCHAR(50),
LastName VARCHAR(50),
CompanyName VARCHAR(80),
Pwd VARCHAR(100) NOT NULL,
Email VARCHAR(100) NOT NULL,
CreatedDate DATE NOT NULL DEFAULT SYSUTCDATETIME(),
LastUpdated DATE NOT NULL DEFAULT SYSUTCDATETIME(),
isActive BIT NOT NULL DEFAULT(1)
)
INSERT INTO @tblHello (FirstName, LastName, CompanyName, Pwd, Email)
VALUES ('First', 'Last', 'Testing this', 'This is the password', 'test@email.com')
UPDATE @tblHello
SET
Email = ISNULL(NULLIF(N'testuser58@email.com', ''), Email),
FirstName = ISNULL(NULLIF(N'Updated', ''), FirstName),
Pwd = ISNULL(NULLIF(N'', N''), Pwd),
LastName = ISNULL(NULLIF(N'YmFaADIDaQVauHF', ''), LastName),
isActive = ISNULL(NULLIF(1, ''), isActive),
CompanyName = ISNULL(NULLIF(N'Testing Co', ''), CompanyName)
WHERE UserID = 1
SELECT *
FROM @tblHello
I get the following result for Pwd: (rest of columns ommitted)
Pwd CompanyName Email
T Testing Co testuser58@email.com
This happens with or without the pre-pended 'N'. Why is this happening?
isnull
takes its type from the first parameter, which in your case is an empty string i.e.varchar(1)
. Tryisnull(NULLIF(N' ', N''),'test')
for comparison. Changeisnull
tocoalesce
to fix.