如何在select(SQL Server)中使用变量?


8

如果我想计算一列并将结果用于多于一列,如何在不进行两次计算的情况下做到这一点?

例:

SELECT LOWER(SUBSTRING([NAME], 4, 100)) + '@somedomain.com' as EMail
      ,hashbytes('SHA1', LOWER(SUBSTRING([NAME], 4, 100)) + '@somedomain.com') as HashedEmail
FROM sometable

如何避免在不使用多个选择的情况下写两次?

Answers:


13

派生表

SELECT
    EMail,
    hashbytes('SHA1', EMail) AS HashedEmail
FROM
    (
    SELECT LOWER(SUBSTRING([NAME], 4, 100)) + '@somedomain.com' as EMail
    FROM sometable
   ) foo

或CTE:

;WITH cEMail AS
(
    SELECT LOWER(SUBSTRING([NAME], 4, 100)) + '@somedomain.com' as EMail
    FROM sometable
)
SELECT
    EMail,
    hashbytes('SHA1', EMail) AS HashedEmail
FROM
    cEMail

但是,在这种情况下,我会考虑使用已计算哈希值的计算列


只要每个请求的域都是静态的和动态的,“计算机专栏”就是一个了不起的主意。
罗伯特·米勒

3

首先,我认为您想编写哈希字节而不是haststring。hashstring没有SQL函数。

这是将给您想要的代码,我希望。

DECLARE @yourvariable nvarchar (50) =  '@somedomain.com';

SELECT LOWER(SUBSTRING([NAME], 4, 100)) + @yourvariable  as EMail
      ,HashBytes('SHA1', LOWER(SUBSTRING([NAME], 4, 100)) +  @yourvariable) as HashedEmail 
FROM sometable;
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.