Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help writing Stored Procedure w/Parameters 1

Status
Not open for further replies.

jcmv007

Technical User
Nov 1, 2001
88
US
USING Windows XP SP1; SQL 8

I need to create a stored procedure which displays the results of a temp table which is populated by that stored procedure. It's complex form me to write becuase it's my first SP.

to get my final results I need to run a couple of querys, lets start with Q1 and Q2 which need a parameter called @User. Q2 uses Q1 as an inner table and it (Q2) will be used in Q3. Q3 pulls the transactional data using Q2 and the parameters @AnoDesde and @AnoHasta to filter for a specific year range, the results of Q3 need to be stored in a temp table, #tp_Datos, becuase I then need to run a couple of insert querys base on it to compute subtotales, which are to be stored in that same temp table. After all the insert querys are ran I would like display all the records of #tp_Datos.

Here is the code I have written so far:

Code:
CREATE PROCEDURE sp_DatosParaSistemaAPH
(
@User int,
@AnoDesde int,  --Start Year in number format CCYY
@AnoHasta int --End Year in number format CCYY
) as

--TABLA VARIABLE PARA DEPARTAMENTOS VISIBLES
DECLARE @tv_Dptos TABLE (
	UnidadNegocio tinyint not null,
	Dpto_ID int not null,
	Departamento nvarchar(50) not null,
	DepnumHACHESYS tinyint not null)
	Insert @tv_Dptos


--Q1 query which determines the stores a user can see
		SELECT UnidadNegocio,Dpto_ID, Departamento, DepnumHACHESYS
		FROM 	tblDepartamentos
		WHERE 	UnidadNegocio=
			(select vp_unidad from tblUsers where @User = 
				(select @User from tblcurrentUser))
		UNION
		SELECT UnidadNegocio,Dpto_ID,Departamento,DepnumHACHESYS
		FROM 	tblDepartamentos
		WHERE 	Gerente Like 
			'*' + convert(varchar,(select @User from tblcurrentUser))
		UNION 	
		SELECT UnidadNegocio,Dpto_ID,Departamento,DepnumHACHESYS
		FROM 	tblDepartamentos
		WHERE 	convert(int,Reporta_A)=
			convert(int,(SELECT @User FROM tblUsers 
				     WHERE MulitipleCenter = -1 AND @User = 
				(SELECT @User FROM tblCurrentUser)))
			AND Reporta_A  IS NOT NULL		
		UNION 
		SELECT UnidadNegocio,Dpto_ID,Departamento,DepnumHACHESYS
		FROM tblDepartamentos
		WHERE 	Dpto_ID Between 
				CASE WHEN 
				(SELECT SecurityLevel FROM tblCurrentUser)=5 THEN 
				1 ELSE 0 END 
				And 
				CASE WHEN (SELECT SecurityLevel FROM tb
				lCurrentUser)=5 THEN 999 ELSE 0 END 
			or 
			Dpto_ID <>(SELECT costcenter FROM tblUsers 
				   WHERE @User = 
					(select @User from tblCurrentUser))

--Q2 query that selects the Stores and Accounts User Can See
Declare @tv_CtasVisibles Table(
	UnidadNegocio tinyint not null,
	Dpto_ID int not null,
	Departamento nvarchar(50) not null,
	GrupoCtas_ID int not null,
	GrupoDeCuentas nvarchar(50) not null,
	Centro nvarchar(8) not null,
	Depnum nvarchar(8) not null)

	Insert @tv_CtasVisibles

	SELECT 
		@tv_Dptos.UnidadNegocio,
		@tv_Dptos.Dpto_ID, 
		@tv_Dptos.Departamento, 
		T1.GrupoCtas_ID, 
		T1.GrupoDeCuentas, 
		tblDepartamentos.CentroCompleto as Centro, 
		tblDepartamentos.DepnumCompleto as Depnum
	FROM 
		tblGrupoDeCuentas as T1, @tv_Dptos 
		INNER JOIN tblDepartamentos ON 
		@tv_Dptos.Dpto_ID = tblDepartamentos.Dpto_ID
	UNION 
	
	SELECT 
		tblDepartamentos.UnidadNegocio,
		T2.Dpto_ID, 
		tblDepartamentos.Departamento, 
		T2.GrupoCtasID, 
		T1.GrupoDeCuentas, 
		tblDepartamentos.CentroCompleto as Centro, 
		tblDepartamentos.DepnumCompleto as Depnum
	
	FROM 
		tblGrupoDeCuentas AS T1 INNER JOIN tblUserAdditionalAccess AS T2 
		ON T1.GrupoCtas_ID = T2.GrupoCtasID
		INNER JOIN tblDepartamentos 
		ON tblDepartamentos.Dpto_ID = T2.Dpto_ID	
	WHERE 
		(((convert(int,@User))=(Select @User From tblCurrentUser)))


--Q3 query that selects the transactional data
select
	T4.UnidadNegocio,
	T4.GrupoCtas_ID AS 'GrupoCuentas_ID',
	T2.Cuenta_ID,
	T4.Dpto_ID,
	T1.Cuenta,
	T1.Centro,
	T1.Departamento,
	T1.Ano,
	T1.Mes,
	Sum((round((T1.Monto/1000),2)*-1)) AS Monto, 
	T1.Origen

into	#tp_Datos
from
	@tv_CtasVisibles AS T4 LEFT OUTER JOIN v_uniDatosMACOLA AS T1 ON 
			T4.Depnum = t1.Departamento AND T4.Centro = T1.Centro 
	LEFT OUTER JOIN tblCuentas AS T2 ON T2.Cuenta_Numero = T1.Cuenta 

WHERE
	t4.GrupoCtas_ID = t2.GrupoCuentas_ID AND
	T1.Ano Between @AnoDesde And @AnoHasta

GROUP BY 
	T4.UnidadNegocio,
	T4.GrupoCtas_ID,
	T2.Cuenta_ID,
	T4.Dpto_ID,
	T1.Cuenta,
	T1.Centro,
	T1.Departamento,
	T1.Ano,
	T1.Mes,
	T1.Origen

HAVING 
	Sum((round((T1.Monto/1000),2)*-1)) <>0


--Q4 query that calculates subtotals based on the data
--of #tp_Datos and inserts the result
--in the same table.
insert #tp_Datos (Centro, Departamento, Ano, Mes, Monto, Origen)
	SELECT 
	T1.Centro, T1.Departamento, T1.Ano, T1.Mes, 
	Sum(T1.Monto)+
		(SELECT Sum(sq1.Monto) FROM v_DatosParaSistemaAPH AS sq1
		WHERE 	sq1.GrupoCuentas_ID = 7 and 
			sq1.Centro = T1.Centro and 
			sq1.Departamento = T1.Departamento and 
			sq1.Ano = T1.Ano and
			sq1.Mes = T1.Mes and 
			sq1.Origen = T1.Origen
		GROUP BY 
			sq1.GrupoCuentas_ID, 
			sq1.Centro, 
			sq1.Departamento, 
			sq1.Ano, 
			sq1.Mes, 
			sq1.Origen) AS Monto, 
	T1.Origen
	FROM v_DatosParaSistemaAPH AS T1
	WHERE T1.GrupoCuentas_ID=6 
	
	GROUP BY 
	T1.Centro, T1.Departamento, T1.Ano, T1.Mes, T1.Origen
RETURN
 
Ok, as you sad, this is your first query.

So, there are some errors. Your queries may be written better, but we need to nowm for example, what you are mean with parameter @User ?

This subquery (select @User from tblcurrentUser)
brings you only rows with count of rows in 'tblcurrentUser' table and only one column containing value of @User variable.
I thing there may be some column instead of @User variable.

Instead of subqueries, use joins if it is possible.

I start to optimize your first query Q1, but I need some more info about @User variable.

SELECT UnidadNegocio,
Dpto_ID,
Departamento,
DepnumHACHESYS
FROM tblDepartamentos
INNER JOIN tblUsers ON tblUsers.vp_unidad = tblDepartamentos.UnidadNegocio
INNER JOIN tblcurrentUser ON ? -- I don't know how to join this table


Also in your last query there is missing bracket somewhere (SELECT Sum(sq1.Monto) FROM v_DatosParaSistemaAPH AS sq1


I you can, post there more informations of columns of your tables, etc.


Zhavic

---------------------------------------------------------------
In the 1960s you needed the power of two Comodore64s to get a rocket to the moon. Now you need a machine which is a vast number of times more powerful just to run the most popular GUI.
 
Zhavic,

Sorry for the mistakes I should of cuaght them, I checked the querys and here it is. The @User is a parameter I would like to use in my querys an it is an int data type.

Code:
CREATE PROCEDURE sp_DatosParaSistemaAPH
(
	@User int,
	@AnoDesde int,
	@AnoHasta int
) as

--TABLA VARIABLE PARA DEPARTAMENTOS VISIBLES
DECLARE @tv_Dptos TABLE (
	UnidadNegocio tinyint not null,
	Dpto_ID int not null,
	Departamento nvarchar(50) not null,
	DepnumHACHESYS tinyint not null)
	Insert @tv_Dptos


--Q1 query which determines the stores a user can see
		SELECT 
			UnidadNegocio,
			Dpto_ID, 
			Departamento, 
			DepnumHACHESYS
		FROM 	tblDepartamentos
		WHERE 	UnidadNegocio=
			(select vp_unidad from tblUsers where [User] = @User)
		UNION

		SELECT 
			UnidadNegocio,
			Dpto_ID,
			Departamento,
			DepnumHACHESYS
		FROM 	tblDepartamentos
		WHERE 	Gerente Like '*' + convert(varchar,@User))

		UNION 	

		SELECT 
			UnidadNegocio,
			Dpto_ID,
			Departamento,
			DepnumHACHESYS
		FROM 	tblDepartamentos
		WHERE 	convert(int,Reporta_A)=
			convert(int,(SELECT [User] FROM tblUsers 
				     WHERE MulitipleCenter = -1 AND [User] = @User))
			AND Reporta_A  IS NOT NULL		

		UNION 

		SELECT 
			UnidadNegocio,
			Dpto_ID,
			Departamento,
			DepnumHACHESYS
		FROM 	tblDepartamentos
		WHERE 	Dpto_ID Between 
				CASE WHEN 
				(SELECT SecurityLevel FROM tblCurrentUser)=5 THEN 
				1 ELSE 0 END 
				And 
				CASE WHEN (SELECT SecurityLevel FROM tblCurrentUser)=5 THEN 999 ELSE 0 END 
			or 
			Dpto_ID <>(SELECT costcenter FROM tblUsers 
				   WHERE [User] = @User)

--Q2 query that selects the Stores and Accounts User Can See
Declare @tv_CtasVisibles Table(
	UnidadNegocio tinyint not null,
	Dpto_ID int not null,
	Departamento nvarchar(50) not null,
	GrupoCtas_ID int not null,
	GrupoDeCuentas nvarchar(50) not null,
	Centro nvarchar(8) not null,
	Depnum nvarchar(8) not null)

	Insert @tv_CtasVisibles

	SELECT 
		@tv_Dptos.UnidadNegocio,
		@tv_Dptos.Dpto_ID, 
		@tv_Dptos.Departamento, 
		T1.GrupoCtas_ID, 
		T1.GrupoDeCuentas, 
		tblDepartamentos.CentroCompleto as Centro, 
		tblDepartamentos.DepnumCompleto as Depnum
	FROM 
		tblGrupoDeCuentas as T1, @tv_Dptos 
		INNER JOIN tblDepartamentos ON 
		@tv_Dptos.Dpto_ID = tblDepartamentos.Dpto_ID
	UNION 
	
	SELECT 
		tblDepartamentos.UnidadNegocio,
		T2.Dpto_ID, 
		tblDepartamentos.Departamento, 
		T2.GrupoCtasID, 
		T1.GrupoDeCuentas, 
		tblDepartamentos.CentroCompleto as Centro, 
		tblDepartamentos.DepnumCompleto as Depnum
	
	FROM 
		tblGrupoDeCuentas AS T1 INNER JOIN tblUserAdditionalAccess AS T2 
		ON T1.GrupoCtas_ID = T2.GrupoCtasID
		INNER JOIN tblDepartamentos 
		ON tblDepartamentos.Dpto_ID = T2.Dpto_ID	
	WHERE 
		(((convert(int,@User))=(Select @User From tblCurrentUser)))


--Q3 is query that selects the transactional data
select
	T4.UnidadNegocio,
	T4.GrupoCtas_ID AS 'GrupoCuentas_ID',
	T2.Cuenta_ID,
	T4.Dpto_ID,
	T1.Cuenta,
	T1.Centro,
	T1.Departamento,
	T1.Ano,
	T1.Mes,
	Sum((round((T1.Monto/1000),2)*-1)) AS Monto, 
	T1.Origen

into	#tp_Datos
from
	@tv_CtasVisibles AS T4 LEFT OUTER JOIN v_uniDatosMACOLA AS T1 ON 
			T4.Depnum = t1.Departamento AND T4.Centro = T1.Centro 
	LEFT OUTER JOIN tblCuentas AS T2 ON T2.Cuenta_Numero = T1.Cuenta 

WHERE
	t4.GrupoCtas_ID = t2.GrupoCuentas_ID AND
	T1.Ano Between @AnoDesde And @AnoHasta

GROUP BY 
	T4.UnidadNegocio,
	T4.GrupoCtas_ID,
	T2.Cuenta_ID,
	T4.Dpto_ID,
	T1.Cuenta,
	T1.Centro,
	T1.Departamento,
	T1.Ano,
	T1.Mes,
	T1.Origen

HAVING 
	Sum((round((T1.Monto/1000),2)*-1)) <>0


-- Q4 is a query that calculates subtotales based on the data
-- of #tp_Datos and inserts the result in the same table.
insert #tp_Datos (Centro, Departamento, Ano, Mes, Monto, Origen)
	SELECT 
	T1.Centro, T1.Departamento, T1.Ano, T1.Mes, 
	Sum(T1.Monto)+
		(SELECT Sum(sq1.Monto) FROM v_DatosParaSistemaAPH AS sq1
		WHERE 	sq1.GrupoCuentas_ID = 7 and 
			sq1.Centro = T1.Centro and 
			sq1.Departamento = T1.Departamento and 
			sq1.Ano = T1.Ano and
			sq1.Mes = T1.Mes and 
			sq1.Origen = T1.Origen
		GROUP BY 
			sq1.GrupoCuentas_ID, 
			sq1.Centro, 
			sq1.Departamento, 
			sq1.Ano, 
			sq1.Mes, 
			sq1.Origen) AS Monto, 
	T1.Origen
	FROM v_DatosParaSistemaAPH AS T1
	WHERE T1.GrupoCuentas_ID=6 
	
	GROUP BY 
	T1.Centro, T1.Departamento, T1.Ano, T1.Mes, T1.Origen
RETURN
 
To show all rows from #tp_Datos table at the end,
just put this befor RETURN statement

SELECT * FROM #tp_Datos -- without INTO clause

and if you run it for example from query analyzer, you can see that rows

By the way I am still getting error in your query Q2, I used alias for table variable @tv_Dptos

SELECT
a.UnidadNegocio,
a.Dpto_ID,
a.Departamento,
T1.GrupoCtas_ID,
T1.GrupoDeCuentas,
tblDepartamentos.CentroCompleto as Centro,
tblDepartamentos.DepnumCompleto as Depnum
FROM
tblGrupoDeCuentas as T1, @tv_Dptos a
INNER JOIN tblDepartamentos ON a.Dpto_ID = tblDepartamentos.Dpto_ID


Also, how are 'tblGrupoDeCuentas' and @tv_Dptos tables joined ?
Without any join condition you get all rows from 'tblGrupoDeCuentas' joined one by one to all rows from @tv_Dptos ( like CROSS join )
For example if your 'tblGrupoDeCuentas' table has 10 rows and @tv_Dptos table has 5 rows, than you get 10 * 5 = 50 rows.
You may not see that because next inner join
INNER JOIN tblDepartamentos ON
@tv_Dptos.Dpto_ID = tblDepartamentos.Dpto_ID

can filter unwanted rows, but it may take longer time to do this. Try to specify join condition for that tables, if it is posssible, or you CROSS join if you want it, it is more readable :)


Zhavic


---------------------------------------------------------------
In the 1960s you needed the power of two Comodore64s to get a rocket to the moon. Now you need a machine which is a vast number of times more powerful just to run the most popular GUI.
 
Zhavic,
I have placed 'SELECT * FROM #tp_Datos -- without INTO clause' at the end of the query before the return.

I read that you can use table variables in a store procedure and that is what I have declared in Q2. I'm open to other options, like temp tables.

'tblGrupoDeCuentas' is not join to any specific column, I need a cross join.

Here is what I get when the query is executed:

Server: Msg 156, Level 15, State 1, Procedure sp_DatosParaSistemaAPH, Line 9
Incorrect syntax near the keyword 'TABLE'.
Server: Msg 170, Level 15, State 1, Procedure sp_DatosParaSistemaAPH, Line 34
Line 34: Incorrect syntax near ')'.
Server: Msg 156, Level 15, State 1, Procedure sp_DatosParaSistemaAPH, Line 68
Incorrect syntax near the keyword 'Table'.
Server: Msg 170, Level 15, State 1, Procedure sp_DatosParaSistemaAPH, Line 127
Line 127: Incorrect syntax near '@tv_CtasVisibles'.
Server: Msg 208, Level 16, State 1, Line 1
Invalid object name '#tp_Datos'.

Thanks,
 
Hmmm, you are using SQL 8, I think that table variables are only in SQL 2000. So you need to use temp tables. ( errors in lines 9, 68, 127 )

at line 34 you need only one ')' at the end
Gerente Like '*' + convert(varchar,@User)[red])[/color]

So try to replace table variables with temp tables, like #tv_Dptos or '#tv_CtasVisibles.

The last error: Invalid object name '#tp_Datos'
is caused ( I thing ) by that previuous errors.

Zhavic





---------------------------------------------------------------
In the 1960s you needed the power of two Comodore64s to get a rocket to the moon. Now you need a machine which is a vast number of times more powerful just to run the most popular GUI.
 
Zhavic,

Ok could you then please help me write the stored procedure using temp tables? What aditional information would you need?

Thank you very much for your time and help!
 
Ok, instead of
DECLARE @tv_Dptos TABLE (
UnidadNegocio tinyint not null,
Dpto_ID int not null,
Departamento nvarchar(50) not null,
DepnumHACHESYS tinyint not null)
Insert @tv_Dptos

use this:

Code:
CREATE TABLE #tv_Dptos (
    UnidadNegocio tinyint not null,
    Dpto_ID int not null,
    Departamento nvarchar(50) not null,
    DepnumHACHESYS tinyint not null)

Than everywhere in your code replace @tv_Dptos with #tv_Dptos

The same with @tv_CtasVisibles, instead of

Declare @tv_CtasVisibles Table(
UnidadNegocio tinyint not null,
Dpto_ID int not null,
Departamento nvarchar(50) not null,
GrupoCtas_ID int not null,
GrupoDeCuentas nvarchar(50) not null,
Centro nvarchar(8) not null,
Depnum nvarchar(8) not null)

Insert @tv_CtasVisibles


use this

Code:
CREATE TABLE #tv_CtasVisibles(
    UnidadNegocio tinyint not null,
    Dpto_ID int not null,
    Departamento nvarchar(50) not null,
    GrupoCtas_ID int not null,
    GrupoDeCuentas nvarchar(50) not null,
    Centro nvarchar(8) not null,
    Depnum nvarchar(8) not null)

    Insert into #tv_CtasVisibles

Than everywhere in your code replace @tv_CtasVisibles with #tv_CtasVisibles

Zhavic

---------------------------------------------------------------
In the 1960s you needed the power of two Comodore64s to get a rocket to the moon. Now you need a machine which is a vast number of times more powerful just to run the most popular GUI.
 
Zhavic,

Thank you very much! I finally got it to work. Now how can I optimize it since it's taking more the a minute to run, I have include the final working code.

Code:
DROP PROCEDURE sp_DatosParaSistemaAPH
GO
CREATE PROCEDURE sp_DatosParaSistemaAPH
(
	@User int,
	@AnoDesde int,
	@AnoHasta int
) as

--TABLA VARIABLE PARA DEPARTAMENTOS VISIBLES
CREATE TABLE #tv_Dptos (
    UnidadNegocio tinyint not null,
    Dpto_ID int not null)


	Insert #tv_Dptos (UnidadNegocio, Dpto_ID) 

--Q1 query which determines the stores a user can see
		SELECT 
			UnidadNegocio,
			Dpto_ID 
		FROM 	tblDepartamentos
		WHERE 	UnidadNegocio=
			(select vp_unidad from tblUsers where [User] = @User)
		UNION

		SELECT 
			UnidadNegocio,
			Dpto_ID
		FROM 	tblDepartamentos
		WHERE 	Gerente Like '*' + convert(varchar,@User)

		UNION 	

		SELECT 
			UnidadNegocio,
			Dpto_ID
		FROM 	tblDepartamentos
		WHERE 	convert(int,Reporta_A)=
			convert(int,(SELECT [User] FROM tblUsers 
				     WHERE MulitipleCenter = -1 AND [User] = @User))
			AND Reporta_A  IS NOT NULL		

		UNION 

		SELECT 
			UnidadNegocio,
			Dpto_ID
		FROM 	tblDepartamentos
		WHERE 	Dpto_ID Between 
				CASE WHEN 
				(SELECT SecurityLevel FROM tblCurrentUser)=5 THEN 
				1 ELSE 0 END 
				And 
				CASE WHEN (SELECT SecurityLevel FROM tblCurrentUser)=5 THEN 999 ELSE 0 END 
			or 
			Dpto_ID <>(SELECT costcenter FROM tblUsers 
				   WHERE [User] = @User)
--SELECT * FROM #tv_Dptos GO
--drop table #tv_Dptosgo

--Q2 query that selects the Stores and Accounts User Can See
	CREATE TABLE #tv_CtasVisibles(
	    UnidadNegocio tinyint not null,
	    Dpto_ID int not null,
	    GrupoCtas_ID int not null,
	    Centro nvarchar(8) not null,
	    Depnum nvarchar(8) not null)
	
	    Insert into #tv_CtasVisibles (UnidadNegocio, Dpto_ID, GrupoCtas_ID, Centro, Depnum)

	SELECT 
		#tv_Dptos.UnidadNegocio,
		#tv_Dptos.Dpto_ID, 
		T1.GrupoCtas_ID, 
		tblDepartamentos.CentroCompleto as Centro, 
		tblDepartamentos.DepnumCompleto as Depnum
	FROM 
		tblGrupoDeCuentas as T1, #tv_Dptos 
		INNER JOIN tblDepartamentos ON 
		#tv_Dptos.Dpto_ID = tblDepartamentos.Dpto_ID
	UNION 
	
	SELECT 
		tblDepartamentos.UnidadNegocio,
		T2.Dpto_ID, 
		T2.GrupoCtasID, 
		tblDepartamentos.CentroCompleto as Centro, 
		tblDepartamentos.DepnumCompleto as Depnum
	
	FROM 
		tblGrupoDeCuentas AS T1 INNER JOIN tblUserAdditionalAccess AS T2 
		ON T1.GrupoCtas_ID = T2.GrupoCtasID
		INNER JOIN tblDepartamentos 
		ON tblDepartamentos.Dpto_ID = T2.Dpto_ID	
	WHERE 
		(((convert(int,[User]))=@User));
--select * from #tv_CtasVisiblesgo
--drop table #tv_CtasVisiblesgo

--Q3 is query that selects the transactional data
select
	T4.UnidadNegocio,
	T4.GrupoCtas_ID AS 'GrupoCuentas_ID',
	T2.Cuenta_ID,
	T4.Dpto_ID,
	T1.Cuenta,
	T1.Centro,
	T1.Departamento,
	T1.Ano,
	T1.Mes,
	Sum((round((T1.Monto/1000),2)*-1)) AS Monto, 
	T1.Origen

into	#tp_Datos
from
	#tv_CtasVisibles AS T4 LEFT OUTER JOIN v_uniDatosMACOLA AS T1 ON 
			T4.Depnum = t1.Departamento AND T4.Centro = T1.Centro 
	LEFT OUTER JOIN tblCuentas AS T2 ON T2.Cuenta_Numero = T1.Cuenta 

WHERE
	t4.GrupoCtas_ID = t2.GrupoCuentas_ID AND
	T1.Ano Between @AnoDesde And @AnoHasta

GROUP BY 
	T4.UnidadNegocio,
	T4.GrupoCtas_ID,
	T2.Cuenta_ID,
	T4.Dpto_ID,
	T1.Cuenta,
	T1.Centro,
	T1.Departamento,
	T1.Ano,
	T1.Mes,
	T1.Origen

HAVING 
	Sum((round((T1.Monto/1000),2)*-1)) <>0


-- Q4 is a query that calculates subtotales based on the data
-- of #tp_Datos and inserts the result in the same table.
insert #tp_Datos (Centro, Departamento, Ano, Mes, Monto, Origen)
	SELECT 
	T1.Centro, T1.Departamento, T1.Ano, T1.Mes, 
	Sum(T1.Monto)+
		(SELECT Sum(sq1.Monto) FROM v_DatosParaSistemaAPH AS sq1
		WHERE 	sq1.GrupoCuentas_ID = 7 and 
			sq1.Centro = T1.Centro and 
			sq1.Departamento = T1.Departamento and 
			sq1.Ano = T1.Ano and
			sq1.Mes = T1.Mes and 
			sq1.Origen = T1.Origen
		GROUP BY 
			sq1.GrupoCuentas_ID, 
			sq1.Centro, 
			sq1.Departamento, 
			sq1.Ano, 
			sq1.Mes, 
			sq1.Origen) AS Monto, 
	T1.Origen
	FROM v_DatosParaSistemaAPH AS T1
	WHERE T1.GrupoCuentas_ID=6 
	
	GROUP BY 
	T1.Centro, T1.Departamento, T1.Ano, T1.Mes, T1.Origen
select * from #tp_datos
go
RETURN
 
Thanks for the star.

I don't understant some part's of your code:

This part of your Q1

Code:
SELECT
	UnidadNegocio,
	Dpto_ID
FROM tblDepartamentos
	INNER JOIN tblUsers ON tblUsers.[User]
WHERE CONVERT( int, Reporta_A ) = convert( int, ( SELECT [User] FROM tblUsers WHERE MulitipleCenter = -1 AND [User] = @User ) )
AND Reporta_A  IS NOT NULL

there is subquery:
SELECT [User] FROM tblUsers WHERE MulitipleCenter = -1 AND [User] = @User

This subquery returns the same value as in the variable @User or NULL ( if now row exists for MulitipleCenter = -1 ), so I think there may some other column in SELECT list or something else.

The next part of Q1 may look like this:
Code:
SELECT
    UnidadNegocio,
    Dpto_ID
FROM tblDepartamentos
	CROSS JOIN tblCurrentUser
    LEFT JOIN tblUsers ON tblUsers.[User] = @User
WHERE ( tblCurrentUser.SecurityLevel = 5 AND Dpto_ID BETWEEN 1 AND 999 )
	  OR
	  ( tblCurrentUser.SecurityLevel <> 5 AND Dpto_ID = 0 )
	  OR
	  Dpto_ID <> tblUsers.costcenter


The last statement may look like this:

Code:
insert #tp_Datos (Centro, Departamento, Ano, Mes, Monto, Origen)
    SELECT
    T1.Centro, T1.Departamento, T1.Ano, T1.Mes,
    Sum( CASE WHEN T1.GrupoCuentas_ID IN ( 6, 7 )THEN T1.Monto ELSE 0 END ) AS Monto,
    T1.Origen
    FROM v_DatosParaSistemaAPH AS T1
    GROUP BY
    T1.Centro, T1.Departamento, T1.Ano, T1.Mes, T1.Origen


Also, have you indexes on your tables ?. If yes, then post there on what columns you have it.

Zhavic

---------------------------------------------------------------
In the 1960s you needed the power of two Comodore64s to get a rocket to the moon. Now you need a machine which is a vast number of times more powerful just to run the most popular GUI.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top