Conversion failed when converting nvarchar - sql

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.

Related

DBSQL_SQL_INTERNAL_DB_ERROR SQL error 2048

I have to join two tabled ACDOCA and BKPF. I have written the follow code for it.
SELECT a~rbukrs,
a~racct,
a~bldat,
a~blart,
a~kunnr,
a~belnr,
a~sgtxt,
b~xblnr,
a~budat,
a~hsl,
a~prctr
INTO TABLE #it_final
FROM acdoca AS a
LEFT OUTER JOIN bkpf AS b
ON a~rbukrs = b~bukrs
AND a~gjahr = b~gjahr
WHERE a~rbukrs IN #s_bukrs
AND a~Kunnr IN #s_kunnr
AND a~Budat IN #s_budat
AND a~Belnr IN #s_belnr
AND a~rldnr IN #s_rldnr
AND a~blart = 'DR' OR a~blart = 'ZK' OR a~blart = 'UE'.
Facing the following errors:----
Runtime error: DBSQL_SQL_INTERNAL_DB_ERROR
SQL error "SQL code: 2048" occurred while accessing table "ACDOCA".
Short Text: An exception has occurred in class "CX_SY_OPEN_SQL_DB"
How do I resolve this? please help.
A few things:
Selecting directly from the database tables is error prone (e.g. you'll forget keys while joining) and you have to deal with those terrible german abbreviations (e.g. Belegnummer -> belnr). Since quite some time there are CDS Views on top such as I_JournalEntryItem with associations and proper english names for those fields, if you can use them, I would (also they're C1 released).
As already pointed out by xQBert the query does probably not work as intended as AND has prescendence over OR, and as such your query basically returns everything from ACDOCA, multiplied by everything from BKPF which likely leads to the database error you've posted
With range queries you might still get a lot of results (like billions of entries, depending on your company's size), you should either limit the query with UP TO, implement some pagination or COUNT(*) first and show an error to the user if the result set is too large.
I would write that like this:
TYPES:
BEGIN OF t_filters,
company_codes TYPE RANGE OF bukrs,
customers TYPE RANGE OF kunnr,
document_dates TYPE RANGE OF budat,
accounting_documents TYPE RANGE OF fis_belnr,
ledgers TYPE RANGE OF rldnr,
END OF t_filters.
DATA(filters) = VALUE t_filters(
" filter here
).
SELECT FROM I_JournalEntryItem
FIELDS
CompanyCode,
GLAccount,
DocumentDate,
AccountingDocumentType,
Customer,
AccountingDocument,
DocumentItemText,
\_JournalEntry-DocumentReferenceID,
PostingDate,
AmountInCompanyCodeCurrency,
ProfitCenter
WHERE
CompanyCode IN #filters-company_codes AND
Customer IN #filters-customers AND
DocumentDate IN #filters-document_dates AND
AccountingDocument IN #filters-accounting_documents AND
Ledger IN #filters-ledgers AND
AccountingDocumentType IN ( 'DR', 'ZK', 'UE' )
INTO TABLE #DATA(sales_orders)
UP TO 100 ROWS.
(As a bonus you'll get proper DCL authorization checks)
2048 is/can be a memory allocation error: Too much data being returned. Given that, this line is highly suspect
AND a~blart = 'DR' OR a~blart = 'ZK' OR a~blart = 'UE'.
I'd consider this instead. Otherwise ALL blart ZK and UE records are returned regardless of customer, year, company et...
SELECT a~rbukrs,
a~racct,
a~bldat,
a~blart,
a~kunnr,
a~belnr,
a~sgtxt,
b~xblnr,
a~budat,
a~hsl,
a~prctr
INTO TABLE #it_final
FROM acdoca AS a
LEFT OUTER JOIN bkpf AS b
ON a~rbukrs = b~bukrs
AND a~gjahr = b~gjahr
WHERE a~rbukrs IN #s_bukrs
AND a~Kunnr IN #s_kunnr
AND a~Budat IN #s_budat
AND a~Belnr IN #s_belnr
AND a~rldnr IN #s_rldnr
AND a~blart IN ('DR','ZK','UE').
However, if you really did mean to return all blart ZK, UE records and only those that ar DR and in the defined parameters... you're simply asking for too much data from teh system and need to "LIMIT" your result set and somehow let the user know only a limited set is being returned due to data volume
I'd also ensure your join on keys is sufficient. Fiscal Year and company code represent an incomplete key to BKPF. I dont' know ACDOCA data table so I'm unsure if that's a proper join which may be leading to a semi-cartesean contributing to data bloat. I'd think in a multi-tenant db, you may need to join on mandt as well... possibly a doc number and some other values... again, this lookst to be an incomplete join on key.... so perhaps more is needed there as well.

SQL Strange Error converting data type nvarchar to numeric Error. Error only in Where Clause

So I have this query
select *
FROM
[JMNYC-AMTDB].[AMTPLUS].[dbo].PickTickets i WITH (NOLOCK)
INNER JOIN
[JMNYC-AMTDB].[AMTPLUS].[dbo].customer_store cs WITH (NOLOCK)
ON i.Company_code = cs.Company_code
AND i.Division_code = cs.Division_code
AND i.Customer_Number = cs.Customer_Number
AND i.ShipTo=cs.store_number
JOIN
[JMNYC-AMTDB].[AMTPLUS].[dbo].PickTickets_Packing ps1 WITH (NOLOCK)
ON i.Company_Code=ps1.Company_Code
AND i.Division_Code=ps1.Division_Code
AND i.PickTicket_Number=ps1.PickTicket_Number
JOIN
[JMNYC-AMTDB].[AMTPLUS].[dbo].Orders o WITH (NOLOCK)
ON i.Company_Code=o.Company_Code
AND i.Division_Code=o.Division_Code
AND i.Control_Number=o.Control_Number
LEFT JOIN
[JMNYC-AMTDB].[AMTPLUS].[dbo].Country cr WITH (NOLOCK)
ON cs.country =cr.country
LEFT JOIN
Packslip P ON I.COMPANY_CODE=P.CLIENTNAME
LEFT JOIN
Moret_shipper sh ON I.COMPANY_CODE=sh.CLIENTNAME
LEFT JOIN
CUSTOMER cu ON i.Customer_Number=cu.CUST_NUM
LEFT JOIN
(
SELECT packslip FROM PICKHEAD (NOLOCK)
WHERE CLIENTNAME='03'
) td3 ON I.PickTicket_number=td3.packslip
JOIN
[JMNYC-AMTDB].[AMTPLUS].[dbo].Picktickets_stage pst1 WITH (NOLOCK)
ON i.Company_Code=pst1.Company_Code
AND i.Division_Code=pst1.Division_Code
AND i.PickTicket_Number=pst1.PickTicket_Number
AND pst1.Stage_code='940READY'
LEFT JOIN
(
SELECT packslip FROM rf_log_all (NOLOCK)
WHERE action='DELETESO' AND clientname='03'
) td4 ON I.PickTicket_number=cast(td4.packslip as numeric)
If I run it just like that, everything seems to work fine.
However as soon as I start adding the where clause, I start getting a weird conversion error.
Here is my where clause:
WHERE
i.company_code='03'
AND ps1.Packed_Status='E'
AND i.Warehouse_Code in ('DAYTO','SANFE','ALLLM')
AND td3.packslip is null
AND td4.packslip is null
With that I get the Error converting data type nvarchar to numeric.
If I comment out the td3 and td4 checks, it works.
WHERE
i.company_code='03'
AND ps1.Packed_Status='E'
AND i.Warehouse_Code in ('DAYTO','SANFE','ALLLM')
--AND td3.packslip is null
--AND td4.packslip is null
However, it also works with those left in but the company code commented out.
WHERE
--i.company_code='03' AND
ps1.Packed_Status='E'
AND i.Warehouse_Code in ('DAYTO','SANFE','ALLLM')
AND td3.packslip is null
AND td4.packslip is null
Does anyone know what might be causing this error. This is a query that we've been using for a while and this problem only started recently. If I knew what specific line is causing this error, I could try to fix it, but I'm not even sure of that.
Obviously, nothing in the where clause is causing this error, because all the comparisons are string comparisons (or type-safe such as comparing to NULL).
So, what is happening is that some of the JOIN conditions are causing problems. That means that you are mixing types. Your question doesn't have enough information to determine which ones.
Why does this occur with some WHERE conditions but not others? Because SQL Server rearranges the query plan to be optimal for the query you have written. In different query plans, the offensive comparison might occur after filtering (in which case no error occurs) or before filtering (in which case an error occurs).
Reading the query plan probably will not help you. You really want to find the comparison that is mixing types -- and that might take a bit of work and digging through the table structures.
If I had to guess, I would speculate that the offending line of code is:
ON I.PickTicket_number = cast(td4.packslip as numeric)
And that packslip cannot always be converted to a numeric value. This is easily fixed by using try_cast():
ON I.PickTicket_number = try_cast(td4.packslip as numeric)

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;

Data type mismatch while fetching data from one table into another

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