T-SQL code producing inconsistently erroneous values - sql-server

The above picture if a screen cap of the output from a report I've been making using t-SQL tables and views. Each column has two values the first being the current number and then following the forward slash is the difference value for each week. These numbers look great for most of my reports and yet as you can see the Total column seems to have a completely erroneous value for the difference.
This table was created using the following code
SELECT
ISNULL(a.[LRPR Biospecimen Consent], 'Missing') AS Consent,
CONVERT(varchar, a.Oppong) + ' / ' + CONVERT(varchar, a.Oppong - ISNULL(b.Oppong, 0)) AS Oppong,
CONVERT(varchar, a.Tousimis) + ' / ' + CONVERT(varchar, a.Tousimis - ISNULL(b.Tousimis, 0)) AS Tousimis,
CONVERT(varchar, a.Willey) + ' / ' + CONVERT(varchar, a.Willey - ISNULL(b.Willey, 0)) AS Willey,
CONVERT(varchar, a.Anderson) + ' / ' + CONVERT(varchar, a.Anderson - ISNULL(b.Anderson, 0)) AS Anderson,
CONVERT(varchar, a.Bacarra) + ' / ' + CONVERT(varchar, a.Bacarra - ISNULL(b.Bacarra, 0)) AS Bacarra,
CONVERT(varchar, a.McMahon) + ' / ' + CONVERT(varchar, a.McMahon - ISNULL(b.McMahon, 0)) AS McMahon
FROM
dbo.vw_RPT_Ourisman_BiospecimenConsentWithProvider_Pivot a
LEFT OUTER JOIN dbo.tbl_vw_RPT_Ourisman_BiospecimenConsentWithProvider_Pivot b
ON ...
Variants of this code (with just pathnames changed has given accurate total values for the numbers on both sides of the forward slash.I am a novice SQL user and I just can't seem to figure out why this code has stopped working.
Any helpful advice is much appreciated
EDIT
Below is the code used to create the dbo.vw_RPT_Ourisman_BiospecimenConsentWithProvider_Pivot Total values.
With T as ( SELECT [LRPR Biospecimen Consent], [Oppong, Bridget A] AS Oppong, [Tousimis, Eleni] AS Tousimis, [Willey, Shawna] AS Willey, [Anderson, Lyndsay] AS Anderson,
[Bacarra, Minna Manalo] AS Bacarra, [McMahon, Ann] AS McMahon
FROM vw_RPT_Ourisman_BiospecimenConsentWithProvider_List c PIVOT (count([Breast Provider]) FOR [Breast Provider] IN ([Oppong, Bridget A], [Tousimis, Eleni],
[Willey, Shawna], [Anderson, Lyndsay], [Bacarra, Minna Manalo], [McMahon, Ann])) piv
WHERE [LRPR Biospecimen Consent] IS NOT NULL)
SELECT *
FROM T
UNION ALL
SELECT 'Total', SUM(Oppong), SUM(Tousimis), SUM(Willey), SUM(Anderson), SUM(Bacarra), SUM(McMahon)
FROM T

Related

SQL Server error: Conversion failed when converting date and/or time from character string

I am trying to write this code, but I keep getting this error. AUSVN and AUZTV columns are of type nvarchar. Please help me.
SELECT
CONVERT(DATETIME, (CONVERT(VARCHAR, CONVERT(DATE, AUSVN)) + ' ' + (LEFT(AUZTV, 2) + ':' + SUBSTRING(AUZTV, 3, 2) + ':' + RIGHT(AUZTV, 2))))
FROM
VIQMEL
AUSVN column has values like 2018-04-27 14:20:18.000.

Need help adding WHERE clause in pre-written SQL statement

Preface: my SQL is rudimentary. I received a SQL query from a vendor, it selects and exports every single employee comment and other data from a few different DBs as CSV meant for import, it was written by them but they're not helping with this request. The query is pulling so much data it makes a large time consuming file for import. So I want to add to / modify the query to have a "WHERE date > whateverdate" to narrow my results to recent data. For example, I want to pull only comments entered in the past 2 days.
The column I'm looking to add the clause for is the column "A.CMS502", defined as datetime. I believe this is the only relevant column in this query. An example date in this column is "2003-10-06 17:05:21.000". I am using SQL Server 2008 if it helps. Is it possible here? Thank you.
SELECT
'ID,Acct/LnNbr,NoteCreatedDate,CollectorId,ApplytoAll,Note'
UNION ALL
SELECT
ID + ',' + ID + ',' + NoteCreatedDate + ',' + CollectorId + ',' + 'No' + ',' + Note
FROM
(SELECT
CASE WHEN SUBSTRING(A.CMS301,LEN(A.CMS301),1) = 'S'
THEN SUBSTRING(A.CMS301,1,LEN(A.CMS301) - 1)
ELSE A.CMS301
END + '-' +
CASE WHEN SUBSTRING(A.CMS301,LEN(A.CMS301),1) = 'S'
THEN 'S' ELSE 'L'
END AS [ID],
REPLACE(CONVERT(VARCHAR, A.CMS501, 10), '-', '') AS [NoteCreatedDate],
CASE WHEN U.CMS1201 IS NOT NULL
THEN U.CMS1205 + ' ' + U.CMS1204
ELSE (SELECT CMS1205 + ' ' + CMS1204 FROM sysUSER WHERE CMS1201 = 'PSUSER')
END AS CollectorId,
CAST(A.CMS512 AS NVARCHAR(MAX)) AS [Note]
FROM
ACTIVITY AS A
LEFT JOIN
sysUSER AS U ON A.CMS503 = U.CMS1201
WHERE
A.CMS504 NOT IN (411,500,511,711,804,900,901,903,907,2000,999777)
AND A.CMS504 NOT BETWEEN 1102 AND 1199) AS S
Try this, this will output last 2 days.
SELECT 'ID,Acct/LnNbr,NoteCreatedDate,CollectorId,ApplytoAll,Note'
UNION ALL
SELECT ID + ',' + ID + ',' + NoteCreatedDate + ',' + CollectorId + ',' + 'No' + ',' + Note
FROM
(
SELECT CASE WHEN SUBSTRING(A.CMS301,LEN(A.CMS301),1) = 'S' THEN SUBSTRING(A.CMS301,1,LEN(A.CMS301) - 1) ELSE A.CMS301 END
+ '-' + CASE WHEN SUBSTRING(A.CMS301,LEN(A.CMS301),1) = 'S' THEN 'S' ELSE 'L'
END AS [ID]
,REPLACE(CONVERT(varchar,A.CMS501,10),'-','') AS [NoteCreatedDate]
,CASE WHEN U.CMS1201 IS NOT NULL THEN U.CMS1205 + ' ' + U.CMS1204 ELSE
(SELECT CMS1205 + ' ' + CMS1204 FROM sysUSER WHERE CMS1201 = 'PSUSER')
END AS CollectorId
,CAST(A.CMS512 AS nvarchar(max)) AS [Note]
FROM ACTIVITY AS A
LEFT JOIN sysUSER AS U
ON A.CMS503 = U.CMS1201
WHERE A.CMS504 NOT IN (411,500,511,711,804,900,901,903,907,2000,999777)
AND A.CMS504 NOT BETWEEN 1102 AND 1199
AND A.CMS502 >= DATEADD(D, -2, GETDATE())
) AS S

Generate XML from SQL issue

I need to generate XML in the following format :
I haven't gone too far with the xml part of the task as I encountered following situation, you can tell that this obviously was not my intention.
How can I handle this properly considering that BBAN and IBAN need to be inside AccountNoas well as that I want it formatted according to the first picture.
The complete query along with my fair attempt of generating xml looks like this:
DECLARE #AccountType NVARCHAR(3);
DECLARE #kodBanke NVARCHAR(3);
SET #AccountType = 'T';
SET #kodBanke = ( SELECT vrednost FROM dbini WHERE IDENT = 'KOD' AND SECTION = 'PP' );
WITH Ent_Posta
AS
(
SELECT e.naziv,p.posta,e.sifra
FROM entitet AS e
INNER JOIN poste AS p ON e.sifra = p.entitet
)
SELECT (
SELECT
[dbo].[brojracuna](#kodBanke,i.partija) AS 'BBAN',
[dbo].[GENERATEIBAN](i.partija) AS 'IBAN'
FOR XML PATH('AccountNo'), ELEMENTS, ROOT('Account')
),
#accountType AS 'AccountType',
(a.ime + ' ( ' + a.roditel + ' ) ' + a.prezime) AS 'Name',
a.embg AS 'UID',
CASE status
WHEN 2 THEN 'A'
WHEN 4 THEN 'B'
WHEN 8 THEN 'U'
END AS 'Status',
c.sifra AS 'Territory',
#kodBanke as 'ID_Bank',
REPLACE(CONVERT(VARCHAR(10), i.DOTVaRANJE, 120), '.', '') + '-' + RIGHT( '0' + CONVERT(VARCHAR(2), DATEPART(hh, i.DOTVaRANJE)), 2) + '' + RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(mi, i.DOTVaRANJE)), 2) + '' + RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(s, i.DOTVaRANJE)),2) AS OpeningDate,
REPLACE(CONVERT(VARCHAR(10),'2006.09.28 ', 120), '.', '') + '-' + RIGHT( '0' + CONVERT(VARCHAR(2), DATEPART(hh, '2006.09.28' )), 2) + '' + RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(mi, '2006.09.28 ')), 2) + '' + RIGHT('0' + CONVERT(VARCHAR(2),DATEPART(s,'2006.09.28 ')),2) AS ClosingDate
FROM adresar AS a
INNER JOIN istdden AS i
ON a.embg = i.embg
INNER JOIN Ent_Posta as c
ON a.postbroj = c.posta
FOR XML PATH ('Account'), ROOT('Accounts');
Upon removal of this part I get...
<Accounts>
<Account>
<BBAN>5710543102313248</BBAN>
<IBAN>BA39531231634039248</IBAN>
<AccountType>T</AccountType>
<Name>DARKO ( DRAGAN ) TESIC</Name>
<UID>0000005467234</UID>
<Status>A</Status>
<Territory>1</Territory>
<ID_Bank>571</ID_Bank>
<OpeningDate>20081205-000000</OpeningDate>
<ClosingDate>20060928-000000</ClosingDate>
</Account>
... but now AccountNO is missing.
Your question is not all clear, but - if I get this correctly - you are fighting with 1:1 values, but within some deeper nesting.
You can use an XPath-like expression within [] in connection with FOR XML PATH. Check this out:
SELECT 'blah' AS FirstNode
,'blub' AS [SecondNode/OneDeeper]
,'blib' AS [SecondNode/OneMore]
,'ballaballa' AS [ThirdNode]
FOR XML PATH('row'),ROOT('root');
the resutl (look especially at <SecondNode>:
<root>
<row>
<FirstNode>blah</FirstNode>
<SecondNode>
<OneDeeper>blub</OneDeeper>
<OneMore>blib</OneMore>
</SecondNode>
<ThirdNode>ballaballa</ThirdNode>
</row>
</root>
If this is not what you need, please tag with the actual RDBMS (product and version) and please read How to ask a good SQL question and How to create a MCVE
For your issue it might be enough to use AS [AccountNo/IBAN] in your query.

SQL Server query: Concatenating two strings and converting to datetime changes the format thereby Datedifference calculated is wrong

Below is the query which I am trying to run:
SELECT
CONVERT(DATETIME,('12/1/2016' +' '+ '2:00:00')) AS A,
CONVERT(DATETIME,('12/1/2016' +' '+ '2:00:00')) AS B,
DATEDIFF(HOUR, CONVERT(DATETIME, ('12/1/2016' + ' ' + '2:00:00')), CONVERT(DATETIME, ('12/1/2016' + ' ' + '2:00:00'))) as DateDiffernce
Output is:
A B DateDiffernce
2016-12-01 02:00:00.000 2016-12-01 02:00:00.000 0
Let's take 12/1/2016 here the format is DD/MM/YYYY. After using convert function it is getting changed to YYYY-MM-DD which is fine the problem is places are changed i.e 12/1/2016 to 2016-12-01 12 which was the date is shifted or considered as month - which should not happen.
I even tried another query to restrict this conversion which didn't help:
SELECT
CONVERT(DATETIME, CONVERT(CHAR(10), '12/1/2016', 112)
+ ' ' + CONVERT(CHAR(8), '2:00:00', 108))
Kindly help..
Please check #Panagiotis Kanavos comment. He is right. Your query would work fine. Please change the time value like the below to get the DateDifference value.
SELECT CONVERT(DATETIME, ('13/1/2016' + ' ' + '2:00:00'),103) AS A
,CONVERT(DATETIME, ('13/1/2016' + ' ' + '13:00:00'),103) AS B
,DATEDIFF(HOUR, CONVERT(DATETIME, ('13/1/2016' + ' ' + '2:00:00'),103), CONVERT(DATETIME, ('13/1/2016' + ' ' + '13:00:00'),103)) AS DateDiffernce
Hello All Thankyou for your inputs, i was able to solve the issue by
using following code
SET DATEFORMAT YDM
Cheers!! Enjoy coding

get custom date time format

I want to display date time as eg. Dec 1, 09 11:22:45 PM using SQL query
Currently my format is :
DATENAME(Month, (((MachineGroups.TimeAdded*10000000)+ 621355968000000000) -599266080000000000) / 864000000000) + SPACE(1) + DATENAME(d, (((MachineGroups.TimeAdded*10000000)+ 621355968000000000) - 599266080000000000) / 864000000000) +', ' + DATENAME(year, (((MachineGroups.TimeAdded*10000000)+621355968000000000) - 599266080000000000) /864000000000) + SPACE(1)+DATENAME (hour,(((MachineGroups.TimeAdded*10000000)+621355968000000000) - 599266080000000000) / 864000000000) + ':' +DATENAME (minute,(((MachineGroups.TimeAdded*10000000)+ 621355968000000000) - 599266080000000000) / 864000000000) + ':' +DATENAME (second,(((MachineGroups.TimeAdded*10000000)+ 621355968000000000) - 599266080000000000) / 864000000000) AS Expr2
Ussing the above i get eg. December 1, 2009 23:22:45
I tries using the cuatom formata of "MMM" and "yy" but it did not work
any suggestions???
thanks
Is there no way i can use the Datename property above to get my desired format??
It is much easier and more efficient to return the value as a generic datetime object and format it in your UI.
What is your motivation for returning a formatted date from the database?
This will get you everything but AM/PM:
declare #myDate datetime
set #myDate = getdate()
select LEFT(DATENAME(MM, #myDate),3) + ' ' +
RIGHT('0'+DATENAME(DD, #myDate),2) + ', ' +
RIGHT(DATENAME(YY, #myDate),2) + ' ' +
convert(varchar,(DATEPART(hour, #myDate))) + ':' + convert(varchar,(DATEPART(minute, #myDate))) + ':' + convert(varchar,(DATEPART(second, #myDate)))
There are various ways to achieve the AM/PM values, among them would be a substring of:
SELECT convert(varchar, getdate(), 109)
As well as MONTHNAME (which you're already using), check out DATEPART. It's also not far from the CONVERT format of 9 [via CONVERT (VARCHAR(20), #datetime, 9)], so you could manipulate this as well.
Yet another option is using two CONVERTs ... this gives you what you want, but the time's in 24hr format:
SELECT CONVERT(VARCHAR(20), #datetime, 107) + ' ' + CONVERT (VARCHAR(20), #datetime, 108)
Use a different conversion function and a bit of string manipulation to get you 12 hour with AM/PM. Or do something like this:
SELECT CAST(DATEPART(hh, #datetime) - 12 AS VARCHAR)
+ ':' + CAST(DATEPART(mi, #datetime) AS VARCHAR)
+ ':' + CAST(DATEPART(ss, #datetime) AS VARCHAR)
+ CASE WHEN DATEPART(hh, #datetime) BETWEEN 0 AND 11 THEN ' AM' ELSE ' PM' END
Neither this or manipulating the output of CONVERT is pretty, but they're your best options.
HOWEVER: as others have pointed out though, this is normally better done client/UI-side rather than SQL-side.
You can find all supported SQL Server formats here.
To select in a format equivalent to Dec 1, 09 11:22:45 PM, you could use the date from format 7: Mon dd, yy. The time can be assembled from format 109: mon dd yyyy hh:mi:ss:mmmAM (or PM). Combined:
select
convert(varchar(10), getdate(), 7) +
' ' +
stuff(
substring(
convert(varchar(32), getdate(), 109)
,13,14) -- Substring HH:mi:ss.mmmAM
,9,4,' ') -- Replace .mmm by one space
This should print:
Nov 24, 09 4:58:36 PM
The second of the two spaces between 09 and 4 is reserved for a two-number hour, like 11:59:59 PM. :)

Resources