如何针对一系列值对运行查询并将结果存储在临时表中?

时间:2011-12-13 14:45:27

标签: sql tsql parameters parameter-passing

假设我有一个值数组:

(A1,a1,A2,a2,A3,a3,A4,a4 .....,An,an)

如何针对(A1,a1 .....,An,an)对自动执行以下TSQL查询

SELECT COUNT (1)
FROM food
WHERE calories = Ai AND ingredient = ai --i = {1..n}

那么(Ai,ai){i = 1..n}得到的每个计数都会存储在临时表中吗?

由于

2 个答案:

答案 0 :(得分:1)

您可以使用动态SQL执行此操作,如下所示:

declare @count int, @limit int
select @count = 0, @limit = 5 -- limit is n

declare @sqlcmd varchar(300)

-- table
create table #result (
combination varchar(10),
total int
)

while @count < @limit
begin
  select @sqlcmd = 'insert into #results select distinct "(" + ingredient + "," + calories + ")", count(*) from food where calories = A' + convert(varchar, @count) + ' and ingredient = a' + convert(varchar, @count)

  exec(@sqlcmd)

  select @count = @count + 1
end

答案 1 :(得分:1)

将数组中的值插入临时表(稍后我将使用相同的结果):

create table #pairs (
    calories    varchar(50),
    ingredient  varchar(50),
    count       int
)

然后,我们可以一步完成结果:

UPDATE p
SET count = x.count
FROM #pairs p inner join
    (   SELECT f.calories, f.ingredient, COUNT(*) as count
        FROM food f inner join
            #pairs p ON f.calories = p.calories and f.ingredient = p.ingredient
        GROUP BY f.calories, f.ingredient
    ) x ON p.calories = x.calories and p.ingredient = x.ingredient


select * from #pairs