[英]How to iterate through sql table and fetch distinct values from another into a result table
I have a set of tables that control a client's budget in a monthly basis. 我有一组表来控制客户每月的预算。 This are the relationships created:
这是创建的关系:
Right now, I'm trying to create a procedure that will bring the distinct "rubro" field from the table [dbo].[Ppto_IngresosRubros] according to the user that is currently logged ([dbo].[Clientes_Usuarios]) And the budgets that he/she has created in [dbo].[Ppto_Master] 现在,我正在尝试创建一个过程,该过程将根据当前登录的用户([dbo]。[Clientes_Usuarios])和预算从表[dbo]。[Ppto_IngresosRubros]中带出单独的“ rubro”字段。他/她在[dbo]中创建的人。[Ppto_Master]
The [dbo].[Ppto_IngresosRubros] has the following data stored in it: [dbo]。[Ppto_IngresosRubros]中存储了以下数据:
ID IdPpto Rubro
3 4 Ventas desarrollo tecnológico
4 4 Ventas diseño estratégico
5 5 Ventas desarrollo tecnológico
5 5 Ventas diseño estratégico
The table [dbo].[Ppto_Master] has the following data: 表[dbo]。[Ppto_Master]具有以下数据:
ID IdCliente IdModulo FechaPpto
4 1 1 2018-01-01
5 1 1 2018-02-01
The code I have so far will bring me the desired result but in separeted set of tables, so I can't use it to populate a repeater (in the project's view - ASP.Net WebForms VB): 到目前为止,我得到的代码将为我带来预期的结果,但会出现在分散的表集中,因此我无法使用它来填充转发器(在项目视图中-ASP.Net WebForms VB):
And what I need is: 我需要的是:
Rubro
Ventas desarrollo tecnológico
Ventas diseño estratégico
This is my code: 这是我的代码:
DECLARE @usuario varchar(max) = 'eduardo@conceptod.co'
DECLARE @idcliente int
SET @idcliente =
(
SELECT
[W1].[ID]
FROM [dbo].[Clientes_Info_W1] [W1]
INNER JOIN
[dbo].[Clientes_Usuarios] [U]
ON [W1].[ID] = [U].[IdCliente]
WHERE
([U].[CorreoElectronico] = @usuario)
)
DECLARE @MyCursor CURSOR;
DECLARE @idppto int;
BEGIN
SET @MyCursor = CURSOR FOR
(
SELECT
[M].[ID]
FROM [dbo].[Ppto_Master] [M]
WHERE
([M].[IdCliente] = @idcliente)
)
OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @idppto
WHILE @@FETCH_STATUS = 0
BEGIN
(
SELECT
DISTINCT([I].[Rubro])
FROM [dbo].[Ppto_IngresosRubros] [I]
WHERE
([I].[ID] = @idppto)
)
FETCH NEXT FROM @MyCursor
INTO @idppto
END;
CLOSE @MyCursor ;
DEALLOCATE @MyCursor;
END;
Help! 救命! Thanks!
谢谢!
It was solved through a Join: 它是通过Join解决的:
CREATE PROCEDURE [dbo].[Ppto_IngresosRubros_Rubros_Tips_IdCliente]
(
@usuario varchar(max)
)
AS
BEGIN
DECLARE @idcliente int
SET @idcliente =
(
SELECT
[W1].[ID]
FROM [dbo].[Clientes_Info_W1] [W1]
INNER JOIN
[dbo].[Clientes_Usuarios] [U]
ON [W1].[ID] = [U].[IdCliente]
WHERE
([U].[CorreoElectronico] = @usuario)
)
SELECT
DISTINCT TOP(5) ([I].[Rubro]) AS [Rubro]
FROM [dbo].[Ppto_IngresosRubros] [I]
INNER JOIN
[dbo].[Ppto_Master] [M]
ON [I].[IdPpto] = [M].[ID]
INNER JOIN
[dbo].[Clientes_Info_W1] [W1]
ON [M].[IdCliente] = [W1].[ID]
WHERE
([W1].[ID] = @idcliente);
END
GO
Thanks! 谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.