Report Builder - Parameter Conversion Error - tsql

Using Report builder and trying to "move" a dataset filter over to the dataset query in order to improve report performance.
"An error occurred while reading data from the query result set. Conversion failed when converting the varchar value '70048-' to data type int."
This is my Where Statement that works (without parameter)
WHERE (JCCD.CostType = 1) AND JCCD.Job = '88800-'
This is my Where Statement that gives error after providing the parameter
WHERE (JCCD.CostType = 1) AND JCCD.Job = #JobParam
Complete SQL Statement
SELECT HQCO.Name, JCCD.JCCo, JCCD.Job, JCCD.Phase, JCJM.Description, JCJP.Description AS PhaseDescription, CAST(JCCD.EstHours AS Numeric) AS EstHours,
CAST(JCCD.EstCost AS Numeric) AS EstCost, CAST(JCCD.ActualHours AS Numeric) AS ActualHours, CAST(JCCD.ActualUnits AS Numeric) AS ActualUnits,
CAST(JCCD.ActualCost AS Numeric) AS ActualCost, JCCD.CostType, JCCD.UM, JCCD.CostTrans, JCCD.Mth, JCCD.JCTransType, JCJM.Job AS Expr2, JCCD.ActualDate,
JCCH.UM AS UM2, CAST(JCCD.EstUnits AS Numeric) AS EstUnits, JCCD.ProjUnits, JCCH.CostType AS Expr4, JCCD.ProjHours, JCCD.ForecastHours,
JCCD.ForecastUnits, JCCD.ForecastCost, CONVERT(INT,LEFT(JCCD.Phase,3)) AS PhasePreFix
FROM JCCD AS JCCD INNER JOIN
JCJM AS JCJM ON JCCD.JCCo = JCJM.JCCo AND JCCD.Job = JCJM.Job INNER JOIN
HQCO AS HQCO ON JCCD.JCCo = HQCO.HQCo INNER JOIN
JCJP AS JCJP ON JCCD.JCCo = JCJP.JCCo AND JCCD.Job = JCJP.Job AND JCCD.PhaseGroup = JCJP.PhaseGroup AND JCCD.Phase = JCJP.Phase INNER JOIN
JCCH AS JCCH ON JCCD.JCCo = JCCH.JCCo AND JCCD.Job = JCCH.Job AND JCCD.PhaseGroup = JCCH.PhaseGroup AND JCCD.Phase = JCCH.Phase AND
JCCD.CostType = JCCH.CostType
WHERE
(JCCD.CostType = 1) AND (JCCD.Job = '88800-')
ORDER BY JCCD.JCCo, JCCD.Job, JCCD.Phase

Related

Postgres functions how to return an array of multiple elements

I want to create a function to return an array of multiple elements, the query work perfect but I can't execute as function because I'm getting error always, this is my function:
CREATE OR REPLACE FUNCTION public.buscarexamen(visit anyelement)
RETURNS anyelement
LANGUAGE plpgsql
AS $function$
BEGIN
return array(SELECT fn_folio_paciente(vi.clave_unilabor, vi.fecha, vi.consec) AS folio_paciente,
vi.cve_visita, gp.nombre AS nombre_grupo, gp.cve_grupo,
--
vp.cve_visita_prueba, p.cve_prueba, p.nombre AS nombre_prueba, me.nombre AS nombre_metodo,
--
gcf.visible AS visible_grupo,
cf.cve_grupo_campo_formato, gc.nombre_grupo_campo AS grupo_parametro, cf.nombre AS nombre_parametro,
cf.orden, cf.tipo_dato, cf.solo_lectura AS tipo_titulo,
cf.cve_seccion_padre, cf.tiene_elementos_seccion, cf.observacion AS observacion_parametro,
--
pr.cve_prueba_resultado, pr.tipo_formato_prueba AS tipo_formato, pr.cantidad_resultado AS cantidad_parametro,
pr.observaciones AS observacion_analista, pr.observaciones_prueba,
CASE
WHEN (TRIM(pr.observaciones) <> '') OR (TRIM(pr.observaciones_prueba) <> '') THEN 1
ELSE 0 END AS prueba_tiene_observacion,
--
rc.cve_resultado_campo, rc.resultado, rc.observacion AS observacion_resultado, rc.signo, rc.decimales, cf.xleft as cursiva,
vr.valor_referencia_min, vr.valor_referencia_max, un.nombre AS nombre_unidad,
cf.tiene_valores_referencia
FROM visitas vi
JOIN corporativo.unilabor_unidades uu ON (vi.cve_unilabor_unidad = uu.cve_unilabor_unidad)
JOIN visita_pruebas vp ON (vi.cve_visita = vp.cve_visita)
JOIN prueba_resultados pr ON (vp.cve_visita_prueba = pr.cve_visita_prueba)
JOIN prueba_metodo pm ON (pr.cve_prueba_metodo = pm.cve_prueba_metodo)
JOIN metodos me ON (pm.cve_metodo = me.cve_metodo)
JOIN pruebas p ON (pr.cve_prueba = p.cve_prueba)
JOIN grupos gh ON (p.cve_grupo = gh.cve_grupo)
JOIN grupos gp ON (gh.cve_grupo_padre = gp.cve_grupo)
JOIN pacientes pa ON (vi.cve_paciente = pa.cve_paciente)
JOIN contratos co ON (vi.cve_contrato = co.cve_contrato AND co.contrato_cerrado = 0)
JOIN resultados_campos rc ON (pr.cve_prueba_resultado = rc.cve_prueba_resultado)
JOIN unidades un ON (rc.cve_unidad = un.cve_unidad)
LEFT JOIN valor_referencia_resultado vr ON (rc.cve_resultado_campo = vr.cve_resultado_campo)
JOIN campos_formatos cf ON (rc.cve_campo_formato = cf.cve_campo_formato)
JOIN grupos_campos_formato gcf ON (cf.cve_grupo_campo_formato = gcf.cve_grupo_campo_formato)
JOIN grupos_campos gc ON (gcf.cve_grupo_campo = gc.cve_grupo_campo)
WHERE vi.cve_visita = 696787
AND cf.solo_lectura = 0
ORDER BY p.orden_prueba, pr.cve_prueba_resultado, gcf.orden_grupo, rc.orden_local, vr.orden_valor);
END;
$function$
;
I try to use:
select * from buscarexamen(123123);
On SQL Script return this:
SQL Error [42601]: ERROR: subquery must return only one column Where: PL/pgSQL function buscarexamen(anyelement) line 3 at RETURN
Really I spend a lot of time finding solutions but until now isn't working.
Any help is really apreciated.
Regards.
Your objective sounds like strange. However you should be able to achieve it by creating a composite type your_composite_type :
CREATE TYPE your_composite_type AS
( folio_paciente folio_paciente_data_type
, cve_visita cve_visita_data_type
, nombre_grupo nombre_grupo_data_type
, cve_grupo cve_grupo_data_type
, cve_visita_prueba cve_visita_prueba_data_type
, cve_prueba cve_prueba_data_type
, nombre_prueba nombre_prueba_data_type
, nombre_metodo nombre_metodo_data_type
, visible_grupo visible_grupo_data_type
, [...]
, nombre_unidad nombre_unidad_data_type
, tiene_valores_referencia tiene_valores_referencia_data_type
) ;
Then the function public.buscarexamen() can return an array of data type your_composite_type :
CREATE OR REPLACE FUNCTION public.buscarexamen(visit anyelement)
RETURNS your_composite_type[] -- instead of anyarray
LANGUAGE plpgsql
AS $function$
BEGIN
return array(SELECT row( fn_folio_paciente(...)
, vi.cve_visita, gp.nombre, gp.cve_grupo
, [...]
, vr.valor_referencia_min, vr.valor_referencia_max, un.nombre
, cf.tiene_valores_referencia
) :: your_composite_type
FROM visitas vi
JOIN [...]
WHERE [...]
ORDER BY p.orden_prueba, pr.cve_prueba_resultado, gcf.orden_grupo, rc.orden_local, vr.orden_valor)
) ;
END;
$function$
;

How to use From clause inside PostgreSQL Update statement

I am converting SQL stored procedure to PostgreSQL stored function. In this stored function inside Update there is From clause.
I want to know how to use From inside Update? Because I am getting error table name "account" specified more than once
CREATE OR REPLACE FUNCTION ETL_Insert_ModifyData( instID numeric)
RETURNS void
LANGUAGE 'sql'
AS $$
--Account
UPDATE account
SET namount = stg_account.namount,
slocation = stg_account.sLocation,
ndept_id = stg_account.ndept_id ,
account.naccount_cpc_mapping_id = stg_account.naccount_cpc_mapping_id
FROM account
INNER JOIN stg_account ON account.naccount_id = stg_account.naccount_id
INNER JOIN department ON stg_account.ndept_id = department.ndept_id
INNER JOIN accountcpcmapping ON stg_account.naccount_cpc_mapping_id = accountcpcmapping.naccount_cpc_mapping_id
WHERE account.ninst_id = instID
AND department.ninst_id = instID
AND accountcpcmapping.ninst_id = instID
--print 'Account completed '
$$
Move the JOIN condition with account table and stg_account to WHERE clause. Also, you need not refer to account in the SET.
Further, prefer shorter aliases (like one or 2 letters) rather than using complete table names.
UPDATE account
SET
namount = stg_account.namount,
slocation = stg_account.sLocation,
ndept_id = stg_account.ndept_id ,
naccount_cpc_mapping_id = stg_account.naccount_cpc_mapping_id
FROM stg_account
INNER JOIN department ON stg_account.ndept_id = department.ndept_id
INNER JOIN accountcpcmapping ON
stg_account.naccount_cpc_mapping_id = accountcpcmapping.naccount_cpc_mapping_id
WHERE account.naccount_id = stg_account.naccount_id
AND account.ninst_id = instID
AND department.ninst_id = instID
AND accountcpcmapping.ninst_id = instID

Linq order by using query expression

Is it possible to do orderby expression using linq query expression based on dynamic string parameter? because the query i have is producing weird SQL query
my linq:
var product = from prod in _context.Products
join cat in _context.Categories on prod.CategoryId equals cat.CategoryId
join sup in _context.Suppliers on prod.SupplierId equals sup.SupplierId
orderby sortParam
select new ProductViewModel
{
ProductName = prod.ProductName,
ProductId = prod.ProductId,
QuantityPerUnit = prod.QuantityPerUnit,
ReorderLevel = prod.ReorderLevel,
UnitsOnOrder = prod.UnitsOnOrder,
UnitPrice = prod.UnitPrice,
UnitsInStock = prod.UnitsInStock,
Discontinued = prod.Discontinued,
Category = cat.CategoryName,
Supplier = sup.CompanyName,
CategoryId = cat.CategoryId,
SupplierId = sup.SupplierId
};
where var sortParam = "prod.ProductName"
The code above produces weird sql where order by sortParam is being converted to (SELECT 1). Full query catched by sql profiler below:
exec sp_executesql N'SELECT [prod].[ProductName], [prod].[ProductID], [prod].[QuantityPerUnit], [prod].[ReorderLevel], [prod].[UnitsOnOrder], [prod].[UnitPrice], [prod].[UnitsInStock], [prod].[Discontinued], [cat].[CategoryName] AS [Category], [sup].[CompanyName] AS [Supplier], [cat].[CategoryID], [sup].[SupplierID]
FROM [Products] AS [prod]
INNER JOIN [Categories] AS [cat] ON [prod].[CategoryID] = [cat].[CategoryID]
INNER JOIN [Suppliers] AS [sup] ON [prod].[SupplierID] = [sup].[SupplierID]
ORDER BY (SELECT 1)
OFFSET #__p_1 ROWS FETCH NEXT #__p_2 ROWS ONLY',N'#__p_1 int,#__p_2 int',#__p_1=0,#__p_2=10
I'm seeing a lot of people doing linq order by using dynamic parameter but all of them use lambda not query expression, please enlighten me
As was already mentioned, you are passing a string value instead of an expression that reflects the column name. There are options for what you want however, see for example here.

How to select from subquery if column contains a specific value in postgre

I would like to ask if it is possible to select again from a result set if a column contains a specific value?
For example, from the below query I want to select it as subquery and check if that subquery's first column contains both 2 and 3 result. Otherwise, no values should be return.
select e.evaluator_id, ROUND(avg(cast(e.rating_score as int))::numeric,1)::varchar, c.q_category_name
from tms.t_evaluation e
inner join tms.m_q_category c
on e.nendo=c.nendo
and e.q_category_id = c.q_category_id
and c.delete_flg = '0'
inner join tms.m_q_subcategory qs
on e.q_category_id = qs.q_category_id
and e.q_subcategory_id = qs.q_subcategory_id
and c.nendo = qs.nendo
and qs.delete_flg = '0'
where e.nendo = '2018'
and e.empl_id = 'empl05'
and e.delete_flg = '0'
and e.evaluator_id in ('2' , '3')
group by e.empl_id, e.nendo, e.q_category_id,
c.q_category_name, e.evaluator_id, e.history_no
Result contains both 2 and 3 in first column. Is this possible?
select e.evaluator_id, ROUND(avg(cast(e.rating_score as int))::numeric,1)::varchar, c.q_category_name
from tms.t_evaluation e
inner join tms.m_q_category c
on e.nendo=c.nendo
and e.q_category_id = c.q_category_id
and c.delete_flg = '0'
inner join tms.m_q_subcategory qs
on e.q_category_id = qs.q_category_id
and e.q_subcategory_id = qs.q_subcategory_id
and c.nendo = qs.nendo
and qs.delete_flg = '0'
where e.nendo = '2018'
and e.empl_id = 'empl05'
and e.delete_flg = '0'
and e.evaluator_id in (select case when evaluator_id=2 or evaluator_id=3 then evaluator_id else null from t_evaluation order by evaluator_id asc)
group by e.empl_id, e.nendo, e.q_category_id,
c.q_category_name, e.evaluator_id, e.history_no

Calling Stored Procedure on Column TSQL

Here is my situation. I know there must be a simple answer, but I am just not well versed in TSQL to know how. Below I have the main query of a stored procedure that selects the data I need. I have it working so far except that I need to call a seperate stored procedure called GetRecordMediaById where I feed it the Id from the PhotoId column, and it selects the BLOB data from the appropriate database which then needs to be its own column in the final query or replace the original PhotoId column.
I have no clue how to go about this. I've tried implementing temp tables, but I could never even get it to execute.
Here is my code:
ALTER PROCEDURE [dbo].[GetRollCallData]
#Ids VARCHAR(255),
#LexiconId INT,
#UUID UNIQUEIDENTIFIER,
#ReadOnly INT
AS
DECLARE #TableCode INT
SET #TableCode = 58
EXEC InsertInSelectionCache #Ids, #UUID, #TableCode, 0
WITH DOACTE AS(
SELECT ROW_NUMBER() OVER(PARTITION BY [File].Id ORDER BY CustomRecordsetId DESC) AS RowNumber, [File].*, FileType2Lexicon.Label as FileTypeLabel, [People].DefaultPhone, [People].InvertedName, CustomFieldValue.Value as DateofArrest
FROM FileType2Lexicon, SelectionCache, [People], [File]
INNER JOIN [CustomRecordSet]
ON [CustomRecordset].RecordId = [File].Id
INNER JOIN CustomFieldValue
ON [CustomRecordset].Id = CustomFieldValue.CustomRecordsetId
INNER JOIN [CustomField2Lexicon]
ON CustomField2Lexicon.CustomFieldId = CustomFieldValue.CustomFieldId
WHERE [File].Id = SelectionCache.RecordId
AND SelectionCache.UUID = #UUID
AND SelectionCache.TableCode = #TableCode -- this is the code for File table
AND [File].Id <> 0
AND [File].FileTypeId = FileType2Lexicon.FileTypeId
AND FileType2Lexicon.LexiconId = #LexiconId
AND [File].ClientIdString = [People].ClientIdString
AND CustomFieldValue.Value <> ''
AND CustomField2Lexicon.Label = 'Date of Arrest'),
PHOTOCTE AS(
SELECT [File].Id, CustomFieldValue.Value as PhotoId
FROM FileType2Lexicon, SelectionCache, [People], [File]
INNER JOIN [CustomRecordSet]
ON [CustomRecordset].RecordId = [File].Id
INNER JOIN CustomFieldValue
ON [CustomRecordset].Id = CustomFieldValue.CustomRecordsetId
INNER JOIN [CustomField2Lexicon]
ON CustomField2Lexicon.CustomFieldId = CustomFieldValue.CustomFieldId
WHERE [File].Id = SelectionCache.RecordId
AND SelectionCache.UUID = #UUID
AND SelectionCache.TableCode = #TableCode -- this is the code for File table
AND [File].Id <> 0
AND [File].FileTypeId = FileType2Lexicon.FileTypeId
AND FileType2Lexicon.LexiconId = #LexiconId
AND [File].ClientIdString = [People].ClientIdString
AND CustomFieldValue.Value <> ''
AND CustomField2Lexicon.Label = 'Booking Photo')
SELECT DOACTE.*, PHOTOCTE.PhotoId
FROM DOACTE
INNER JOIN
PHOTOCTE
ON DOACTE.Id = PHOTOCTE.Id
WHERE DOACTE.RowNumber = 1
EDIT:
Solution for me was to create a scalar function that resolves the Id in the BLOB database and returns the BLOB data.
SELECT DOACTE.*, dbo.GetImagebyId(PHOTOCTE.PhotoId) as Photo,
FROM DOACTE
INNER JOIN
PHOTOCTE
ON DOACTE.Id = PhotoCTE.Id
WHERE DOACTE.RowNumber = 1
You can declare a #table_variable and insert the results from "EXEC InsertInSelectionCache #Ids, #UUID, #TableCode, 0" into the table variable.
Then you can join to the #table_variable in the final query.
See here for examples: How to return temporary table from stored procedure