I need to define temporal table depending of value of parameter, I put this code:
CASE #estadoFacturacion
WHEN 1 THEN SELECT * INTO #EstadoFacturacion FROM f_lineas_proceso_pendiente(#custCod) --PROCESOS QUE NO TIENEN NINGUNA FACTURA ASOCIADA
WHEN 2 THEN SELECT * INTO #EstadoFacturacion FROM f_lineas_proceso_FactParcial(#custCod) --PROCESOS CON, AL MENOS, 1 TRAMO FACTURADO
WHEN 3 THEN SELECT * INTO #EstadoFacturacion FROM f_lineas_proceso_AbonoParcial(#custCod) --PROCESOS CON, AL MENOS, 1 TRAMO ABONADO
WHEN 4 THEN SELECT * INTO #EstadoFacturacion FROM f_lineas_proceso_Facturada(#custCod) --PROCESOS CON TODOS LOS TRAMOS FACTURADOS
WHEN 5 THEN SELECT * INTO #EstadoFacturacion FROM f_lineas_proceso_Abonada(#custCod) --PROCESOS CON TODOS LOS TRAMOS ABONADO
ELSE SELECT CONVERT(VARCHAR, LP.fk_proyecto_id) + '-' + CONVERT(VARCHAR,LP.linea) IdProyLinea INTO #EstadoFacturacion FROM lineas_proceso LP --TODOS LOS PROCESOS
But it doesn't works...
¿How can I do this?
Thanks.
SQL server does not have a CASE statement, only a CASE expression. So use an IF ELSE IF ladder instead:
IF #estadoFacturacion = 1
BEGIN
SELECT *
INTO #EstadoFacturacion
FROM f_lineas_proceso_pendiente(#custCod)
END
ELSE IF #estadoFacturacion = 2
BEGIN
SELECT *
INTO #EstadoFacturacion
FROM f_lineas_proceso_FactParcial(#custCod)
END
...
ELSE
BEGIN
SELECT CONVERT(VARCHAR, LP.fk_proyecto_id) + '-' + CONVERT(VARCHAR,LP.linea) Id
INTO #EstadoFacturacion
FROM lineas_proceso LP
END
Related
I have the following query which has an issue with Query Builder.
SELECT IIF(ISNULL(MAX(CODCLIENTE), 0) + 1 = 1,
(SELECT VALOR + 1
FROM PARAMETROS
WHERE LTRIM(RTRIM(SUBCLAVE)) = 'MINIM'
AND USUARIO = '1'),
ISNULL(MAX(CODCLIENTE), 0) + 1)
FROM CLIENTES
WHERE CODCLIENTE >= (SELECT VALOR
FROM PARAMETROS
WHERE LTRIM(RTRIM(SUBCLAVE)) = 'MINIM'
AND USUARIO = '1')
AND CODCLIENTE <= (SELECT VALOR
FROM PARAMETROS
WHERE LTRIM(RTRIM(SUBCLAVE)) = 'MAXIM'
AND USUARIO = '1');
Is there any way to do it with Query Builder? I'm currently using this method.
I have to write a table function so I prototyped the query in SQL Server and used a temp table but when I change it to a table variable the query goes from taking approx. 1 minute to more than 2 hours.
The second code is this one:
DECLARE #DETALLE TABLE
(
FECHA smalldatetime,
NO_OP NVARCHAR(100),
MONTO FLOAT,
PLAZO INT,
CLIENTE NVARCHAR(100)
)
-- CALCULO EL PLAZO POR EL MONTO, EL CUAL SERA EL NUMERADOR --
--DROP TABLE #DETALLE
INSERT INTO #DETALLE
SELECT
D.FECHA, D.NO_OP,
MONTO = (D.CAPITAL+D.INTERESES)/1000000,
PLAZO = CAST(D.FECHA_VCTO-D.FECHA AS INT),
CLIENTE = CASE
WHEN MIN_MAY = 'N' THEN 'MINORISTA'
WHEN M.ORIGEN = 'MESA LIQUIDEZ' THEN 'CLIENTE LIQUIDEZ'
WHEN M.ORIGEN IS NULL AND MIN_MAY = 'S' AND COD_SUCURSAL = '246' THEN 'EMPRESAS SALES'
ELSE 'OTRO MAYORISTA'
END
--INTO #DETALLE
FROM
BCI_RIF_ODS.dbo.Tab_Detalle_DAP AS D
INNER JOIN
BCI_RI_ODS.dbo.Cliente_Traduce AS C ON (C.CLIENTE_ID = D.CLIENTE_ID)
LEFT JOIN
BCI_RIF_ODS.dbo.TabMae_CliMesa AS M ON (D.CLIENTE_ID = M.CLIENTE_ID)
WHERE
FECHA >= '20180101' AND FECHA_VCTO > FECHA
SELECT
D1.CLIENTE, D1.FECHA,
NUMERADOR = SUM(D1.PLAZO*D1.MONTO),
MONTO = D2.MONTO,
FACTOR = SUM(D1.PLAZO*D1.MONTO)/D2.Monto
FROM
#DETALLE D1
LEFT JOIN
(SELECT
CLIENTE, FECHA,
MONTO = SUM(MONTO)
FROM
#DETALLE
GROUP BY
CLIENTE, FECHA) D2 ON (D1.CLIENTE = D2.CLIENTE AND D1.Fecha = D2.Fecha)
GROUP BY
D1.CLIENTE, D1.Fecha, D2.MONTO
You really don't need to make another copy of your data to then just perform an aggregate. You could use a cte here instead. Something like this will likely perform a lot better than copying data from one table to a variable.
with DETALLE as
(
-- CALCULO EL PLAZO POR EL MONTO, EL CUAL SERA EL NUMERADOR --
SELECT
D.FECHA, D.NO_OP,
MONTO = (D.CAPITAL+D.INTERESES)/1000000,
PLAZO = CAST(D.FECHA_VCTO-D.FECHA AS INT),
CLIENTE = CASE
WHEN MIN_MAY = 'N' THEN 'MINORISTA'
WHEN M.ORIGEN = 'MESA LIQUIDEZ' THEN 'CLIENTE LIQUIDEZ'
WHEN M.ORIGEN IS NULL AND MIN_MAY = 'S' AND COD_SUCURSAL = '246' THEN 'EMPRESAS SALES'
ELSE 'OTRO MAYORISTA'
END
FROM
BCI_RIF_ODS.dbo.Tab_Detalle_DAP AS D
INNER JOIN
BCI_RI_ODS.dbo.Cliente_Traduce AS C ON (C.CLIENTE_ID = D.CLIENTE_ID)
LEFT JOIN
BCI_RIF_ODS.dbo.TabMae_CliMesa AS M ON (D.CLIENTE_ID = M.CLIENTE_ID)
WHERE
FECHA >= '20180101' AND FECHA_VCTO > FECHA
)
SELECT
D1.CLIENTE, D1.FECHA,
NUMERADOR = SUM(D1.PLAZO*D1.MONTO),
MONTO = D2.MONTO,
FACTOR = SUM(D1.PLAZO*D1.MONTO)/D2.Monto
FROM
DETALLE D1
LEFT JOIN
(SELECT
CLIENTE, FECHA,
MONTO = SUM(MONTO)
FROM
DETALLE
GROUP BY
CLIENTE, FECHA) D2 ON (D1.CLIENTE = D2.CLIENTE AND D1.Fecha = D2.Fecha)
GROUP BY
D1.CLIENTE, D1.Fecha, D2.MONTO
I need your help on this please:
I have one table in which ID_Erreur_CallBack could be NULL, 0, 1, 2, 3, 4, 5 or 6.
If I execute:
SELECT ID_SkillGroup AS Competence
,ID_Erreur_CallBack
,count(*) AS Nombre_de_Ocurrences
,CASE ID_Erreur_CallBack
WHEN '0'
THEN 'Abandon pendant l’exécution du script (le client a raccroché)'
WHEN '1'
THEN 'Ligne occupée'
WHEN '2'
THEN 'Le client n’a pas confirmé en appuyant sur étoile'
WHEN '3'
THEN 'Le client n’a pas décroché'
WHEN '4'
THEN 'Le numéro de téléphone du client est invalide'
WHEN '5'
THEN 'Problemes de ressources lors de l’appel'
WHEN '6'
THEN 'Echec de l’appel'
ELSE 'Appel réussi'
END AS Description_Erreur
FROM dbo.TB_WCB_USER
WHERE Date_Heure_Insert BETWEEN '01/11/2015'
AND '01/12/2015'
AND TYPE = 'WCB'
GROUP BY ID_SkillGroup
,ID_Erreur_CallBack
ORDER BY ID_SkillGroup
,ID_Erreur_CallBack ASC
And I get for example:
Result
I want to make a SELECT statement where I can vary ID_Erreur_CallBack from 0 to 6 and NULL even if Nombre_de_Ocurrences is 0 (or NULL). Something like:
Result I wish
Thank you!
Instead of using a CASE You create a table with your errors description, that way is easy to mantain if you want add or update text, dont need change code.
like errors
error_id error_text
1 err1
2 err2
3 err3
....
100 'Appel réussi'
THEN use LEFT JOIN
select ID_SkillGroup as Competence,
E.error_id as ID_Erreur_CallBack,
E.error_text as Description_Erreur,
count(*) as Nombre_de_Ocurrences
FROM errors E
LEFT JOIN TB_WCB_USER W
ON E.error_id = ID_Erreur_CallBack
I see you have an ELSE on your CASE
You can do something like this
LEFT JOIN TB_WCB_USER W
ON E.error_id = CASE ID_Erreur_CallBack
WHEN > 99 then 100 -- 'Appel réussi'
ELSE ID_Erreur_CallBack
END
Thank for the answer Juan Carlos.
I finally used CROSS JOIN
/*Creation de table temporaire et remplisage avec NULL*/
WITH T1 AS (
SELECT n = 0
UNION ALL
SELECT n + 1 FROM T1 WHERE n < 6
)
SELECT n INTO #Temp_Cesar FROM T1
INSERT INTO #Temp_Cesar (n) VALUES (NULL)
SELECT t1.ID_SkillGroup as Competence,t2.n as ID_Erreur_CallBack
INTO #Temp_Cesar1
FROM dbo.TB_SKILLGROUP t1
CROSS JOIN #Temp_Cesar t2
ORDER BY t1.ID_SkillGroup
ALTER TABLE #Temp_Cesar1 ADD Nombre_de_Ocurrences INT NULL, Description_Erreur VARCHAR(30) NULL;
select Competence,isnull(ID_Erreur_CallBack,99) as ID_Erreur_CallBack,isnull(Nombre_de_Ocurrences,0) as Nombre_de_Ocurrences,
Case ID_Erreur_CallBack
WHEN '0' THEN 'Abandon pendant l’exécution du script (le client a raccroché)'
WHEN '1' THEN 'Ligne occupée'
WHEN '2' THEN 'Le client n’a pas confirmé en appuyant sur étoile'
WHEN '3' THEN 'Le client n’a pas décroché'
WHEN '4' THEN 'Le numéro de téléphone du client est invalide'
WHEN '5' THEN 'Problemes de ressources lors de l’appel'
WHEN '6' THEN 'Echec de l’appel'
ELSE 'Appel réussi'
END AS Description_Erreur
into #Temp_Cesar11 from #Temp_Cesar1
I like using the SQL Management Studio report 'Disk Usage by Top Tables' to see what's taking up space in my databases. What equivalent query can I use in SQL Azure to see
number of rows per table
disk usage per table (preferably breaking out data and index)
In SQL Profiler I can see that the Disk Usage by Top Tables report normally runs this:
begin try
SELECT TOP 1000
(row_number() over(order by (a1.reserved + ISNULL(a4.reserved,0)) desc))%2 as l1,
a3.name AS [schemaname],
a2.name AS [tablename],
a1.rows as row_count,
(a1.reserved + ISNULL(a4.reserved,0))* 8 AS reserved,
a1.data * 8 AS data,
(CASE WHEN (a1.used + ISNULL(a4.used,0)) > a1.data THEN (a1.used + ISNULL(a4.used,0)) - a1.data ELSE 0 END) * 8 AS index_size,
(CASE WHEN (a1.reserved + ISNULL(a4.reserved,0)) > a1.used THEN (a1.reserved + ISNULL(a4.reserved,0)) - a1.used ELSE 0 END) * 8 AS unused
FROM ( SELECT
ps.object_id,
SUM ( CASE WHEN (ps.index_id < 2) THEN row_count ELSE 0 END ) AS [rows],
SUM (ps.reserved_page_count) AS reserved,
SUM (CASE WHEN (ps.index_id < 2) THEN (ps.in_row_data_page_count + ps.lob_used_page_count + ps.row_overflow_used_page_count)
ELSE (ps.lob_used_page_count + ps.row_overflow_used_page_count) END
) AS data,
SUM (ps.used_page_count) AS used
FROM sys.dm_db_partition_stats ps
GROUP BY ps.object_id
) AS a1
LEFT OUTER JOIN ( SELECT
it.parent_id,
SUM(ps.reserved_page_count) AS reserved,
SUM(ps.used_page_count) AS used
FROM sys.dm_db_partition_stats ps
INNER JOIN sys.internal_tables it ON (it.object_id = ps.object_id)
WHERE it.internal_type IN (202,204)
GROUP BY it.parent_id
) AS a4 ON (a4.parent_id = a1.object_id)
INNER JOIN sys.all_objects a2 ON ( a1.object_id = a2.object_id )
INNER JOIN sys.schemas a3 ON (a2.schema_id = a3.schema_id)
WHERE a2.type <> N'S' and a2.type <> N'IT'
end try
begin catch
select
-100 as l1
, 1 as schemaname
, ERROR_NUMBER() as tablename
, ERROR_SEVERITY() as row_count
, ERROR_STATE() as reserved
, ERROR_MESSAGE() as data
, 1 as index_size
, 1 as unused
end catch
but that fails when running against SQL Azure with message
Msg 208, Level 16, State 1, Line 4
Invalid object name 'sys.internal_tables'.
EDIT 24 May 2016: Doesn't seem to work these days ... I'll have to rework this
Well I guess since it's sys.internal_tables that's the problem the simplest thing is to remove it from the mix. A slight adjustment and we're left with this:
SELECT TOP 1000
a3.name AS SchemaName,
a2.name AS TableName,
a1.rows as Row_Count,
(a1.reserved )* 8.0 / 1024 AS reserved_mb,
a1.data * 8.0 / 1024 AS data_mb,
(CASE WHEN (a1.used ) > a1.data THEN (a1.used ) - a1.data ELSE 0 END) * 8.0 / 1024 AS index_size_mb,
(CASE WHEN (a1.reserved ) > a1.used THEN (a1.reserved ) - a1.used ELSE 0 END) * 8.0 / 1024 AS unused_mb
FROM ( SELECT
ps.object_id,
SUM ( CASE WHEN (ps.index_id < 2) THEN row_count ELSE 0 END ) AS [rows],
SUM (ps.reserved_page_count) AS reserved,
SUM (CASE WHEN (ps.index_id < 2) THEN (ps.in_row_data_page_count + ps.lob_used_page_count + ps.row_overflow_used_page_count)
ELSE (ps.lob_used_page_count + ps.row_overflow_used_page_count) END
) AS data,
SUM (ps.used_page_count) AS used
FROM sys.dm_db_partition_stats ps
GROUP BY ps.object_id
) AS a1
INNER JOIN sys.all_objects a2 ON ( a1.object_id = a2.object_id )
INNER JOIN sys.schemas a3 ON (a2.schema_id = a3.schema_id)
WHERE a2.type <> N'S' and a2.type <> N'IT'
order by a1.data desc
There are some interesting management views and functions provided by Azure but not needed in this case ... I think.
try querying sys.dm_db_partition_stats
e.g.,
-- Calculates the size of individual database objects.
SELECT sys.objects.name, SUM(reserved_page_count) * 8.0 / 1024 as Size
FROM sys.dm_db_partition_stats, sys.objects
WHERE sys.dm_db_partition_stats.object_id = sys.objects.object_id
GROUP BY sys.objects.name
ORDER BY Size DESC;
GO
Here is one that is functional on SQL 2012 that has basically the same data as the Report. Based on a previous answer and expanded a little.
It's wrapped in a SP to allow it to be called against any DB on the server so you don't need 20 copies of it.
Comment out whichever unit size you don't want. GB was useful to me.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE dbo.TableSizes
#DB varchar(50) = 'OP'
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- DECLARE #DB AS varchar(50)='OP'; -- DEBUG LINE
DECLARE #sql nvarchar(max)='
WITH A AS (
SELECT Sc.name AS SchemaName, O.name AS TableName
, SUM(ps.row_count) AS TotalRows
, CAST(SUM(ps.reserved_page_count) * 8.0 / 1024 / 1024 AS Decimal(28,6)) AS TotalSizeGB
, CAST(SUM(ps.used_page_count) * 8.0 / 1024 / 1024 AS Decimal(28,6)) AS UsedTotalSizeGB
, CAST(SUM(ps.reserved_page_count) * 8.0 / 1024 AS Decimal(28,3)) AS TotalSizeMB
, CAST(SUM(ps.used_page_count) * 8.0 / 1024 AS Decimal(28,3)) AS UsedTotalSizeMB
, CAST(SUM(ps.reserved_page_count) * 8.0 AS Decimal(28,0)) AS TotalSizeKB
, CAST(SUM(ps.used_page_count) * 8.0 AS Decimal(28,0)) AS UsedTotalSizeKB
--, O.Type
FROM $DB$.sys.dm_db_partition_stats AS PS
JOIN $DB$.sys.objects AS O ON PS.object_id=O.object_id
JOIN $DB$.sys.schemas AS Sc on O.schema_id=Sc.Schema_id
WHERE O.Type=''U'' -- user tables only
GROUP BY Sc.name, O.name
--, O.Type
)
SELECT A.*
, CASE WHEN A.TotalSizeGB=0 THEN NULL ELSE 100.0 * A.UsedTotalSizeGB / A.TotalSizeGB END AS UsedPercent
FROM A
ORDER BY A.TotalSizeGB DESC
'
SET #sql=replace(#sql,'$DB$',#DB);
EXEC sp_executesql #sql;
-- EXEC Agent.TableSizes 'Scorecards' -- DEBUG LINE
END
GO
How can i join these two queries
SELECT
GLMA_COMP_CODE COMP,
GLMA_ACCT_CODE ACCOUNT_NO,
GLMA_DEPT_NO DEPT,
GLMA_ACCT_NAME ACCOUNT_NAME
FROM GLAS_GL_MASTERS
WHERE GLMA_COMP_CODE = #COMP_CODE
AND GLMA_YEAR = CONVERT(NUMERIC(8, 2), DATEPART(YYYY, #DATE_FROM))
AND GLMA_ACCT_CODE BETWEEN ISNULL(#ACCT_CODE_FROM, GLMA_ACCT_CODE) AND
ISNULL(#ACCT_CODE_TO, GLMA_ACCT_CODE)
ORDER BY GLMA_ACCT_CODE
SELECT
GLTR_COMP_CODE,
GLTR_DEPT_NO,
GLTR_ACCT_CODE,
CAST(GLTR_PSTNG_TYPE AS VARCHAR) + CAST(GLTR_PSTNG_NO AS VARCHAR) REF_NO,
CAST(GLTR_DOC_CODE AS VARCHAR) + CAST(GLTR_OUR_DOC_NO AS VARCHAR) DOC_NO,
GLTR_DOC_DATE DOC_DATE,
GLTR_DOC_NARR NARRATIVE,
GLTR_PSTNG_DATE,
CASE SIGN(GLTR_TRAN_AMT)
WHEN + 1 THEN GLTR_TRAN_AMT
ELSE 0
END DEBIT,
CASE SIGN(GLTR_TRAN_AMT)
WHEN - 1 THEN GLTR_TRAN_AMT
ELSE 0
END CREDIT,
GLTR_TRAN_AMT AMOUNT,
GLTR_FC_CODE FC_CODE,
GLTR_FC_AMT FC_AMOUNT
FROM GLAS_GL_TRANSACTIONS
WHERE GLTR_PSTNG_DATE BETWEEN ISNULL(#DATE_FROM, GLTR_PSTNG_DATE) AND ISNULL(#DATE_TO, GLTR_PSTNG_DATE)
ORDER BY GLTR_ACCT_CODE,
GLTR_PSTNG_DATE,
GLTR_DOC_CODE,
GLTR_OUR_DOC_NO
From what's provided, here goes:
SELECT t.gltr_comp_code,
t.gltr_acct_code,
t.gltr_dept_no,
m.glma_acct_name
CAST(t.gltr_pstng_type AS VARCHAR) + CAST(t.gltr_pstng_no AS VARCHAR) REF_NO,
CAST(t.gltr_doc_code AS VARCHAR) + CAST(t.gltr_our_doc_no AS VARCHAR) DOC_NO,
t.gltr_doc_date DOC_DATE,
t.gltr_doc_narr NARRATIVE,
t.gltr_pstng_date,
CASE SIGN(t.gltr_tran_amt) WHEN + 1 THEN t.gltr_tran_amt ELSE 0 END DEBIT,
CASE SIGN(t.gltr_tran_amt) WHEN - 1 THEN t.gltr_tran_amt ELSE 0 END CREDIT,
t.gltr_tran_amt AMOUNT,
t.gltr_fc_code FC_CODE,
t.gltr_fc_amt FC_AMOUNT
FROM GLAS_GL_TRANSACTIONS t
JOIN GLAS_GL_MASTERS m ON m.glma_comp_code = t.gltr_comp_code
AND m.glma_acct_code = t.gltr_acct_code
AND m.glma_dept_no = t.glma_dept_no
WHERE t.gltr_pstng_date BETWEEN COALESCE(#DATE_FROM, t.gltr_pstng_date) AND COALESCE(#DATE_TO, t.gltr_pstng_date)
AND m.glma_comp_code = #COMP_CODE
AND m.glma_year = CONVERT(NUMERIC(8, 2), DATEPART(YYYY, #DATE_FROM))
AND m.glma_acct_code BETWEEN COALESCE(#ACCT_CODE_FROM, t.glma_acct_code) AND COALESCE(#ACCT_CODE_TO, t.glma_acct_code)
ORDER BY t.gltr_acct_code, t.gltr_pstng_date, t.gltr_doc_code, t.gltr_our_doc_no