I have a search form that is allowing you to enter any information you want into it and perform the search on that data.
Here is what the form looks like:
My goal is to allow them to enter a start and end date. However, they could chose to only enter one or the other. In this case, I need my stored procedure to handle it correctly.
If the end date is empty, the end date will just become today's date. If the start date is empty, we could do any date (sqls default date for example which would include everything.
The awardDate is that field that is being searched. If both dates are entered, then it would need to be the range between start and end
Below is my current stored procedure:
SELECT DISTINCT A.[awardID],
A.[awardDescription],
convert(varchar,cast(A.[awardValue] as money),1) as awardValue,
CONVERT (VARCHAR (10), A.[awardDate], 101) AS awardDate,
CONVERT (VARCHAR (10), A.[timestamp], 101) AS timestamp,
B.[FirstName] + ' ' + B.[LastName] as empName,
B.[ntid] AS empNTID,
C.[awardType] as awardTypeName,
D.[locationName],
E.[awardStatusName]
FROM taxTracker AS A
INNER JOIN
empTable AS B
ON A.[employee] = B.[empID]
INNER JOIN
taxTrackerAwardTypes AS C
ON A.[awardType] = C.[awardTypeID]
INNER JOIN taxTrackerLocations as D
ON A.[awardLocation] = D.[id]
INNER JOIN taxTrackerStatuses as E
ON A.[awardStatus] = E.[awardStatusID]
WHERE ((A.[employee] IN (SELECT ParamValues.x2.value('empID[1]', 'VARCHAR(60)')
FROM #employees.nodes('/employees/employee') AS ParamValues(x2)))
OR (ISNULL(#awardType, '') <> ''
AND A.[awardType] LIKE '%' + #awardType + '%')
OR (ISNULL(#awardStatus, '') <> ''
AND A.[awardStatus] LIKE '%' + #awardStatus + '%'))
FOR XML PATH ('details'), TYPE, ELEMENTS, ROOT ('root');
where (awarddate >= #startdate or #stardate is null)
and (awarddate <= isnull(#enddate, getdate())
Awarddate between isnull (#startdate, '19000101') and isnull (#enddate, getdate ())
Related
This question already has answers here:
How to convert data to json format in SQL Server 2008?
(3 answers)
Closed 8 months ago.
My question is to know if it is possible from T-SQL to create a JSON file in previous versions of 2016, since from this version it already brings the function implicitly, but in my case I am using SQL Server 2014.
Is there a way to parse it from XML to JSON or create a function?
Here's an example of an XML File with objects inside him processing by SP.
ALTER PROCEDURE [dbo].[sp_Socio_IntegracionPOST] #Codigo nvarchar(20), #Query int
AS
BEGIN
DECLARE #socio xml,#direccion xml,#contacto xml
SET NOCOUNT ON;
--Este query consulta el socio de negocio
IF (#Query = 1)
BEGIN
SET #direccion = (SELECT
SUCURSAL AS AddressName,
DIRECCION AS Street,
mun.NombreMunicipio AS 'Block',
FORMAT(CONVERT(int, codciudad), '00000') AS ZipCode,
mun.NombreMunicipio AS City,
'CO' AS County,
'CO' AS Country,
dep.IdSAP AS 'State',
NULL AS AddressType,
RTRIM(dir.CODIGO) AS BPCode,
CONVERT(date, GETDATE()) AS CreateDate,
CONVERT(char(8), GETDATE(), 108) AS CreateTime,
FORMAT(CONVERT(int, codciudad), '00000') AS U_HBT_MunMed,
CASE
WHEN DEFECTO_FACTURA = 1 THEN 'Y'
ELSE 'N'
END AS U_HBT_DirMM
FROM tblmvto_direccion dir
INNER JOIN tblMunicipios mun
ON dir.CODCIUDAD = mun.CodMunc
INNER JOIN tblDepartamentos dep
ON dir.DEPARTAMENTO = dep.NombreDepartamento
WHERE dir.CODIGO = #Codigo
FOR XML PATH ('Row'))
SET #contacto = (SELECT
RTRIM(contac.CODIGO) AS CardCode,
CONCAT(RTRIM(contac.PrimerNombre), RTRIM(' ' + contac.SegundoNombre), RTRIM(' ' + contac.PrimerApellido), RTRIM(' ' + contac.SegundoApellido)) AS 'Name',
contac.Telefono AS Phone1,
contac.TelefonoMovil as MobilePhone,
contac.CorreoContacto AS E_Mail,
'E' AS Gender,
'Y' AS Active,
contac.PrimerNombre AS FirstName,
contac.SegundoNombre AS MiddleName,
CONCAT(RTRIM(contac.PrimerApellido), RTRIM(' ' + contac.SegundoApellido)) AS LastName,
CONVERT(date, GETDATE()) AS CreateDate,
CONVERT(char(8), GETDATE(), 108) AS CreateTime
FROM tblmvto_contactos contac
WHERE contac.CODIGO = #Codigo
FOR XML PATH('Row'))
SET #contacto = CONVERT(xml, '<ContactEmployees>'+CAST(#contacto AS nvarchar(MAX))+'</ContactEmployees>')
SET #direccion = CONVERT(xml, '<BPAddresses>'+CAST(#direccion AS nvarchar(MAX))+'</BPAddresses>')
SET #socio = (SELECT top 1
RTRIM(sn.codigo) AS CardCode,
RTRIM(sn.nit) as FederalTaxID,
CONCAT(RTRIM(sn.nombre), RTRIM(' ' + sn.nombre1), RTRIM(' ' + sn.apellido), RTRIM(' ' + sn.apellido1)) AS CardName,
[dbo].[FN_Validar_CardType_SocioNegocio](sn.escliente, sn.esprovee, sn.esempleado) AS CardType,
CASE
WHEN sn.GranContribuyente = 1 THEN 'S'
ELSE 'N'
END AS U_GraCont,
RTRIM(sn.celular) AS Phone1,
CONCAT(rtrim(sn.nombre), RTRIM(' ' + sn.nombre1)) AS U_HBT_Nombres,
RTRIM(sn.apellido) AS U_HBT_Apellido1,
RTRIM(sn.apellido1) AS U_HBT_Apellido2,
sn.Nacionalidad AS U_HBT_Nacional,
CASE
WHEN sn.codtipoper = 'O-SIN' THEN 1
ELSE CONVERT(int, sn.codtipoper)
END AS U_HBT_TipEnt,
FORMAT(CONVERT(int, sn.codciudad), '00000') AS U_HBT_MunMed,
CASE
WHEN ti.IdSAP = 'O-SIN' THEN '13'
ELSE ti.IdSAP
END AS U_HBT_TipDoc,
CASE
WHEN tc.IdSAP = 'O-SIN' OR
tc.IdSAP IS NULL THEN 'RS'
ELSE tc.IdSAP
END AS U_HBT_RegTrib,
CASE
WHEN sn.Autorretenedor = 0 THEN 'N'
ELSE 'Y'
END AS U_HBT_AutRet,
CASE
WHEN rf.IdSAP = 'O-SIN' THEN 'R-99-PN'
ELSE rf.IdSAP
END AS U_HBT_RegFis,
mp.IdSAP AS U_HBT_MedPag
FROM tblsocio_negocios sn
INNER JOIN tbltipo_identificacion ti
ON sn.codtipo = ti.codtipo
INNER JOIN tbltipo_contribuyente tc
ON sn.codcontribuye = tc.codcontribuye
INNER JOIN tblregimenfiscal rf
ON sn.RegimenFiscal = rf.Id
INNER JOIN tblMedioPago mp
ON sn.MedioPago = mp.Id
WHERE sn.codigo = #Codigo
FOR XML PATH ('BusinessPartner'))
SELECT CAST( CAST(#socio AS nvarchar(MAX)) + '(Objeto)' + CAST(#contacto AS nvarchar(MAX)) + '(Objeto)' + CAST(#direccion AS nvarchar(MAX)) as nvarchar(max))
END
END
You can but it will take a little work. You can use C Sharp to create a CLR function that can be passed an nvarchar type and return an nvarchar type. There is no JSON type so it would have to be stored, typically, as a nvarchar(max).
On the C Sharp side it is not hard to do - look at serialization methods. Many users are hesitant to use the CLR but its a short learning curve and can be very useful. Please see the comments below for limitations of CLR.
I have an stored procedure that receives a parameter of store id. I need that variable to be added in a openquery tsql script I am not able to do it.. Look in my code where it says #var thats where the variable will need to work
I tried to reference to this https://support.microsoft.com/en-us/help/314520/how-to-pass-a-variable-to-a-linked-server-query but I cant get it to work
SELECT x.*
FROM (
SELECT tl.title_log_sts_cd
,tl.ro_vin
,tl.ro_store_id
,ll.CurrentLoanStatus
,bc.vin
,bc.BorrowerId
,ll.DisplayLoanNumber
,CONVERT(DATE, CONVERT(VARCHAR(10), ll.CreateDateKey, 7)) LoanDate
,CONCAT (
bb.LastName
,','
,bb.FirstName
) CustomerName
,ll.CurrentPrincipalBalanceAmt + ll.CurrentFeeBalanceAmt TotalDue
FROM OPENQUERY(TLXPRD, 'SELECT * FROM TITLE_LOG
WHERE title_log_sts_cd in (''Ready to Send to DMV'', ''Sent to DMV'')
and ro_store_id =#VAR ') AS tl
JOIN EIS.Borrower.Collateral bc WITH (NOLOCK) ON tl.ro_vin = bc.Vin
LEFT JOIN eis.loan.loan ll WITH (NOLOCK) ON ll.BorrowerId = bc.BorrowerId
AND convert(DATE, tl.created_ts) = CONVERT(DATE, CONVERT(VARCHAR(10), ll.CreateDateKey, 7))
LEFT JOIN EIS.Borrower.Borrower BB ON bb.borrowerid = ll.BorrowerId
) AS x
ORDER BY vin
Expected get some data from oracle join it in with tsql
I didn't totally get what you are trying to do but I hope this is what you are looking for.
FROM OPENQUERY(TLXPRD, concat( 'SELECT * FROM TITLE_LOG
WHERE title_log_sts_cd in (''Ready to Send to DMV'', ''Sent to DMV'')
and ro_store_id =', cast(#VAR as nvarchar(50) ) ))
basically, you had your variable in your string but you want to have it as a value.
so we get the value and put it in your string.
What I'm trying to do is I'm doing a quicksearch with multiple input so that if either any of the textbox is filled even when there are empty textbox, the data can still be retrieved.
The problem that I've faced is when I've tried to do the searching with date range the data failed to search when the date textbox of the date is empty.
Even when other textbox is not null.
I've also tried finding the date range using this method:
and (convert(varchar, DateIssue, 105) between #DateTo and #DateFrom )
next is query that I used for searching
SELECT * FROM [Table2]
where (ID like '%' + #ID + '%' or ID=#ID )
and(Pic_Mgr like '%' + #Picmgr + '%' or Pic_Mgr=#Picmgr)
and(DEPT like '%' + #dept + '%' or DEPT=#dept)
and ( DateIssue between #DateTo and #DateFrom )
next is the code behind that I used to get the parameter value:
cmd.Parameters.AddWithValue("#ID", txtid.Text)
cmd.Parameters.AddWithValue("#Dept", txtIssDept.Text)
cmd.Parameters.AddWithValue("#Picmgr", txtPICMgr.Text)
cmd.Parameters.AddWithValue("#DateTo", txtdateto.Text)
cmd.Parameters.AddWithValue("#DateFrom", txtdatefrm.Text)
I've tried to do the searching without the date range and it work just fine.So I assume there might be problem with my query regarding handling the datetime data .
Is there any suggestion on how to fix this ??
SELECT * FROM [Table2]
where (ID like '%' + #ID + '%' or ID=#ID )
and(Pic_Mgr like '%' + #Picmgr + '%' or Pic_Mgr=#Picmgr)
and(DEPT like '%' + #dept + '%' or DEPT=#dept)
and (DateIssue between
(case when isnull(#DateTo,'') <>'' then #DateTo else DateIssue end) and
(case when isnull(#DateFrom,'') <>'' then #DateFrom else DateIssue end))
I have a report that requires a parameter which may have one value, or a collection of values (jurisdictions assigned to a district office). I can't figure out how to ask sql if a particular value (a.jurisdiction) matched to a value contained in a parameter set up as a table. I have the following code:
DECLARE #District INT = 1614 --Richmond D1
DECLARE #StartDate DATETIME = '20160101'
DECLARE #EndDate DATETIME = '20160731'
DECLARE #Jurisdiction TABLE(Location INT) --= 1223 --Richmond City --multiselect?
IF #District = 1614 --Richmond District 1
INSERT INTO #Jurisdiction Values (1223); --Richmond City
IF #District = 1632 --Newport News District 19
INSERT INTO #Jurisdiction Values (1203); --Newport News
IF #District = 1642 --Fairfax District 29
INSERT INTO #Jurisdiction Values (2568) --Fairfax City
,(1154) ,(1140) ,(1178) ,(1243)
SELECT b.OffenderId
, b.Sex
, b.CurrentLocationId
, b.MasterTermId
, b.ReleaseDate
, b.Jurisdiction
, b.HomePlanAddress
FROM (SELECT DISTINCT o.OffenderId
, o.CurrentLocationId
, CASE WHEN o.GenderId = 12 THEN 'M'
WHEN o.GenderId = 13 THEN 'F'
ELSE 'Unknown' END AS Sex
, mt.MasterTermId
, t.TermId
, CASE WHEN t.GtrdApprovedDate IS NULL AND
t.MprdApprovedDate IS NULL THEN '19000101'
WHEN t.GtrdApprovedDate IS NULL THEN t.MprdApprovedDate
WHEN t.MprdApprovedDate IS NULL THEN t.GtrdApprovedDate
WHEN t.MprdApprovedDate < t.GtrdApprovedDate THEN
t.MprdApprovedDate
ELSE t.GtrdApprovedDate END AS ReleaseDate
, j.HomePlanAddress
, j.Jurisdiction
FROM ind.Offender AS o
INNER JOIN (SELECT oa.OffenderId
, oa.AddressId
, LTRIM(COALESCE(CAST(a.StreetNumber AS
VARCHAR(10)),' ') + COALESCE(a.StreetNumberSuffix
+ ' ',' '
+ COALESCE(a.StreetName + ',','') + COALESCE(' '
+ a.AppartmentNumber + ',','')
+ l.LocationName + ',' + 'VA ' + COALESCE
(a.ZipCode,'')) AS HomePlanAddress
, j.LocationName AS Jurisdiction
FROM ind.Offender_Address AS oa
INNER JOIN ref.Address AS a ON oa.AddressId =
a.AddressId
LEFT JOIN ref.Location AS l ON a.CountyId = l.LocationId
INNER JOIN ref.Location AS j ON a.JurisdictionId = j.LocationId
WHERE a.StateId = 1047
AND EXISTS (SELECT a.JurisdictionId FROM #Jurisdiction)
--AND a.JurisdictionId IN (#Jurisdiction) --
AND oa.AddressTypeId = 5 --Proposed
AND oa.EndDate IS NULL) AS j ON o.OffenderId = j.OffenderId
INNER JOIN scl.MasterTerm AS mt ON o.OffenderId = mt.OffenderId
LEFT JOIN scl.Term AS t ON mt.MasterTermId = t.MasterTermId
WHERE o.CurrentLocationId IS NOT NULL
AND t.TermStatusId <> 631) AS b --Inactive
WHERE b.ReleaseDate BETWEEN #StartDate AND #EndDate
I've tried to find solutions, but most of them refer to using stored procedures, which I can't use in our environment. I tried the EXISTS option on one answer I found, but it gives me all locations, not just the ones in the parameter. Any suggestions?
The reference to the answer SSRS Multiple Value parameter filter based on dataset doesn't seem to address the fact that the District parameter has no one-on-one match to the values used for Jurisdiction. But it gives me something to work on and play around with.
I don't know why
AND a.JurisdictionId IN (#Jurisdiction)
doesn't work for you. As far as I can tell it should.
You can try adding the Filter to the SSRS dataset instead of inside the query. Choose your Jurisdiction for the Expression and your Jurisdiction Parameter as the value.
I am trying to show my PT.TotalAmount(money) field in decimal format upto 3 decimal places. I tried using
CAST(ROUND(123.4567, 3) AS MONEY)
But I get error:
An object or column name is missing or empty. For SELECT INTO
statements, verify each column has a name. For other statements, look
for empty alias names. Aliases defined as "" or [] are not allowed.
Change the alias to a valid name.
Here is my SP:
Select PT.[ID] 'TransactionID', PT.BatchNumber, PT.SequenceNumber, PT.TransactionDate,
PT.TerminalID ,CAST(ROUND(PT.TotalAmount, 2) AS MONEY), PT.TransactionTypeID, TT.TransactionType,
PT.PAN 'EmbossLine',PT.PreBalanceAmount, PT.PostBalanceAmount, RefTxnID,
SettlementDate,PaidCash, CreditAmount, DiscountAmount,
RefPAN, PT.Remarks, ' ' + CashierCard as 'SupervisorCard',St.StoreID
into #Temp
from POS_Transactions PT inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
inner join Staff St on St.CardNumber=PT.CashierCard
where
PT.[ID] not in (Select distinct isnull(TransactionID,0) from Testcards)
and (PT.TransactionDate >= #DateFrom)
and (PT.TransactionDate < #DateTo)
and (PT.TransactionTypeID = #TransactionTypeID or #TransactionTypeID = -999)
select T.*, ' '+ C.EmbossLine as 'EmbossLine', ' '+ C.EmbossLine as 'EmbossLine1',
isnull(C.FirstName,'') +' '+ isnull(C.LastName,'') 'EmbossName',C.FirstName,C.LastName,City.CityName,Country.CountryName,Country.CurrencyName, PM.MerchantID , PM.MerchantName1, C.AccountNumber, C.VehicleNumber
from #Temp T
inner join Card C on C.EmbossLine= T.EmbossLine
inner join Terminal on Terminal.TerminalID = T.TerminalID
inner join Merchant PM on PM.MerchantID = Terminal.MerchantID
inner join City on City.CityID = PM.CityID
inner join Country on Country.CountryID = PM.CountryID
where C.Status <>'E3'
and C.CardID not in (Select distinct isnull(CardID,0) from Testcards)
and (PM.MerchantID =#MerchantID or #MerchantID='-999')
and (C.EmbossLine like '%'+#EmbossLine+'%' or #EmbossLine like '-999')
and (C.FirstName like '%'+#FirstName+'%' or #FirstName like '-999')
and (C.LastName like '%'+#LastName+'%' or #LastName like '-999')
and (PM.CountryID = #CountryID or #CountryID ='-999')
and(PM.CityID = #CityID or #CityID ='-999')
order by T.TransactionDate, MerchantName1, T.BatchNumber, T.SequenceNumber
drop table #Temp
Why am I getting this error? Whats wrong in conversion? When I simply write PT.TotalAmount in my Select statement, the query is completed successfully
Just add any alias name for CAST(ROUND(PT.TotalAmount, 2) AS MONEY) as roundedamont(whatever column name you want) in your sql query.
Select * into statement require each column have distinct name
Select PT.[ID] 'TransactionID', PT.BatchNumber, PT.SequenceNumber, PT.TransactionDate,
PT.TerminalID ,CAST(ROUND(PT.TotalAmount, 2) AS MONEY)<----Give Alias HERE