Data type mismatch while fetching data from one table into another - sql

I'm trying to get data from a table CustomerCase of database TD_EDD; into a table CustomerCase of database DsVelocity. The problem is whenever I try to get the data, error message is generated because in CustomerCase table of TD_EDD database, there are 3 columns: LOB, ReferralSource and CaseType of type varchar; while in CustomerCase table of DsVelocity database, the 3 matching columns are LOBID, ReferralSourceID and CaseTypeID and are of type int.
I've simply tried to execute this query:
INSERT INTO [DsVelocity].[dbo].[CustomerCase]
([CustomerID]
,[Tier]
,[EscalationDate]
,[ReferralSourceID]
,[ICMSID]
,[LOBID]
,[TriggerRC]
,[TriggerAccount]
,[Project]
,[CaseTypeID]
,[DateDue]
,[SARFiledYes]
,[SARFiledNo]
,[TeamLead]
,[SARAmount]
,[InitialNotes]
,[WorkFlowStatus]
,[CaseDecision]
,[AccountsReviewed]
,[ActionDate]
,[SecondLvlReview]
,[CompanyType]
,[IfOther]
,[ClientType]
,[MergeFlag]
,[MergeCaseID]
,[AMLREP]
,[HighRiskYes]
,[HighRiskNo]
,[AutoCreated]
,[FileName]
,[SourceRefDate]
,[SourceRefID]
,[ETMAdd]
,[ETMRemove]
,[ETMDate]
,[Investigator]
,[InUseBy])
SELECT [CustomerID]
,[Tier]
,[EscalationDate]
,[ReferralSource]
,[ICMSID]
,[LOB]
,[TriggerRC#]
,[TriggerAccount]
,[Project]
,[CaseType]
,[DateDue]
,[SARFiledYes]
,[SARFiledNo]
,[TeamLead]
,[SARAmount]
,[InitialNotes]
,[WorkFlowStatus]
,[CaseDecision]
,[AccountsReviewed]
,[ActionDate]
,[2ndLvlReview]
,[CompanyType]
,[IfOther]
,[ClientType]
,[MergeFlag]
,[MergeCaseID]
,[AMLREP]
,[HighRiskYes]
,[HighRiskNo]
,[AutoCreated]
,[FileName]
,[SourceRefDate]
,[SourceRefID]
,[ETMAdd]
,[ETMRemove]
,[ETMDate]
,[Investigator]
,[InUseBy]
FROM [TD_EDD].[dbo].[CustomerCase]
and then ran into the following error:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'CRR' to data type int.
CRR is a data in the column ReferralSource.
Similar messages may appear in case of LOB and CaseType columns
The database server I'm using is MSSQL Server 2008 R2.
What is the solution to this problem???
EDIT-1: Tried using Inner Join with LOB, CaseType and ReferralSource tables. Now the error has disappeared, query ran ok, but I get data from only 2 rows. I can't understand why?????? I had more than 40 data in the [TD_EDD].[dbo].[CustomerCase] table, so all these data were supposed to be passed to the [DsVelocity].[dbo].[CustomerCase] table. What's wrong?
EDIT-2: Got it. CaseType column in [TD_EDD].[dbo].[CustomerCase] had mostly NULL values, only 2 rows had valid data. Hence, only 2 rows were sent to [DsVelocity].[dbo].[CustomerCase] becasue no corresponding ID match can be made for null values. I guess I figured it out myself. Thanks everyone.

You could try casting as already suggested or probably you're referring the wrong field name, like (I shall focus only on the one that has an error):
SELECT
,[ReferralSourceID]
,[LOBID]
,[CaseTypeID]
FROM [TD_EDD].[dbo].[CustomerCase]
Instead of ReferralSource use ReferralSourceID, instead of LOB use LOBID and instead of CaseType use CaseTypeID.
Or probably you need to reference the Reference Table on those fields like:
SELECT
,[ReferralSourceID]
,[LOBID]
,[CaseTypeID]
FROM [TD_EDD].[dbo].[CustomerCase] CC
INNER JOIN Referral R
ON CC.ReferralSource = R.ReferralSource
INNER JOIN LobTbl L
ON CC.LOB = L.LOB
INNER JOIN CaseTypeTbl C
ON CC.CaseType = C.CaseType

Try casting your varchar columns to int (assuming the data in your source columns is valid for int columns in target)
SELECT CAST(ReferralSource AS int),
CAST(LOB AS int),
CAST(CaseType AS int)
--etc

Related

Conversion failed when converting nvarchar

Can someone assist with the error I have below on this statement
SELECT
sh.INTERNAL_SHIPMENT_NUM,sh.shipment_id, sh.carrier,
sh.carrier_service,sh.carrier_type,sh.route,sh.customer_name,sh.total_lines,
sh.total_weight,sh.total_volume,sh.SCHEDULED_SHIP_DATE AS SCHEDULED_SHIP_DATE,sh.total_qty,sh.trailing_sts,
CASE
WHEN sh.CUSTOMER IN (46003204, 30321)
THEN 'CHUB'
ELSE ''
END AS CUSTOMER,
(SELECT TOP 1 sd.customer_po
FROM shipment_detail sd
WHERE sd.internal_shipment_num = sh.internal_shipment_num
ORDER BY sd.CUSTOMER_PO desc) as CUSTOMER_PO,
SH.REJECTION_NOTE
FROM
shipment_detail sd
INNER JOIN
shipment_header_view sh ON sd.INTERNAL_SHIPMENT_NUM = sh.INTERNAL_SHIPMENT_NUM
LEFT OUTER JOIN
RYDI_orders RO ON SH.SHIPMENT_ID = RO.DELIVERY_id
WHERE
sh.leading_sts = 100 AND sh.trailing_sts = 100
GROUP BY
sh.INTERNAL_SHIPMENT_NUM,sh.shipment_id, sh.carrier,
sh.carrier_service, sh.carrier_type, sh.customer,
sh.route, sh.customer_name, sh.total_lines,
sh.total_weight, sh.total_volume, sh.SCHEDULED_SHIP_DATE,
sh.total_qty, sh.trailing_sts, SH.REJECTION_NOTE
Error:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value '50310H' to data type int.
My money is on the join or the where clause as your problem. I’ll offer debugging suggestions that may help since I can’t comment.
To identify: If you have any idea what the 50310H is, if is it a shipment number or whatever, you can find it faster and compare the fields in the two tables. Another option is to just compare the table properties and see what the fields are. There might be two tables with values you’re trying to match, but one is int and one is nvarchar.
To solve: The ultimate solution is to
cast(whateverintfield as nvarchar)
to stop it from arguing with you, once you’ve identified the offender. Good luck.

How to Take two SQL queries of a column of substrings to search database using the appended result of the other

I have two select statements that both contain a column of substrings that derived from a database table. They are substrings derived from a varchar that should be an XML, but were saved as varcars because they could be not well-formed and potentially invalid.
I am trying to take the table that results in the 1st query, a list of 50 Varchars, and search the database using the 2nd query. I could get from 0 to n SQLRelatesMessageID sets from each SQLmessageID if I use each row in the first query and append a string to get the node ("z4480" is an example here).
I have tried a cursor implementation but the performance detered me from finishing it. Join doesn't work if you try giving the substring column with an as alias. What steps should I do to get the overall list of SQLRelatesMessageIDs. My goal is to get all MessageLogId (3 in picture) given a NCPDPID.
I am using SQL Server Manager 2012.
--1--Recieves a list based on a given NCPDPID node Value
select substring(m.message, charindex('<MessageID>', m.message)+11, charindex('</MessageID>', m.message)-charindex('<MessageID>', m.message)-11) as
SQLmessageID from messagelog m where message like '%<NCPDPID>'+'1234567'+'</NCPDPID>%'
--2--Selects messageID from top select and searches RelatesToMessageID node
select substring(r.message, charindex('<RelatesToMessageID>', r.message)+20, charindex('</RelatesToMessageID>', r.message)-charindex('<RelatesToMessageID>', r.message)-20) as SQLRelatesMessageID, * from messagelog r
where message like ('%<RelatesToMessageID>'+'z4480'+'</RelatesToMessageID>%')
This works for this answer.
---main
SELECT * FROM
(
select substring(m.message, charindex('<MessageID>', m.message)+11, charindex('</MessageID>', m.message)-charindex('<MessageID>', m.message)-11) as SQLmessageID from messagelog m
where message like '%<NCPDPID>1234567</NCPDPID>%' and dateTime > '3/01/2016'
) a JOIN
(
select
substring(r.message, charindex('<RelatesToMessageID>', r.message)+20, charindex('</RelatesToMessageID>', r.message)-charindex('<RelatesToMessageID>', r.message)-20) as SQLRelatesMessageID,
message,
messagelogid from messagelog r
where
dateTime > '3/01/2016' AND
message LIKE ('%<RelatesToMessageID>%</RelatesToMessageID>%')
) b ON b.SQLRelatesMessageID = a.SQLmessageID

SQL returns the unique identifier instead of the value in my Access UNON ALL SQL

So here is my project using MS Access 2010,
I have developed 2 queries to select 2 different reading periods. These queries are called CycleStart and CycleEnd. When I run these 2 queries individually I get expected output results. these 2 queries pull data from tables with a couple lookup fields in them. So the lookup fields use other tables where there are only 2 columns. The next step I use SQL to create a UNION ALL query to bring these 2 cycle queries together for reporting purposes. The problem I run into is that my resulting Union query does not output the same information as the 2 individual cycle queries.
Now the specific issues. My cycle queries have a couple lookup fields referencing another table. For example the Read_Cycle field comes for a table(Read_Cycles) and only has 2 columns, the unique identifer assigned by Access and the Read_Cycle column with the data I enter. When I run the cycle queries the field for Read_Cycle returns the Read_Cycle data as expected, but the union query does not. So here is some structure of my project:
Read_Cycles Table
|ID Col1 | |Cycle_ID Col2|
1 Spring
2 Fall
3 Winter
The data tables behind the CycleStart and the CycleEnd have fields that are lookup values referencing the above described Read_Cycles table.
Query CycleStart and CycleEnd return Spring or fall or winter, which ever value is associated with the record, correctly.
however, the problem I have is that the Union SQL Query returns the ID instead of the value, so instead of getting Fall, I get the 2.
Here is my UNION ALL SQL........
SELECT "CycleEnd" AS source,
[CycleEnd].[Recloser_SerialNo],
[CycleEnd].[Read_Date],
[CycleEnd].[3_Phase_Reading],
[CycleEnd].[A_Phase_Reading],
[CycleEnd].[B_Phase_Reading],
[CycleEnd].[C_Phase_Reading],
[CycleEnd].[Read_Cycle],
[CycleEnd].[PoleNo],
[CycleEnd].[Substation],
[CycleEnd].[Feeder],
[CycleEnd].[Feeder_Description],
[CycleEnd].[Recloser_Location]
FROM [CycleEnd]
UNION ALL
SELECT "CycleStart" AS source,
[CycleStart].[Recloser_SerialNo],
[CycleStart].[Read_Date],
[CycleStart].[3_Phase_Reading] * - 1,
[CycleStart].[A_Phase_Reading] * - 1,
[CycleStart].[B_Phase_Reading] * - 1,
[CycleStart].[C_Phase_Reading] * - 1,
[CycleStart].[Read_Cycle],
[CycleStart].[PoleNo],
[CycleStart].[Substation],
[CycleStart].[Feeder],
[CycleStart].[Feeder_Description],
[CycleStart].[Recloser_Location]
FROM [CycleStart];
All other fields are coming across just fine and as expected, I have narrowed it down to only fields that are a lookup in the original tables.
Any help would be greatly appreciated. Also my SQL experience is really limited so example code would help greatly.
UPDATE:
here is the sql from the CycleEnd that works. I got this by building the query then changing to the SQL view...
SELECT Recloser_Readings.Recloser_SerialNo,
Recloser_Readings.Read_Date,
Recloser_Readings.[3_Phase_Reading],
Recloser_Readings.A_Phase_Reading,
Recloser_Readings.B_Phase_Reading,
Recloser_Readings.C_Phase_Reading,
Recloser_Locations.PoleNo,
Recloser_Locations.Substation,
Recloser_Locations.Feeder,
Recloser_Locations.Feeder_Description,
Recloser_Locations.Recloser_Location,
Recloser_Readings.Read_Cycle
FROM (
Recloser_Inventory LEFT JOIN Recloser_Locations
ON Recloser_Inventory.PoleNo = Recloser_Locations.PoleNo
)
RIGHT JOIN Recloser_Readings
ON Recloser_Inventory.Serial_No = Recloser_Readings.Recloser_SerialNo
WHERE (((Recloser_Readings.Read_Cycle) = "8"));
UPDATE#2
I noticed I grabbed the wrong code that references the Read_Cycles table. Here it is...
SELECT Read_Cycles.Cycle_ID, Read_Cycles.ID
FROM Read_Cycles
ORDER BY Read_Cycles.Cycle_ID DESC;
UPDATE : SYNTAX ERROR FROM THE FOLLOWING CODE!!
SELECT "CycleEnd" as source,
[CycleEnd].[Recloser_SerialNo],
[CycleEnd].[Read_Date],
[CycleEnd].[3_Phase_Reading],
[CycleEnd].[A_Phase_Reading],
[CycleEnd].[B_Phase_Reading],
[CycleEnd].[C_Phase_Reading],
[CycleEnd].[Read_Cycle],
[CycleEnd].[PoleNo],
[CycleEnd].[Substation],
[CycleEnd].[Feeder],
[CycleEnd].[Feeder_Description],
[CycleEnd].[Recloser_Location]
FROM [CycleEnd] JOIN [Read_Cycles] ON [CycleEnd].[Read_Cycle] = [Read_Cycles].[ID]
UNION ALL SELECT "CycleStart" as source,
[CycleStart].[Recloser_SerialNo],
[CycleStart].[Read_Date],
[CycleStart].[3_Phase_Reading]*-1,
[CycleStart].[A_Phase_Reading]*-1,
[CycleStart].[B_Phase_Reading]*-1,
[CycleStart].[C_Phase_Reading]*-1,
[CycleStart].[Read_Cycle],
[CycleStart].[PoleNo],
[CycleStart].[Substation],
[CycleStart].[Feeder],
[CycleStart].[Feeder_Description],
[CycleStart].[Recloser_Location]
FROM [CycleStart] JOIN [Read_Cycles] ON [CycleStart].[Read_Cycle] = [Read_Cycles].[ID];

Type conversion failure in update query

I'm fairly new to Access so this is driving me a little crazy.
I'm creating an inventory database and want to count the number of items in stock to update an ordering form. Received items are assigned an order code, and I want to count the number of instances of each order code found within the master table. I have a make table query which does this just fine:
SELECT PrimerList.PrimerName
, First(Primer_Master.FR) AS FR
, Primer_Master.OrderCode
, Count(Primer_Master.OrderCode) AS InStock
INTO PrimerOrder
FROM PrimerList
LEFT JOIN Primer_Master ON PrimerList.ID = Primer_Master.PrimerName
GROUP BY PrimerList.PrimerName
, Primer_Master.OrderCode
, Primer_Master.PrimerName
, Primer_Master.FR
, Primer_Master.Finished
HAVING ((([Primer_Master]![Finished])=No));
I want to use PrimerOrder to update an order list table PrimerOrderList which has all of the different possible order codes, updating the InStock value for records with matching OrderCode:
UPDATE PrimerOrderList
SET PrimerOrderList.InStock = PrimerOrder.InStock
WHERE (((PrimerOrderList.OrderCode)=[PrimerOrder].[OrderCode]));
However, when I try to run it I get parameter boxes which pop-up asking for PrimerOrder.OrderCode and PrimerOrderList.OrderCode. Even if I put in a valid value for each, I get a type conversion failure. I've checked the data types for both tables and don't see how there could be a type conversion failure - both are set to text.
Any insight would be greatly appreciated! Thanks in advance!
You haven't included the PrimerOrder table in your query. Should be:
UPDATE PrimerOrderList INNER JOIN PrimerOrder
ON PrimerOrderList.OrderCode = PrimerOrder.OrderCode
PrimerOrderList.InStock = PrimerOrder.InStock

Invalid Column Name in SQL Server Management Studio

When I execute this query in SQL Server Management Studio, this error appears:
'Msg 207, Level 16, State 1, Line 1
Invalid column name 'ACCOUNT_NO'.'
This is the code for the query:
DECLARE #largeaccnumber INT = ACCOUNT_NO
DECLARE #smallaccnumber INT
SET #smallaccnumber = (SELECT LEFT(#largeaccnumber, 6))
SELECT DNADRX.CODE,
DNADDR.NAME,
DNADDR.TYPE,
DNADDR.MAIL_NAME,
ADDRESS_LINE1,
ADDRESS_LINE2,
ADDRESS_LINE3,
TOWN_CITY,
COUNTY_STATE,
COUNTY_STATE_CODE,
COUNTRY,
POST_ZIP,
LAST_STAT_DATE,
ACCOUNT_NO
FROM DNADRX,
DNADDR,
BACCNT
WHERE DNADDR.CODE = DNADRX.ADDRESS_CODE
AND DNADDR.CODE = #smallaccnumber
ORDER BY DNADRX.CODE
I want the query to display the data from the columns of the different tables (the columns are listed in the SELECT bit of the query) from 3 different tables (DNADRX, DNADDR, BACCNT), and the factor linking all 3 tables together is the 6 digit code (ACCOUNT_NO in the BACCNT table, ADDRESS_CODE in the DNADRX table and CODE in the DNADDR table). Originally, ACCOUNT_NO from table BACCNT was 8 digits long, but I reduced it to the first 6 digits using SELECT LEFT and assigned this 6 digit value to the variable #smallaccnumber.
Whenever I try to execute the query, it keeps telling me that 'ACCOUNT_NO' is an invalid code name. I have checked the spelling, refreshed using IntelliSense and tried 'BACCNT.ACCOUNT_NO' instead of just 'ACCOUNT_NO' on the first line of the query but it still won't work (instead it says that the multi-part identifier could not be bound when I try 'BACCNT.ACCOUNT_NO').
I am really new to SQL coding so sorry if the answer to my problem is really simple.
Thank you for your assistance :)
You can try something like this.
This assumes you know the 6 character code. This query will only find results IF there is a record matching in EVERY table. If one table doesn't find a matching record this query will return NOTHING. If you want to find a row even if a recrod is missing from a table, replace the "INNER JOIN" with "LEFT OUTER JOIN"
SELECT Dnadrx.Code,
Dnaddr.Name,
Dnaddr.Type,
Dnaddr.Mail_Name,
Address_Line1,
Address_Line2,
Address_Line3,
Town_City,
County_State,
County_State_Code,
Country,
Post_Zip,
Last_Stat_Date,
Account_No
FROM Dnaddr
INNER JOIN BACCNT ON DNAADDR.CODE = BACCNT.ACCOUNT_NO
INNER JOIN Dnadrx ON Dnaaddr.Code=Dnaadrx.Address_Code
WHERE Dnaddr.Code='YOUR 6 CHARACTER CODE GOES HERE'
ORDER BY Dnadrx.Code;