【问题标题】:Assigning select results into variable in stored procedure in mssql?将选择结果分配给mssql存储过程中的变量?
【发布时间】:2014-01-16 22:22:47
【问题描述】:

我有以下选择:

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

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

我该怎么做?

【问题讨论】:

  • 如果你想从存储过程中返回这些值,你为什么要把它分配给一个变量?这些是 SP 的输出变量吗?

标签: sql-server stored-procedures


【解决方案1】:

像这样? :)

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

select @val

【讨论】:

    【解决方案2】:

    使用这样的表变量:

    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
    

    【讨论】:

      猜你喜欢
      • 2023-01-14
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多