How to update a varbinary field with a specific value?

僤鯓⒐⒋嵵緔 提交于 2019-11-30 08:28:52

Try this:

UPDATE dbo.Login
SET
  Salt=CAST('bPftidzyAQik' AS VARBINARY),
  Password=0x2B89C2954E18E15759545A421D243E251784FA009E46F7A163926247FDB945F85F095DBB1FFF5B2B43A6ADAE27B8C46E176902412C4F8943E39528FF94E0DD5B
WHERE LoginID=10947

(you don't need to cast a string storing a hex value into varbinary - that's just what it is by default, without the quotes)

The question is, how are you generating that password hex value, and are you using the same encoding to generate it as you are to read it? If you are planning on converting that data back into a string, you'll need some code to do so. Here's a function I wrote that does this:

CREATE FUNCTION ConvertBinary
(  
    @value AS varbinary(max)
) RETURNS VARCHAR(MAX) AS BEGIN  

    DECLARE @result AS varbinary(max),
            @result2 AS varchar(max),
            @idx AS bigint;

    IF @value IS null
        return null;

    SELECT @result = @value;  
    SELECT @result2 = '';
    SELECT @idx = 1;

    WHILE substring(@result, @idx, 1) != 0 AND @idx < len(@result)
        BEGIN
            SET @result2 = @result2 + cast(substring(@result,@idx,1) as char(1));  
            SET @idx = @idx + 1;
        END

    RETURN @result2;  

END 

I don't know how helpful this will be for you, though, since it's very possible that whatever app is using these fields is handling the values differently than this function expects. For the record, this function takes a varbinary value which was originally utf-8 string, and returns the varchar value of that string. Good luck!

Since you are using 2008, try this:

UPDATE dbo.Login 
SET 
    Salt=CAST('bPftidzyAQik' AS VARBINARY),   
    Password=CONVERT(VARBINARY(MAX), '0x2B89C2954E18E15759545A421D243E251784FA009E46F7A163926247FDB945F85F095DBB1FFF5B2B43A6ADAE27B8C46E176902412C4F8943E39528FF94E0DD5B', 1) 
WHERE LoginID=10947 

(http://blogs.msdn.com/b/sqltips/archive/2008/07/02/converting-from-hex-string-to-varbinary-and-vice-versa.aspx)

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