将多个名称替换为变量

问题描述 投票:0回答:2

我需要为多个名称设置多个变量,例如@ nom2(@ Real2),@ nom3(@ Real3)。

我如何在不重复所有代码行(总和)的情况下执行此操作,其中仅更改人名?我对动态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```


sql sql-server variables dynamic
2个回答
1
投票

根据给定的信息,我建议:

代替定义变量,您可以创建一个表并向其中插入数据并将其连接到查询,如下所示

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并对其进行分组,然后选择RealColnom


0
投票

您可以定义表变量,并保留名称并更新实值,如下所示。以下是未经测试的代码,因为您没有提供示例值。但是,您应该了解一下。

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的Real值。如果您要在多个批次之间坚持下去,可以使用临时表。

select Real from @NomReal Where nom = 'Pedro' 
© www.soinside.com 2019 - 2024. All rights reserved.