替换变量中的多个名称

blpfk2vs  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(325)

我需要为更多的名称设置多个变量,例如@nom2(@real2)、@nom3(@real3)。
我如何做到这一点而不重复所有的代码行(sum),其中只有人名更改?我有一种感觉,动态sql就是这样,但说实话,我真的不知道该怎么做。

use Performance
go
declare @nom1 nvarchar(20)
declare @nom2 nvarchar(20)
declare @real1 int
set @nom1 = 'Ricardo'
set @nom2 = 'Pedro'
set @Real1 = (select(
sum (case when [SUPERVISOR] = @nom1 and [FAMILIA] = 'MEOFIBRA' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end) +
sum (case when [SUPERVISOR] = @nom1 and [FAMILIA] = 'MEOCOBRE' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end) +
sum (case when [SUPERVISOR] = @nom1 and [FAMILIA] = 'MEOSAT' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end)) from DOC```
lsmepo6l

lsmepo6l1#

根据给定的信息,我建议:
不必定义变量,您可以创建一个表并向其中插入数据,然后将其连接到查询,如下所示

Create table tNom (nom varchar(100))

insert into tNom values
('Ricardo'), ('Pedro')

select d.[SUPERVISOR], (
sum (case when [SUPERVISOR] = t.nom and [FAMILIA] = 'MEOFIBRA' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end) +
sum (case when [SUPERVISOR] = t.nom and [FAMILIA] = 'MEOCOBRE' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end) +
sum (case when [SUPERVISOR] = t.nom and [FAMILIA] = 'MEOSAT' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end)) as SumByNom
from DOC d
left join tNom t on d.[SUPERVISOR] = t.nom
Group by d.[SUPERVISOR]

如果不再需要该表,可以创建临时表。如果需要nom以外的引用,可以在tnom表中使用额外的列realcol并按其分组,然后选择realcol和nom。
为新需求编辑:

drop table tNom
Create table tNom (nom varchar(100), SumColumn Real)

insert into tNom (nom) values 
('Ricardo'), ('Pedro')

Update t Set t.SumColumn = ColSum
From tNom t
inner join
(
    Select t.nom, 
        sum (case when [SUPERVISOR] = t.nom and [FAMILIA] = 'MEOFIBRA' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end) +
        sum (case when [SUPERVISOR] = t.nom and [FAMILIA] = 'MEOCOBRE' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end) +
        sum (case when [SUPERVISOR] = t.nom and [FAMILIA] = 'MEOSAT' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end) as ColSum
    from DOC d
    left join tNom t on d.[SUPERVISOR] = t.nom
    Group by t.nom
) q on q.nom = t.nom
nbysray5

nbysray52#

您可以定义表变量并保存名称和更新实值,如下所示。下面是未测试的代码,因为您没有提供示例值。但是,你应该明白。

DECLARE @NomReal TABLE(Nom nvarchar(20), Real int)

INSERT INTO @NomReal (Nom)
VALUES ('Ricardo'),('Pedro');

UPDATE n
SET Real = (
sum (case when [FAMILIA] = 'MEOFIBRA' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end) +
sum (case when [FAMILIA] = 'MEOCOBRE' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end) +
sum (case when [FAMILIA] = 'MEOSAT' and [EVENTO] = 'VB' then [QUANTIDADE] else 0 end))  
@NomReal AS n
INNER JOIN Doc as d
ON d.Supervisor = n.Nom

现在,您可以通过查询表变量获得每个nom的实际值。如果您想在批处理之间保持这种状态,可以使用temp表。

select Real from @NomReal Where nom = 'Pedro'

相关问题