sql - 在 SQL 表中动态存储值
问题描述
我正在尝试在 SQL 中动态创建一个variable
or table
,它将存储不同的值作为另一个sql
查询的结果。
declare sample_table table
( values varchar(100))
insert into @sample_table values (select t1.value from my_tablw as t1 group by t1.value);
假设distinct
列中的值value
可以从表查询更改为另一个表查询,我想将此查询的结果存储在用户定义的变量/表中,以后可以在另一个查询中使用。
解决方案
根据您稍后可以使用的定义,您可以使用本地临时表或表变量...。您只需稍微更改语法以不使用,values
因为您是从查询结果中插入的。我还在DISTINCT
下面使用了比GROUP BY
没有聚合函数更清晰的方法。
declare sample_table table ([values] varchar(100))
insert into @sample_table
select distinct t1.value
from my_tablw as t1
--one way to use it
select *
from newTable
where columnVal in (select * from @sample_table)
--another way to use it
select at.*
from anotherTable at
inner join @sample_table t on
t.column = at.column
--and another way...
select f.*
from finalTable f
where exists (select * from @sample_table t where t.column = f.column)
如果您需要在当前批处理范围之外使用它,则需要使用持久表或全局临时表。