Can I concatenate a virtual column in a view?

≡放荡痞女 提交于 2019-12-12 18:27:55

问题


Unfortunately, I have plaintext passwords in a database. I want to pass these plaintext values around as little as possible for, say, comparisons and updates. To this end, I'm trying to create a view of my Users table that excludes the plaintext passwords and instead provides a hashed value of that password.

Here's my current SQL Server view, which doesn't work:

SELECT CAST(CAST(32768 * RAND() AS INT) AS NVARCHAR) AS PasswordSalt
       HashBytes('SHA1', PasswordSalt + u.Password) AS PasswordHash
FROM dbo.Users AS u

I'd be happy to hear about alternatives to this approach, but otherwise the problem seems to be concatenating the virtual column PasswordSalt with.. anything. For instance, the following simple view works:

SELECT u.Login AS Column1, u.Login + 'b' AS Column2

but this one does not:

SELECT u.Login AS Column1, Column1 + 'b' AS Column2

The error I'm receiving from Management Studio is

Invalid column name 'Column1'.

Thanks in advance for any ideas about what I'm doing wrong!


回答1:


The problem is occurring because the FROM clause of your statement indicates that the data to be selected comes from the Users table, but the SELECT part references a column named PasswordSalt. SQL Server cannot find a column with this name on the Users table, hence the error.

Alternative approach may be to generate the Salt in a subquery. For example

SELECT x.PasswordSalt,  HashBytes('SHA1', x.PasswordSalt + x.Password) AS PasswordHash FROM ( SELECT  CAST(CAST(32768 * RAND() AS INT) AS NVARCHAR) AS PasswordSalt, Password FROM dbo.Users) x




回答2:


What about

SELECT CAST(CAST(32768 * RAND() AS INT) AS NVARCHAR) AS PasswordSalt 
       HashBytes('SHA1', CAST(CAST(32768 * RAND() AS INT) AS NVARCHAR) + u.Password) AS PasswordHash 
FROM dbo.Users AS u 


来源:https://stackoverflow.com/questions/2375575/can-i-concatenate-a-virtual-column-in-a-view

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