SQL Server 的 varbinary 数据类型可以存储哪些数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3275548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:52:25  来源:igfitidea点击:

What data can be stored in varbinary data type of SQL Server?

sqlsql-servertypesvarbinary

提问by Fraz Sundal

I have a table in which the userpassword field have varbinary datatype, So I'm confused that in which form should I save the data into userpassword field because when I save varchar data it gave me error.

我有一个表,其中 userpassword 字段具有 varbinary 数据类型,所以我很困惑我应该以哪种形式将数据保存到 userpassword 字段中,因为当我保存 varchar 数据时,它给了我错误。

回答by Andomar

A varbinarycolumn can store anything. To store a string in it, you'd have to cast it to varbinary:

varbinary列可以存储任何东西。要在其中存储字符串,您必须将其强制转换为varbinary

declare @t table (id int identity, pwd varbinary(50))
insert into @t (pwd) values (cast('secret' as varbinary(50)))

But for a password, a varbinarycolumn usually stores a hash of some kind. For example, a SHA1 hash using the HashBytesfunction:

但是对于密码,varbinary列通常存储某种散列。例如,使用HashBytes函数的 SHA1 哈希:

insert into @t (pwd) values (HashBytes('sha1', 'secret'));

Storing a one-way hash instead of the real password is more secure. You can check if the password matches:

存储单向哈希而不是真实密码更安全。您可以检查密码是否匹配:

select * from @t where pwd = HashBytes('sha1', 'secret')

But there is no way you can retrieve the password by looking at the table. So only the end user knows his password, and not even the DBA can retrieve it.

但是您无法通过查看表格来检索密码。因此只有最终用户知道他的密码,甚至 DBA 也无法检索它。

回答by Chris Diver

You will need to explicitly cast the VARCHAR.

您将需要显式转换 VARCHAR。

SELECT CAST(N'Test' as VARBINARY)

SQL Server error message says.

SQL Server 错误消息说。

Implicit conversion from data type varchar to varbinary is not allowed.

不允许从数据类型 varchar 隐式转换为 varbinary。

回答by gbn

SQL Server requires an explicit conversion from varchar to varbinary, as per the big table on CAST and CONVERT in MSDN

根据 MSDN 中 CAST 和 CONVERT 上的大表,SQL Server 需要从varchar 到 varbinary的显式转换

The table will have a varbinary column to store hashed values as per sys.sql_logins

该表将有一个 varbinary 列来根据sys.sql_logins存储散列值

回答by Loay Oraby

SELECT CAST(N'Test' as VARBINARY)

------you have to give it a size ---------->

------你必须给它一个尺寸 ---------->

SELECT CAST(N'Test' as VARBINARY(30))