question

udhaya avatar image
udhaya asked

Convert Password nvarchar() to binary datatype in sql

I want to convert Password from varchar to binary. I have the query like, SELECT 'INSERT INTO Table2(Username,password)values('+ IsNull(''''+wl.UserName+'''', 'NULL')+','+ HASHBYTES('MD5',ISNULL(wl.Password,'NULL'))+')' But i have **error** when i execute the above code, The data types nvarchar and varbinary are incompatible in the add operator. I need your help. My query is correct. why it is show like that.
sql-server-2008sql-serverselecthash
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Kev Riley avatar image
Kev Riley answered
You are trying to build a string that contains the whole insert query, so you need to convert the binary into a string using convert(varchar(max),HASHBYTES('MD5',ISNULL(w1.Password,'NULL')),1) so the whole query is SELECT 'INSERT INTO Table2(Username,password)values('+ IsNull(''''+w1.UserName+'''', 'NULL')+','+ convert(varchar(max),HASHBYTES('MD5',ISNULL(w1.Password,'NULL')),1)+')' Alternatively, don't use dynamic sql: INSERT INTO Table2(Username,password) select IsNull(w1.UserName, 'NULL'), HASHBYTES('MD5',ISNULL(Password,'NULL')) from w1
5 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

udhaya avatar image udhaya commented ·
Thanks.i want clarification. What is ISNULL(w1.Password,'NULL')),1) Here 1 is there. why use 1 here?
0 Likes 0 ·
Kev Riley avatar image Kev Riley ♦♦ commented ·
It's the *style* parameter for the convert function. See here : http://msdn.microsoft.com/en-us/library/ms187928(v=sql.100).aspx and scroll down to **Binary Styles**
0 Likes 0 ·
udhaya avatar image udhaya commented ·
Actually, ISNULL(w1.Password,'NULL') this query is convert NULL to MD5. so it is show "0x351A64C5DE93984A0B71280CECA8B464" like that where NULL values there. Is this one correct way or not?Please help me.
0 Likes 0 ·
Kev Riley avatar image Kev Riley ♦♦ commented ·
take the isnull outside of the HASHBYTES function, as isnull(convert(varchar(max),HASHBYTES('MD5',Password),1),'NULL') This will change any null-valued passwords to the sting 'NULL' - is that what you want?
0 Likes 0 ·
udhaya avatar image udhaya commented ·
Thanks. It is working
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.