How can I know the exact column name and value on which the conversion failed while running an SQL query? - sql

I got below error while running a SQL query:
Msg 241, Level 16, State 1, Line 16
Conversion failed when converting date and/or time from character string.
I tried putting it Line by Line so that the error would point out the exact line and it did.
But to my surprise a date / time conversion error was given and pointed to a field which is varchar. In this example it pointed out to 'F1' as Facility field which is the first line of the query.
SELECT 'F1' AS FACILITY, NULL AS NSH, NULL AS EMC, NULL AS OD, NULL AS OA,
URN AS PA,
Title, [First Name], [Second Name], [Third Name], [Family Name], Sex, [Date Of Birth],
[Estimated Date Of Birth ], [Marital Status],
Religion, [Nationality Code],
Nationality, [Passport Number], [Country Of Birth], [Preferred Language],
Address, [PO Box], CONVERT(VARCHAR(15), [Home Phone]) AS [Home Phone], [Office Phone], [Mobile Phone], [Blood Type], VIP, Notes, [National ID], NULL AS [Deceased Date], NULL AS [Deceased Time],
NULL AS [Deceased Indicator (Y/N)], NULL AS [Location Of Death], NULL AS [Death Notified By]
FROM PD_PA
UNION ALL
SELECT 'F2' AS FACILITY, URN AS NSH, NULL AS EMC, NULL AS OD, NULL AS OA, NULL AS PA, Title, [First Name], [Second Name], [Third Name], [Family Name], Sex, BDATE AS [Date Of Birth], [Estimated Date Of Birth], [Marital Status], Religion, [NationalityCode],
Nationality, [Passport Number], [Country], [Preferred Language],
Address, [PO Box], CONVERT(VARCHAR(15), [Home Phone]) AS [Home Phone], [Office Phone], [Mobile Phone] AS [MobilePhone], [Blood Type], VIP, Notes, [National ID], NULL AS [Deceased Date], NULL AS [Deceased Time],
NULL AS [Deceased Indicator (Y/N)], NULL AS [Location Of Death], NULL AS [Death Notified By]
FROM PD_LKIL
Is there a way to trace or know the details of which is the exact field and on which value exactly is the error thrown?
Since my data has over 100k entries, its difficult to trace out and proceed.

If you are on a version greater than 2008 you can replace your CONVERT with TRY_CONVERT.
This returns null if the conversion fails so you can simply check for NULLs in the output.

Related

How can I summarize a set of records into one line where only one record in a column has text and all others are null?

I have invoice data stored in a SQL database and I need a summary query to bring up the Invoice Number, PO number, Date, and Invoice Amount in a single line using an MS Access Query. Unfortunately, the customer PO number is only on one line of the invoice data and pops up on the query result like this.
Invoice Date
Invoice #
PO Number
Amount
8/11/22
12345
NULL
$23.00
8/11/22
12345
456
$00.00
I need the output to look like this instead:
Invoice Date
Invoice #
PO Number
Amount
8/11/22
12345
456
$23.00
My query looks like this:
SELECT
[Invoice Date],
[Invoice #],
[PO Number],
FORMAT$(Sum([Amount])),'$#,##0.00') AS [Amount]
FROM [Invoice Details]
GROUP BY
[Invoice Date],
[Invoice #],
[PO Number]
HAVING
[INVOICE DATE] BETWEEN [8/11/2022] AND [8/11/2022]
ORDER BY
[INVOICE #]
I am still a novice when it comes to SQL queries and am not sure what I am missing here. Any help is appreciated.
Then you can exclude [PO Number] column from your GROUP BY and just take the greater value in each group. I think you can use :
SELECT
[Invoice Date],
[Invoice #],
MAX(Nz([PO Number], 0)) AS [PO Number],
FORMAT$(Sum([Amount])),'$#,##0.00') AS [Amount]
FROM [Invoice Details]
GROUP BY
[Invoice Date],
[Invoice #],
HAVING
[INVOICE DATE] BETWEEN [8/11/2022] AND [8/11/2022]
ORDER BY
[INVOICE #]
Nz is replacing Null by 0 here.
You have very limited example input, but assuming TABLE1
This will work
SELECT Amounts.[Invoice Date], Amounts.[Invoice #], [PO Numbers].[PO Number], Amounts.Amount
FROM Table1 AS Amounts
INNER JOIN Table1 AS [PO Numbers]
ON (Amounts.[Invoice Date] = [PO Numbers].[Invoice Date]) AND (Amounts.[Invoice #] = [PO Numbers].[Invoice #])
WHERE ((([PO Numbers].[PO Number]) Is Not Null) AND ((Amounts.[PO Number]) Is Null));
Looks like this in the query window

Insert value only when column is null

I have 2 different Excel sources
Employee Excel source
Sales Excel source
In my employee source I have multiple folder and in my sales source I have multiple folders as well as multiple sheets, so I had to use two data flow task and two for each loop containers for that purpose.
I need to take the ID column from my employee Excel source, if the ID column in my employee source is not available (null) only if not available in my employee source then I need to get the ID Column from my sales source, they have matching SSN, how can I achieve this?
This is my staging table
SELECT
ID, [SSN],
[Borrower FirstName], [Borrower LastName],
[Borrower Email], [Home Phone], [Cell Phone],
[Marital Status], [Date of Birth],
[Current Street Address], [City], [State], [Zip],
[YearsAtThisAddress], [Sex], [Ethnicity], [Race]
FROM
[Mortgage]
This is my staging table, half of my data from the employee and half from sales.
Employee source has
[ID] ,[SSN] ,[Borrower FirstName] ,[Borrower LastName] ,[Borrower Email] ,[Home Phone] ,[Cell Phone] ,[Marital Status] ,[Date of Birth] ,[YearsAtThisAddress]
and SALES source has
[ID] ,[SSN] ,[Borrower FirstName] ,[Borrower LastName] ,[Borrower Email] ,[Home Phone] ,[Cell Phone] ,[Current Street Address] ,[City] ,[State] ,[Zip]
You have records from two data sources merged together and part of your requirement is to know from which source the record came (whether the ID column is NULL only if from the employee source). Our only clue as to whether a record came from the "employee source" is if there are values in the columns that differ between the two ([Marital Status], [Date of Birth], [YearsAtThisAddress]), but you don't say if any of these nullable, so we must make an assumption. Assuming the value in column [YearsAtThisAddress] can be used to determine the record's source (NOT NULL means "Employee" while NULL means "Sales"), you could do something like this to return the corresponding "Sales" ID number for records matching on SSN when the "Employee" ID number is NULL.
SELECT
CASE WHEN ID IS NULL AND [YearsAtThisAddress] IS NOT NULL
THEN (SELECT TOP (1) ID
FROM [Mortgage]
WHERE [YearsAtThisAddress] IS NULL
AND ID IS NOT NULL
AND [SSN] = m.[SSN]
ORDER BY ID)
ELSE ID
END AS ID,
[SSN],
[Borrower FirstName], [Borrower LastName],
[Borrower Email], [Home Phone], [Cell Phone],
[Marital Status], [Date of Birth],
[Current Street Address], [City], [State], [Zip],
[YearsAtThisAddress], [Sex], [Ethnicity], [Race]
FROM
[Mortgage] AS m

I can't figure out the issue with my UNION query

This is what I'm using:
SELECT [Contact ID], [Contact], [Zip Code], [County]
FROM [Training WLS]
UNION
SELECT [Contact ID], [Contact], [Zip Code], [County]
FROM [WLS TA]
This is the error:
Syntax error(missing operator) in query expression 'Contact ID'.
My guess? The engine's not smart enough to Union columns that have spaces in the names.
Try this instead, and see if it works:
SELECT [Contact ID] as ContactID, [Contact], [Zip Code] as ZipCode, [County]
FROM [Training WLS]
UNION
SELECT [Contact ID] as ContactID, [Contact], [Zip Code] as ZipCode, [County]
FROM [WLS TA]

Workaround for PIVOT statement

I have this query, is taking like 2 minutes to resolve, I need to find a workaround, I know that UNPIVOT has a better solution using CROSS APPLY, is there anything similar for PIVOT?
SELECT [RowId], [invoice date], [GL], [Entité], [001], [Loc], [Centre Cout], [Compte_1], [Interco_1], [Futur_1], [Department], [Division], [Compagnie], [Localisation], [Centre/Cout], [Compte], [Interco], [Futur], [Account], [Mobile], [Last Name], [First Name], [license fee], [GST], [HST], [PST], [Foreign Tax], [Sales Tax License], [Net Total], [Total], [ServiceType], [Oracle Cost Center], [CTRL], [EXPENSE], [Province]
FROM
(SELECT fd.[RowId], fc.[ColumnName], fd.[Value]
FROM dbo.FileData fd
INNER JOIN dbo.[FileColumn] fc
ON fc.[FileColumnId] = fd.[FileColumnId]
WHERE FileId = 1
AND TenantId = 1) x
PIVOT
(
MAX(Value)
FOR [ColumnName] IN ( [invoice date], [GL], [Entité], [001], [Loc], [Centre Cout], [Compte_1], [Interco_1], [Futur_1], [Department], [Division], [Compagnie], [Localisation], [Centre/Cout], [Compte], [Interco], [Futur], [Account], [Mobile], [Last Name], [First Name], [license fee], [GST], [HST], [PST], [Foreign Tax], [Sales Tax License], [Net Total], [Total], [ServiceType], [Oracle Cost Center], [CTRL], [EXPENSE], [Province])
) AS p
Pivots are great, but so are Conditional Aggregations. Also, there would be no datatype conficts or conversions necessary
SELECT [RowId]
,[invoice date] = max(case when [FileColumnId] = ??? then Value end)
,[GL] = max(case when [FileColumnId] = ??? then Value end)
,... more fields
FROM dbo.FileData fd
WHERE FileId = 1
AND TenantId = 1
Group By [RowId]
EDIT
You could add back the join to make it more readable.

Access 2007 Error 3071 -report using parameters

I have a query in MS Access 2007 that pulls data from two different tables and displays in a report. This occurs after a user clicks a button on the main form, which opens a date field parameter form where the user can select two dates. From there the query runs using the two dates the user provided, or the dates are 'faked' if none are selected to fill in the dates. I'm getting a Run-time error 3071, this expression is typed incorrectly, or it is too complex to be evaluated and i'm not sure why.
I run a similar query in another database and it executes perfectly so i'm at a loss.
Query is below,
(SELECT
[Group Name],
tbGroups AS [Group Number],
Analyst,
[Account Manager],
NULL AS [SER Number],
[Received Date] AS [Corporate Recevied],
DateValue(Created) AS [Sales Submitted],
tbBAAcceptedDate AS [BA Accepted],
NULL AS [Submitted to MDSS],
NULL AS [Completed],
NULL AS [Cancelled],
DateDiff("d",[Received Date], IIf([Forms]![frmReportDateFilter].[tbToDate] = '01/01/2116', Date(), CDate([Forms]![frmReportDateFilter].[tbToDate]))) AS [Aging Days Count],
LocalID AS [ID Number]
FROM ChangeRequest
WHERE DateValue([Created]) BETWEEN CDate([Forms]![frmReportDateFilter].[tbFromDate]) AND CDate([Forms]![frmReportDateFilter].[tbToDate]))
UNION ALL (SELECT
tbGroupProgramProductName AS [Group Name],
tbGroups AS [Group Number],
cboAnalyst AS Analyst,
tbAccountManager AS [Account Manager],
tbSERNumber AS [SER Number],
tbCorpReceivedDate AS [Corporate Recevied],
tbBAReceivedDate AS [Sales Submitted],
IIf([tbBAAcceptedDate] > CDate([Forms]![frmReportDateFilter].[tbToDate]), NULL, [tbBAAcceptedDate]) AS [BA Accepted],
IIf([tbSubmittedToMDSS] > CDate([Forms]![frmReportDateFilter].[tbToDate]), NULL, [tbSubmittedToMDSS]) AS [Submitted to MDSS],
DateValue(tbCompleteDate) AS [Completed],
DateValue(tbCancelDate) AS [Cancelled],
DateDiff("d",tbCorpReceivedDate, IIf([Forms]![frmReportDateFilter].[tbToDate] = '01/01/2116', Date(), CDate([Forms]![frmReportDateFilter].[tbToDate]))) AS [Aging Days Count],
LocalID AS [ID Number]
FROM tblDD
WHERE DateValue([tbBAReceivedDate]) BETWEEN CDate([Forms]![frmReportDateFilter].[tbFromDate]) AND CDate([Forms]![frmReportDateFilter].[tbToDate]))
ORDER BY [Group Name];
Any help is greatly appreciated.
Specify the control as Date. Something like this with no CDate - and no outer parenthesis:
PARAMETERS
[Forms]![frmReportDateFilter].[tbFromDate] Date,
[Forms]![frmReportDateFilter].[tbToDate] Date;
SELECT
[Group Name],
tbGroups AS [Group Number],
Analyst,
[Account Manager],
NULL AS [SER Number],
[Received Date] AS [Corporate Recevied],
DateValue(Created) AS [Sales Submitted],
tbBAAcceptedDate AS [BA Accepted],
NULL AS [Submitted to MDSS],
NULL AS [Completed],
NULL AS [Cancelled],
DateDiff("d",[Received Date], IIf([Forms]![frmReportDateFilter].[tbToDate] = #01/01/2116#, Date(), [Forms]![frmReportDateFilter].[tbToDate])) AS [Aging Days Count],
LocalID AS [ID Number]
FROM ChangeRequest
WHERE DateValue([Created]) BETWEEN [Forms]![frmReportDateFilter].[tbFromDate] AND [Forms]![frmReportDateFilter].[tbToDate]
UNION ALL
SELECT
tbGroupProgramProductName AS [Group Name],
tbGroups AS [Group Number],
cboAnalyst AS Analyst,
tbAccountManager AS [Account Manager],
tbSERNumber AS [SER Number],
tbCorpReceivedDate AS [Corporate Recevied],
tbBAReceivedDate AS [Sales Submitted],
IIf([tbBAAcceptedDate] > [Forms]![frmReportDateFilter].[tbToDate], NULL, [tbBAAcceptedDate]) AS [BA Accepted],
IIf([tbSubmittedToMDSS] > [Forms]![frmReportDateFilter].[tbToDate], NULL, [tbSubmittedToMDSS]) AS [Submitted to MDSS],
DateValue(tbCompleteDate) AS [Completed],
DateValue(tbCancelDate) AS [Cancelled],
DateDiff("d",tbCorpReceivedDate, IIf([Forms]![frmReportDateFilter].[tbToDate] = #01/01/2116#, Date(), [Forms]![frmReportDateFilter].[tbToDate])) AS [Aging Days Count],
LocalID AS [ID Number]
FROM tblDD
WHERE DateValue([tbBAReceivedDate]) BETWEEN [Forms]![frmReportDateFilter].[tbFromDate] AND [Forms]![frmReportDateFilter].[tbToDate]
ORDER BY [Group Name];