gpt4 book ai didi

sql - 如何在 SQL Server 中声明数组变量?

转载 作者:行者123 更新时间:2023-12-02 22:35:11 24 4
gpt4 key购买 nike

我想在存储过程中执行一个查询,该查询应该循环所有数组值。

例如:

declare arrayStoreID={1001,2400,2001,5000}

for(int i=0;i<arrayStoreID.length;i++)
{
select
col_name1,col_name2
into
@temp_table
from
Table_Name
Where
storeID=arrayStoreID[i]
}

我想像上面那样执行。谢谢

最佳答案

第一个商店 ID temporary table如下

create table #Table_Name(storeID INT, col_name1 varchar(50), col_name2 varchar(50))
insert into #Table_Name values
(1001, 'Test1', 'Test2'),
(5000, 'Rest1', 'Rest2'),
(1122, 'Best1', 'Best2')

然后您可以加入要从中获取记录的表,如下所示, 这个方法比通过loop要好得多如果您的要求不是more complicated实际情况

select t.col_name1,
t.col_name2
INTO #new_table
from #Table_Name t
inner join #tmp_ids ti on ti.id = t.storeID

它将返回与 IDs 匹配的两条记录并插入到 #new_table上面

select * from #new_table

OUTPUT:
col_name1 col_name2
Test1 Test2
Rest1 Rest2

Note: you can use `table variable` as well

关于sql - 如何在 SQL Server 中声明数组变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41671882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com