Using Execute() method in Table-valued function SQL Server - sql

I am trying to create a table-valued function in SQL Server. My issue is that I can't find the right syntax for the SQL. I keep getting errors. I don't know if it is possible to use an execute() method in a table-valued function. I have tried declaring and setting the variables and also using the execute method in an oridinary sql query and it works.
My SQL:
CREATE FUNCTION SortRoutePartByDay
(
#date datetime
)
RETURNS TABLE
AS
Begin
declare #cmdtext varchar(max)
declare #Daynameofweek varchar(10)
set #Daynameofweek = datename(weekday, #date)
set #cmdtext = 'select * from RoutePartPart where ' +#Daynameofweek+' =1';
RETURN
(
execute(#cmdtext)
)
GO
My error so far is:
Msg 156, Level 15, State 1, Procedure SortRoutePartByDay, Line 21
Incorrect syntax near the keyword 'execute'.
Msg 102, Level 15, State 1, Procedure SortRoutePartByDay, Line 23
Incorrect syntax near ')'.
RoutePartPart DDL:
CREATE TABLE [dbo].[RoutePartPart](
[RouteID] [int] NOT NULL,
[RoutePartNo] [smallint] NOT NULL,
[RoutePartPartNo] [smallint] NOT NULL,
[PickupAreaGrpID] [int] NULL,
[DeliveryAreaGrpID] [int] NULL,
[Monday] [bit] NULL,
[Tuesday] [bit] NULL,
[Wednesday] [bit] NULL,
[Thursday] [bit] NULL,
[Friday] [bit] NULL,
[Saturday] [bit] NULL,
[Sunday] [bit] NULL,
[Pickup] [bit] NULL,
[Delivery] [bit] NULL,
[Types] [varchar](10) NULL
) ON [PRIMARY]

I think using dynamic SQL is unnecessary in your case, so try this one -
Query:
CREATE FUNCTION SortRoutePartByDay
(
#date DATETIME
)
RETURNS TABLE
AS RETURN
SELECT *
FROM dbo.RoutePartPart
WHERE DATENAME(weekday, #date) = 1
Small info:
Functions on SQL Server are not the same as stored procedures, they have several limitations on the things that can be done. For example, you can't use dynamic SQL.
Update:
CREATE FUNCTION SortRoutePartByDay
(
#date DATETIME
)
RETURNS TABLE
AS RETURN
SELECT p.*
FROM dbo.RoutePartPart p
CROSS JOIN (
SELECT [WeekDay] = DATENAME(weekday, #date)
) t
WHERE ([WeekDay] = 'Monday' AND [Monday] = 1)
OR ([WeekDay] = 'Tuesday' AND [Tuesday] = 1)
OR ([WeekDay] = 'Wednesday' AND [Wednesday] = 1)
OR ([WeekDay] = 'Thursday' AND [Thursday] = 1)
OR ([WeekDay] = 'Friday' AND [Friday] = 1)
OR ([WeekDay] = 'Saturday' AND [Saturday] = 1)
OR ([WeekDay] = 'Sunday' AND [Sunday] = 1)

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.

Can I make this stored procedure faster

I have the stored procedure below. This stored procedure runs in 3-4 seconds even on my developer computer but on the server it takes 15-20 seconds. I tried to change some of subqueries to cross apply and some to outer apply. But it caused to take more longer time.
#startDate datetime ,
#endDate datetime ,
#customerId int
;WITH t1(Plate,UsedFuelTypeUID,RemainingBefore,DateRangeTotal,DateRangeTransactionsTotal,RemaininCurrent) AS
(
select
v.Plate, v.UsedFuelTypeUID,
isnull((select isnull( sum(vls1.FT_TotalLimit),0)
from VehicleChildLog vls1
where vls1.VehicleChildId =v.VehicleID and vls1.UpdateDate < #startDate
),0)-
isnull((select isnull( sum(t1.Liter),0) from Transactions t1
where t1.VehicleChildID=v.VehicleID and t1.SaleDate <#startDate
),0)as RemainingBefore,
sum(vl.FT_TotalLimit) DateRangeTotal,
isnull((select isnull( sum(t1.Liter),0) from Transactions t1
where t1.VehicleChildID=v.VehicleID and t1.SaleDate between #startDate and #endDate
),0) as DateRangeTransactionsTotal,
(v.FT_TotalLimit - v.FT_UsedTotalLimit) as RemainingCurrent
from VehicleChildLog vl
inner join VehiclesChild v on vl.VehicleChildId = v.VehicleID
where vl.CustomerChildID = #customerId and vl.UpdateDate between #startDate and #endDate
group by
v.VehicleID, v.Plate, v.UsedFuelTypeUID
,v.FT_TotalLimit - v.FT_UsedTotalLimit
)
select *, t1.RemainingBefore+t1.DateRangeTotal-t1.DateRangeTransactionsTotal as RemainingAfter from t1 ;
Table structure is below
[Transactions]
(
[TransactionID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[SaleDate] [datetime] NULL,
[Liter] [float] NULL,
[VehicleChildID] [int] NULL
...
)
[VehiclesChild]
(
[VehicleID] [int] IDENTITY(1,1) NOT NULL,
[CustomerChildID] [int] NULL,
[Plate] [varchar](16) NULL,
[UsedFuelTypeUID] [int] NULL,
[FT_TotalLimit] [float] NULL,
[FT_UsedTotalLimit] [float] NULL
...
)
[VehicleChildLog]
(
[VehiclesChildLogId] [int] IDENTITY(1,1) NOT NULL,
[VehicleChildId] [int] NOT NULL,
[CustomerChildId] [int] NOT NULL,
[FT_TotalLimit] [float] NULL,
[FT_UsedTotalLimit] [float] NULL,
[UpdateDate] [datetime] NULL
...
)

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

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.

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".