在mssql中将选择结果分配给存储过程中的变量?

时间:2014-01-16 13:38:21

标签: sql-server stored-procedures

我有以下选择:

SELECT School_Type,COUNT(ID) from Schools where City_ID = 1 group by School_Type

我得到了结果:

10 | 3
20 | 4
30 | 14

我想把结果放在:

  • 输入10到变量@ElementarySchools
  • 输入20到变量@HighSchools
  • 输入30到变量@ProfessionalSchools

并从存储过程中获取此结果。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

这样的事情? :)

declare @val varchar(max) = ''
select @val = @val + rtrim(foryear) + ' | ' + RTRIM( COUNT(*)) + ',' from mytable
group by ForYear

select @val

答案 1 :(得分:0)

使用像这样的表变量:

declare @tmp table (School_Type int, School_Count int)
insert into @tmp
SELECT School_Type,COUNT(ID) from Schools where City_ID = 1 group by School_Type

select @ElementarySchools=School_Count from @tmp where School_Type=10
select @HighSchools=School_Count from @tmp where School_Type=20
select @ProfessionalSchools=School_Count from @tmp where School_Type=30