SQL Conversion to Date And/Or Time From Character String Error - sql

Here is my table
CREATE TABLE [dbo].[RPost_Receipts]
(
[id] [int] IDENTITY(1,1) NOT NULL,
[branch] [int] NULL,
[policyref] [varchar](10) NULL,
[receipt_email_received] [datetime] NULL,
[receipt_email_to_openattach] [int] NULL,
[receipt_email_to_openattach_dt] [datetime] NULL,
[sender_name] [varchar](50) NULL,
[sender_address] [varchar](100) NULL,
[subject] [varchar](160) NULL,
[message_id] [varchar](100) NULL,
[time_received] [datetime] NULL,
[delivery_to] [varchar](100) NULL,
[delivery_status] [varchar](100) NULL,
[delivery_report] [varchar](max) NULL,
[delivery_time_utc] [datetime] NULL,
[delivery_time_local] [datetime] NULL,
[time_opened] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
This is the following UPDATE query I am attempting to run on the same table
UPDATE [FreshSystems].[dbo].[RPost_Receipts]
SET [sender_name] = 'RPost eSignOff Service' ,
[sender_address] = 'contracts#usw.rpost.net' ,
[subject] = 'Re: REF: 02-OGKX02PC01 Your Insurance Policy (2 of 2)' ,
[message_id] = '49B918875098C1EFCB5A33FDB2D446FF5C294ACE' ,
[time_received] = '9/15/2015 10:36:29 AM' ,
[delivery_to] = 'AutoSaintCS#Fresh.co.uk' ,
[delivery_status] = 'Delivered to Mailserver' ,
[delivery_report] = '250 OK id=1ZbnbS-0003fY-4y engine03-30179-2.icritical.com (192.162.216.4)' ,
[delivery_time_utc] = '9/15/2015 10:36:47 AM' ,
[delivery_time_local] = '9/15/2015 10:36:47 AM' ,
[time_opened] = 'NULL'
WHERE [branch] = 02
AND [policyref] = 'OGKX02PC01'
AND [delivery_to] IS NULL
Why am I receiving a conversion error
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
The inserts are going into 'DATETIME' columns and the datetime's that are being inserted are all correctly formatted, can anyone shed any light on this for me please?
UPDATE
The problem seems to occur ONLY within my VB.NET Application. When running the statement in SQL Server Management Studio it is fine, when it executed within my VB.NET it fails as a conversation from character to Datetime.
Any suggestions?

the issue is you were trying to put the word NULL into the time_opened field. (which is a datetime field)
Change it from [time_opened] = 'NULL' to [time_opened] = NULL
UPDATE [FreshSystems].[dbo].[RPost_Receipts]
SET [sender_name] = 'RPost eSignOff Service' ,
[sender_address] = 'contracts#usw.rpost.net' ,
[subject] = 'Re: REF: 02-OGKX02PC01 Your Insurance Policy (2 of 2)' ,
[message_id] = '49B918875098C1EFCB5A33FDB2D446FF5C294ACE' ,
[time_received] = '9/15/2015 10:36:29 AM' ,
[delivery_to] = 'AutoSaintCS#Fresh.co.uk' ,
[delivery_status] = 'Delivered to Mailserver' ,
[delivery_report] = '250 OK id=1ZbnbS-0003fY-4y engine03-30179-2.icritical.com (192.162.216.4)' ,
[delivery_time_utc] = '9/15/2015 10:36:47 AM' ,
[delivery_time_local] = '9/15/2015 10:36:47 AM' ,
[time_opened] = NULL
WHERE [branch] = 02
AND [policyref] = 'OGKX02PC01'
AND [delivery_to] IS NULL

I think Datetime format is yy-mm-dd hh:mm:ss and not 9/15/2015 10:36:29 AM
Convert it before updating table.

Related

Stored procedure throws an error while getting data from two table using UNION

I have two tables which are shown in this screenshot:
I am writing a stored procedure which will return data from both tables:
ALTER PROCEDURE [dbo].[GetInventoryDetails]
#MaterialId INT
AS
BEGIN
SELECT
tms.Material_ID AS MaterialId,
tmm.Name As MaterialName,
CONVERT(varchar,Quantity) AS AddedQuantity,
UtilizedQuantity ='-',
tcl.LedgerName AS SupplierName,
UsedFor = '-',
tmm.CurrentStock,
tmm.OpeningStock,
CONVERT(DATETIME,CONVERT(VARCHAR(100), tms.Material_Date, 112)) AS MaterialDate,
tms.Narration AS Narration
FROM
tblMaterialSheet tms
JOIN
tblMaterialMaster tmm ON tmm.Material_ID = tms.Material_ID
JOIN
tblCompanyLedger tcl ON tcl.Pk_LedgerId = tms.Ledger_ID
WHERE
tms.Material_ID = #MaterialId
AND tms.isActive = 1
UNION
SELECT
tmu.Material_ID AS MaterialId,
tmm.Name As MaterialName,
AddedQuantity = '-',
CONVERT(varchar,Utilized_Quantity) AS UtilizedQuantity,
CONVERT(DATETIME,CONVERT(VARCHAR(100), Utilization_Date, 112)) AS MaterialDate,
SupplierName = '-',
tbst.Name AS UsedFor,
tmm.CurrentStock,
tmm.OpeningStock,
tmu.Narration As Narration
FROM
tblMaterialUtilization tmu
JOIN
tblMaterialMaster tmm ON tmm.Material_ID = tmu.Material_ID
JOIN
tblBuildingSubTask tbst ON tbst.BuildingSubTask_ID = tmu.BuildingSubTask_ID
WHERE
tmu.Material_ID = #MaterialId
AND tmu.isActive = 1
END
When I call the stored procedure, it throws an error:
Conversion failed when converting date and/or time from character string.
Table structure: tblmaterialsheet
CREATE TABLE [dbo].[tblMaterialSheet]
(
[MaterialSheet_ID] [int] IDENTITY(1,1) NOT NULL,
[Company_ID] [int] NOT NULL,
[User_ID] [int] NOT NULL,
[BuildingSubTask_ID] [int] NOT NULL,
[Material_Date] [datetime] NOT NULL,
[Material_ID] [int] NOT NULL,
[Unit_ID] [int] NOT NULL,
[Quantity] [decimal](10, 2) NOT NULL,
[Size_ID] [int] NULL,
[Height] [decimal](6, 2) NULL,
[Width] [decimal](6, 2) NULL,
[Rate_Per_Unit] [money] NULL,
[Paid_Amount] [money] NULL,
[Total_Amount] [money] NULL,
[Vehical_No] [varchar](50) NULL,
[Ledger_ID] [int] NULL,
[Narration] [varchar](max) NULL,
[Challan_No] [int] NULL,
[Bill_ID] [int] NULL,
[isBilled] [bit] NOT NULL,
[Approval] [varchar](50) NULL,
[Approval_ModifiedDate] [datetime] NULL,
[UploadImage] [image] NULL,
[isActive] [bit] NOT NULL,
[CreatedBy] [int] NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[ModifiedBy] [int] NULL,
[ModifiedDate] [datetime] NULL
)
Table structure : tblMaterialUtilization
CREATE TABLE [dbo].[tblMaterialUtilization]
(
[MaterialUtilization_ID] [int] IDENTITY(1,1) NOT NULL,
[Company_ID] [int] NOT NULL,
[User_ID] [int] NOT NULL,
[BuildingSubTask_ID] [int] NOT NULL,
[Material_ID] [int] NOT NULL,
[Utilization_Date] [datetime] NOT NULL,
[Utilized_Quantity] [decimal](10, 2) NOT NULL,
[Narration] [varchar](max) NOT NULL,
[IsActive] [bit] NOT NULL,
[CreatedBy] [int] NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[ModifiedBy] [int] NULL,
[ModifiedDate] [datetime] NULL
)
Table structure : tblMaterialMaster
CREATE TABLE [dbo].[tblMaterialMaster]
(
[Material_ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NOT NULL,
[Unit_ID] [int] NOT NULL,
[IsActive] [bit] NOT NULL,
[CreatedBy] [int] NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[ModifiedBy] [int] NULL,
[ModifiedDate] [datetime] NULL,
[OpeningStock] [numeric](18, 0) NULL,
[PurchaseLedger] [numeric](18, 0) NULL,
[CurrentStock] [numeric](18, 0) NULL
)
Table structure : tblBuildingSubTask
CREATE TABLE [dbo].[tblBuildingSubTask]
(
[BuildingSubTask_ID] [int] IDENTITY(1,1) NOT NULL,
[BuildingTask_ID] [int] NOT NULL,
[Name] [varchar](200) NOT NULL,
[Narration] [varchar](max) NULL,
[StartDate] [datetime] NULL,
[TargetCompletionDate] [datetime] NULL,
[ActualCompletionDate] [datetime] NULL,
[IsActive] [bit] NOT NULL,
[CreatedBy] [int] NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[ModifiedBy] [int] NULL,
[ModifiedDate] [datetime] NULL
)
How to solve this error?
TRY THIS NOW: The order of the column were not in the same order so it was getting the different datatype values for the same column. Datatype and Order is most important in the UNION
ALTER PROCEDURE [dbo].[GetInventoryDetails]
#MaterialId int
AS
BEGIN
SELECT
tms.Material_ID AS MaterialId,
tmm.Name As MaterialName,
CONVERT(varchar,Quantity) AS AddedQuantity,
UtilizedQuantity ='-',
tcl.LedgerName AS SupplierName,
UsedFor='-',
tmm.CurrentStock,
tmm.OpeningStock,
CONVERT(DATETIME,CONVERT(VARCHAR(100), tms.Material_Date, 112)) AS MaterialDate,
tms.Narration As Narration
FROM
tblMaterialSheet tms
JOIN tblMaterialMaster tmm on tmm.Material_ID = tms.Material_ID
JOIN tblCompanyLedger tcl on tcl.Pk_LedgerId = tms.Ledger_ID
WHERE
tms.Material_ID = #MaterialId
AND
tms.isActive = 1
UNION
SELECT
tmu.Material_ID AS MaterialId,
tmm.Name As MaterialName,
AddedQuantity = '-',
CONVERT(varchar,Utilized_Quantity) AS UtilizedQuantity,
SupplierName = '-', --Moved up
tbst.Name AS UsedFor, --Moved up
tmm.CurrentStock, --Moved up
tmm.OpeningStock, --Moved up
CONVERT(DATETIME,CONVERT(VARCHAR(100), Utilization_Date, 112)) AS MaterialDate,
tmu.Narration As Narration
FROM
tblMaterialUtilization tmu
JOIN tblMaterialMaster tmm on tmm.Material_ID = tmu.Material_ID
JOIN tblBuildingSubTask tbst on tbst.BuildingSubTask_ID = tmu.BuildingSubTask_ID
WHERE
tmu.Material_ID = #MaterialId
AND
tmu.isActive = 1
END
The troubleshooting direction I'd take:
Look at your SQL. You're looking for anything that might be converting something of non-date type to date type. Your error probably means there's data somewhere you're converting to date that can't be converted. Be aware that this can include comparisons or functions that output a date.
Looking at your example, without knowing that actual data types, the only place I can see this happening is the explicit CONVERT functions on tms.Material_Date and Utilization_Date. I'd quickly comment these out and run each of the halves of the UNION separately. If they work, I could uncomment one or other until I figure out which field is causing the error. If they work independently but not unioned, I know that it's the after-union fields getting converted to date because the pre-union field is date.
Say it's the first half, before the union. I'd run:
SELECT * As Narration
FROM
tblMaterialSheet tms
JOIN tblMaterialMaster tmm on tmm.Material_ID = tms.Material_ID
JOIN tblCompanyLedger tcl on tcl.Pk_LedgerId = tms.Ledger_ID
WHERE
tms.Material_ID = #MaterialId
AND
tms.isActive = 1
AND
ISDATE(tms.Material_Date) = 0
You might need to work outwards in your converting to see where it falls over, e.g.,
AND
ISDATE(CONVERT(VARCHAR(100), tms.Material_Date, 112))
Then you should have a good idea about the problem.
Incidentally,
CONVERT(DATETIME,CONVERT(VARCHAR(100), Utilization_Date, 112))
looks very odd - what are you trying to achieve here by converting a date to varchar and back?
When you write a UNION or UNION ALL, You should make sure the following
No of Columns should be Same for Each Select Should Be same
Data Type of Column coming on the same position of each select Should be same
Suppose I have a column with character datatype for the first select and I'm trying to union it with a DateTime datatype, then I will get the error
SELECT 'ABCD'
UNION ALL
SELECT GETDATE()
This will throw the error
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
because the datatypes do not match.
And this will cause another error:
SELECT 'ABCD',GETDATE()
UNION ALL
SELECT GETDATE()
Like this:
Msg 205, Level 16, State 1, Line 1
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
because the number of columns does not match.
So make sure that the datatypes match for each column in your UNION and if they does not match, try Cast or Convert

Error converting data type varchar to numeric while inserting/ updating

I was trying to insert/update records in bulk using merge statement. But I am getting following error. I have searched online i couldn't find a way to fix. Can some one tell me where I am doing wrong?
Error converting data type varchar to numeric while inserting'
Table structure
CREATE TABLE [Metric].[MetricGoal]
(
[metricGoalId] [int] IDENTITY(1,1) NOT NULL,
[profileConfigId] [int] NOT NULL,
[metricGoalName] [varchar](200) NULL,
[metricIndicatorId] [int] NOT NULL,
[marketConfigId] [int] NOT NULL,
[regionConfigId] [int] NOT NULL,
[goalYearConfigId] [int] NOT NULL,
[goalPeriodConfigId] [int] NOT NULL,
[targetValue] [decimal](20, 3) NULL,
[actualValue] [decimal](20, 3) NULL,
[metricGoalStatusConfigId] [int] NOT NULL,
[metricGoalStatusReasonConfigId] [int] NOT NULL,
[ownerId] [int] NULL,
[workerId] [int] NULL,
[createdOn] [datetime] NOT NULL,
[createdBy] [int] NOT NULL,
[updatedOn] [datetime] NOT NULL,
[updatedBy] [int] NOT NULL,
[lineOfBusinessConfigId] [int] NULL,
[productConfigId] [int] NULL,
[serviceAreaConfigId] [int] NULL,
)
User Defined Table Type(created type with only columns that needs to insert / update):
CREATE TYPE [Metric].[MetricGoalType3] AS TABLE
(
[metricGoalId] [int] NULL,
[lineOfBusinessConfigId] [int] NULL,
[metricIndicatorId] [int] NOT NULL,
[goalYearConfigId] [int] NOT NULL,
[goalPeriodConfigId] [int] NOT NULL,
[marketConfigId] [int] NOT NULL,
[targetValue] [decimal](20, 3) NULL,
[actualValue] [decimal](20, 3) NULL,
[metricGoalStatusConfigId] [int] NOT NULL,
[metricGoalStatusReasonConfigId] [int] NOT NULL,
[ownerId] [int] NULL,
[workerId] [int] NULL
)
Stored procedure to insert/update using Merge:
CREATE PROCEDURE [Metric].[prMaintainMetricGoalBulkLoad]
#currUserId INT = NULL,
#currProfileConfigId INT = NULL,
#tblMetricGoal [Metric].[MetricGoalType3] READONLY
AS
DECLARE #now DATETIME = GETDATE()
BEGIN
SET NOCOUNT ON;
MERGE INTO [Metric].[MetricGoal] T
USING #tblMetricGoal S ON (T.metricGoalId = S.metricGoalId)
WHEN MATCHED
THEN UPDATE
SET T.targetValue = CASE WHEN S.targetValue = '' THEN NULL ELSE ISNULL(CONVERT(DECIMAL(20,3),NULLIF(S.targetValue,'')),T.targetValue) END,
T.actualValue = CASE WHEN S.actualValue = '' THEN NULL ELSE ISNULL(CONVERT(DECIMAL(20,3),NULLIF(S.actualValue,'')),T.actualValue) END,
T.metricGoalStatusConfigId = CASE WHEN S.metricGoalStatusConfigId = -1 THEN NULL ELSE ISNULL(S.metricGoalStatusConfigId,T.metricGoalStatusConfigId) END,
T.metricGoalStatusReasonConfigId = CASE WHEN S.metricGoalStatusReasonConfigId = -1 THEN NULL ELSE ISNULL(S.metricGoalStatusReasonConfigId,T.metricGoalStatusReasonConfigId) END,
T.ownerId = CASE WHEN S.ownerId = -1 THEN NULL ELSE ISNULL(S.ownerId,T.ownerId) END,
T.workerId = CASE WHEN S.workerId = -1 THEN NULL ELSE ISNULL(S.workerId,T.workerId) END,
T.updatedOn = #now,
T.updatedBy = #currUserId
WHEN NOT MATCHED BY TARGET
THEN INSERT (profileConfigId,
--metricGoalName,
metricIndicatorId, lineOfBusinessConfigId, marketConfigId,
--productConfigId,
--serviceAreaConfigId,
--regionConfigId,
goalYearConfigId, goalPeriodConfigId, targetValue, actualValue,
metricGoalStatusConfigId, metricGoalStatusReasonConfigId,
ownerId, workerId, createdOn, createdBy,
updatedOn, updatedBy)
VALUES (#currProfileConfigId,
--S.metricGoalName,
S.metricIndicatorId, S.lineOfBusinessConfigId, S.marketConfigId,
--NULLIF(S.productConfigId,-1),
--NULLIF(S.serviceAreaConfigId,-1),
--S.regionConfigId,
S.goalYearConfigId, S.goalPeriodConfigId,
CONVERT(DECIMAL(20,3),NULLIF(S.targetValue,'')),
CONVERT(DECIMAL(20,3),NULLIF(S.actualValue,'')),
S.metricGoalStatusConfigId, S.metricGoalStatusReasonConfigId,
NULLIF(S.ownerId, -1),
NULLIF(S.workerId, -1),
#now, #currUserId, #now, #currUserId);
END
Execution (used SQL Server Profiler to get below statements)
declare #p3 Metric.MetricGoalType3
insert into #p3 values(820,819,4,602,570,694,39.000,43.000,655,660,1585,NULL)
insert into #p3 values(NULL,819,4,602,570,1853,NULL,NULL,655,660,NULL,NULL)
exec Metric.prMaintainMetricGoalBulkLoad #currUserId=1618,#currProfileConfigId=301,#tblMetricGoal=#p3
These 2 rows contain error:
T.targetValue = CASE WHEN S.targetValue = '' THEN NULL ELSE ISNULL(CONVERT(DECIMAL(20,3),NULLIF(S.targetValue,'')),T.targetValue) END,
T.actualValue = CASE WHEN S.actualValue = '' THEN NULL ELSE ISNULL(CONVERT(DECIMAL(20,3),NULLIF(S.actualValue,'')),T.actualValue) END,
Both targetValue and actualValue are decimal(20,3), so how can you use '' that is string with decimals?
It should be
T.targetValue = CASE WHEN S.targetValue is null THEN NULL ELSE ISNULL(CONVERT(DECIMAL(20,3),NULLIF(S.targetValue,null)),T.targetValue) END,
T.actualValue = CASE WHEN S.actualValue is null THEN NULL ELSE ISNULL(CONVERT(DECIMAL(20,3),NULLIF(S.actualValue,null)),T.actualValue) END,
even it has no sense but at least there vill be no conversion from varchar to numeric.
Here is how to reproduce your error (I'll use variables instead of tables):
declare #StargetValue DECIMAL(20,3) = 10, #TtargetValue DECIMAL(20,3) = 20;
set #ttargetValue = CASE WHEN #StargetValue = '' THEN NULL ELSE ISNULL(CONVERT(DECIMAL(20,3),NULLIF(#StargetValue,'')),#TtargetValue) END
When you try to confront your decimal with '' you get the error because '' just cannot be converted to decimal.
There is data that will not convert correctly, exactly what or where I can't tell but since you indicate you are using SQL Server 2012 then use TRY_CONVERT or TRY_CAST instead of convert or cast.
These 2 newer functions do not cause a failure if the data cannot be converted, they simply return NULL instead. While this may not solve bad data it does help. For example you can use these in a where clause e.g.
select *
from to_be_imported
where try_convert(date,stringcolumn) IS NULL
It looks like the insert portion of the statement does not align with your table definition. The third field in your insert list is lineOfBusinessConfigId which is trying to insert into the third field of the table, a varchar column metricGoalName.

Update Table Variable in SQL Server and getting Must declare the scalar variable

I CAN change to temp table if need be, but when I am doing an UPDATE on a table variable in sql server, why are I getting this error
and how can I fix, should I switch to temp table ?
Must declare the scalar variable "#rpmuserTableVariable".
DECLARE #rpmuserTableVariable TABLE
(
[usr_id] [varchar](8) NOT NULL,
[usr_fnm] [varchar](64) NOT NULL,
[usr_lnm] [varchar](64) NOT NULL,
[usr_pwd] [varchar](64) NOT NULL,
[email_id] [varchar](250) NULL,
[wwid] [varchar](8) NULL,
[tel] [char](20) NULL,
[dflt_ste_id] [int] NOT NULL,
[lst_pwd_chg_dtm] [datetime] NULL,
[lst_accs_dtm] [datetime] NULL,
[apprvr_wwid] [varchar](8) NULL,
[inact_ind] [varchar](1) NOT NULL,
[cre_usr_id] [varchar](8) NOT NULL,
[cre_dtm] [datetime] NOT NULL,
[chg_usr_id] [varchar](8) NULL,
[chg_dtm] [datetime] NULL,
[salt] [varchar](20) NULL,
STATUS [char] (1) NULL
);
-- All Active Users
INSERT INTO #rpmuserTableVariable
SELECT * ,'0'
FROM rpm_scrty_rpm_usr WITH(NOLOCK)
WHERE inact_ind = 'N'
-- Internal Users
UPDATE #rpmuserTableVariable
SET STATUS = 1
FROM rpm_scrty_rpm_usr ru WITH(NOLOCK)
INNER JOIN rpm_scrty_emp_info ei WITH(NOLOCK)
ON ru.wwid = ei.wwid
WHERE ru.inact_ind = 'N'
AND ei.inact_ind = 'N'
AND ei.dmn_addr IS NOT NULL
AND #rpmuserTableVariable.usr_id = ru.usr_id
select * from #rpmuserTableVariable
Do I need to use a temp table #tempblah or is there a "trick" to doing this?
Also, I CAN do a bulk update right? I do not need to do a WHILE loop do I?
No need. You just need a table alias. Aliases cannot start with #:
UPDATE rtv
SET STATUS = 1
FROM #rpmuserTableVariable rtv INNER JOIN
rpm_scrty_rpm_usr ru WITH(NOLOCK)
ON rtv.usr_id = ru.usr_id INNER JOIN
rpm_scrty_emp_info ei WITH(NOLOCK)
ON ru.wwid = ei.wwid
WHERE ru.inact_ind = 'N' AND
ei.inact_ind = 'N' AND
ei.dmn_addr IS NOT NULL;

select fails when converting data type varchar to numeric

My select is to insert from a table 1 to table 2 and when I run it I get the following message:
Msg 8114, Level 16, State 5, Line 5
Error converting data type varchar to numeric.
the columns that I am converting from varchar to numeric are:
titulos
cambio
liquido
resultado
If I eliminate these columns from the select it works fine.
This is the actual select:
INSERT INTO SICAVS1_Transacciones_con_ISIN
(tipo_operacion, fecha, cod_operacion,
nombre, titulos, cambio, liquido,
resultado, ISIN )
SELECT DISTINCT st.tipo_operacion
, st.fecha
, st.cod_operacion
, st.nombre
, cast(st.titulos as DECIMAL(16,2))
, cast(st.cambio as DECIMAL(16,2))
, cast(st.liquido as DECIMAL(16,2))
, cast(st.resultado as DECIMAL(16,2))
, st.ISIN
FROM temp_Transacciones st WHERE NOT EXISTS
(SELECT 1
FROM SICAVS1_Transacciones t2
WHERE t2.tipo_operacion = st.tipo_operacion
AND t2.fecha = st.fecha
AND t2.cod_operacion = st.cod_operacion
AND t2.nombre = st.nombre
AND t2.ISIN = st.ISIN)
And this is the table scheme of SICAVS1_transacciones_con_ISIN[dbo].[SICAVS1_Transacciones_con_ISIN]
[ID] [int] IDENTITY(1,1) NOT NULL,
[tipo_operacion] [varchar](30) NULL,
[fecha] [varchar](10) NULL,
[cod_operacion] [varchar](6) NULL,
[nombre] [varchar](32) NULL,
[titulos] [decimal](16, 2) NULL,
[cambio] [decimal](16, 2) NULL,
[liquido] [decimal](16, 2) NULL,
[resultado] [decimal](16, 2) NULL,
[ISIN] [varchar](20) NULL,
[fecha_valor] [date] NULL,
[type] [varchar](14) NULL,
[categoria_1] [char](35) NULL,
CONSTRAINT [PK__BNP_SICA__3214EC27DA21ECEF] PRIMARY KEY CLUSTERED
(
[ID] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
SQL Server 2012 and Later
Just use Try_Convert instead:
TRY_CONVERT takes the value passed to it and tries to
convert it to the specified data_type. If the cast succeeds,
TRY_CONVERT returns the value as the specified data_type;
if an error occurs, null is returned.
However if you request a conversion that is explicitly not
permitted, then TRY_CONVERT fails with an error.
Read more about Try_Convert.
One of these rows aren't numeric, you have to eliminate them. To find them:
SELECT DISTINCT st.tipo_operacion
, st.fecha
, st.cod_operacion
, st.nombre
, st.titulos
, st.cambio
, st.liquido
, st.resultado
, st.ISIN
FROM temp_Transacciones st WHERE NOT EXISTS
(SELECT 1
FROM SICAVS1_Transacciones t2
WHERE t2.tipo_operacion = st.tipo_operacion
AND t2.fecha = st.fecha
AND t2.cod_operacion = st.cod_operacion
AND t2.nombre = st.nombre
AND t2.ISIN = st.ISIN)
WHERE ISNUMERIC(st.titulos) = 0
OR ISNUMERIC(st.cambio) = 0
OR ISNUMERIC(st.liquido) = 0
OR ISNUMERIC(st.resultado) = 0
Note that this only find them. It won't help you resolve the issues by itself. There's no way to convert abc123 to a number.

Error converting data type varchar to bigint in stored procedure

I'm trying to call this procedure with the usp_TimesheetsAuditsLoadAllbyId 42747, NULL command.
But I always get an error
Msg 8114, Level 16, State 5, Procedure usp_TimesheetsAuditsLoadAllById, Line 9
Error converting data type varchar to bigint.
The ID of TimesheetsAudits table is a bigint type. I tried several types of conversions and casts, but I'm really stuck right now.
Hope somebody can help. Thanks
ALTER PROCEDURE [dbo].[usp_TimesheetsAuditsLoadAllById]
(
#Id INT,
#StartDate DATETIME
)
AS
BEGIN
SET NOCOUNT ON
SELECT TOP 51 *
FROM
(SELECT TOP 51
ID,
Type,
ReferrerId,
CAST(Description AS VARCHAR(MAX)) AS Description,
OnBehalfOf,
Creator,
DateCreated
FROM
TimesheetsAudits
WHERE
(ReferrerID = #Id) AND
(#StartDate IS NULL OR DateCreated < #StartDate)
ORDER BY
DateCreated DESC
UNION
SELECT TOP 51
tia.ID,
tia.Type,
tia.ReferrerId,
'[Day: ' + CAST(DayNr AS VARCHAR(5)) + '] ' + CAST(tia.Description AS VARCHAR(MAX)) AS Description,
tia.OnBehalfOf,
tia.Creator,
tia.DateCreated
FROM
TimesheetItemsAudits tia
INNER JOIN
TimesheetItems ti ON tia.ReferrerId = ti.ID
WHERE
(ti.TimesheetID = #Id) AND
(#StartDate IS NULL OR tia.DateCreated < #StartDate)
ORDER BY
tia.DateCreated DESC) t
ORDER BY
t.DateCreated DESC
END
Table definition for tables from comments:
CREATE TABLE [dbo].[TimesheetsAudits](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Type] [tinyint] NOT NULL,
[ReferrerId] [varchar](15) NOT NULL,
[Description] [text] NULL,
[OnBehalfOf] [varchar](10) NULL,
[Creator] [varchar](10) NOT NULL,
[DateCreated] [datetime] NOT NULL
)
CREATE TABLE [dbo].[TimesheetItemsAudits](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Type] [tinyint] NOT NULL,
[ReferrerId] [varchar](15) NOT NULL,
[Description] [text] NULL,
[OnBehalfOf] [varchar](10) NULL,
[Creator] [varchar](10) NOT NULL,
[DateCreated] [datetime] NOT NULL
)
You perform an INNER JOIN of [dbo].[TimesheetsAudits] and TimesheetItems ti ON tia.ReferrerId = ti.ID
tia.[ReferrerId] is varchar and ti.[ID] is [bigint].
I'd expect a value in tia.[ReferrerId] that cannot be converted to bigint.
Try the following:
SELECT [ReferrerId] FROM TimesheetItemsAudits WHERE ISNUMERIC(ReferrerId) = 0
This may help you to find the "offending rows".