如何在SQL中从一个条件设置变量并在另一个条件中使用

时间:2019-01-02 04:57:27

标签: sql sql-server

我有以下查询:

DECLARE @someValue INT

SELECT * 
FROM dummytable
WHERE EXISTS (SELECT @someValue = somecolumn 
              FROM dummytable2 
              WHERE tableindex = dummytableIndex) 
  AND EXISTS (SELECT * 
              FROM dummytable3 
              WHERE somecolumn = @someValue)
  AND SomeDummyFunctionReturnsBool(@someValue) = 1

错误是不允许该语句@someValue = somecolumn

我无法设置@someValue的值,以后再使用。

我尝试将错误行替换为@someValue AS somecolumn,但是在打印@someValue时,它报告了NULL

如果支持此功能,请分享并实现该解决方案。

2 个答案:

答案 0 :(得分:1)

有一个不使用变量的选项,例如,如下重写查询

select * 
  from dummytable
 where exists (select 1 
                 from dummytable3 t3
                 join dummytable2 t2
                   on t3.somecolumn=t2.somecolumn
                where t2.uniqueindex= dummytable.tableindex
               )   

答案 1 :(得分:0)

我暂时尝试过此作为解决方案。更多符合乔治的答案

DECLARE @someValue INT
select * from dummytable
where exists 
 (select somecolumn 
  from dummytable2  dt2
  where tableindex=dummytableIndex
     and exists (select * from dummytable3 where somecolumn = dt2.somecolumn 
     and SomeDummyFunctionReturnsBool(@someValue) = 1
   )