Trouble using stored procedure to insert query results into table - sql

I'm trying to do some testing on some tables but I seem to keep running into an error.
I'm trying to run the following stored procedure:
INSERT INTO [Customer].[TableA_test] ([CustomerID], [VisitID], [TransactionId], [ArrivalDT], [DataA], [DataB], [DataC], [SnapDate])
SELECT
b.CustomerID,
b.VisitID,
b.TransactionID,
b.ArrivalDT,
b.DataA,
b.DataB,
b.DataC,
SnapDate = GETDATE()
FROM
[Customer].[TableA_test] a
LEFT JOIN
[Customer].[TableB] b ON a.VisitID = b.VisitID
AND a.TransactionId = b.TransactionID
WHERE
a.TransactionID IS NULL
The procedure is meant to take the results from the query and insert them into the TableA. Table A has the exact same columns and data types as TableB. When I try to execute the stored procedure (code provided above), I get the following error:
Msg 241, Level 16, State 1, Procedure InsertTo_TableA_test, Line 27
Conversion failed when converting date and/or time from character string.
All of my date columns are set to datetime data type: ArrivalDT and the SnapDate. TableA_testing and TableB have the exact same column names and datatypes.
Is there something I'm missing?
Here's the table info for [Customer].[TableA_test]:
CREATE TABLE [Customer].[TableA_test]
(
[TransactionID] [VARCHAR](254) NULL,
[VisitID] [VARCHAR](254) NULL,
[ArrivalDT] [DATETIME] NULL,
[CustomerID] [VARCHAR](254) NULL,
[DataA] [VARCHAR](50) NULL,
[DataB] [VARCHAR](50) NULL,
[DataC] [VARCHAR](50) NULL,
[SnapDate] [DATETIME] NULL
)
And for TableB:
CREATE TABLE [Customer].[TableB]
(
[TransactionID] [VARCHAR](254) NULL,
[VisitID] [VARCHAR](254) NULL,
[ArrivalDT] [DATETIME] NULL,
[CustomerID] [VARCHAR](254) NULL,
[DataA] [VARCHAR](50) NULL,
[DataB] [VARCHAR](50) NULL,
[DataC] [VARCHAR](50) NULL,
[SnapDate] [DATETIME] NULL
)
Line 27 of my stored procedure is:
INSERT INTO [Customer].[JTM_NY_SPARCS_VitalSigns_test] ([CustomerID],[VisitID], [TransactionID], [ArrivalDT], [DataA], [DataB], [DataC], [SnapDate])
Here's the full read-out of the stored procedure:
USE [Database_3]
GO
/****** Object: StoredProcedure [Customer].[InsertTo_TableA_test] Script Date: 4/12/2019 11:49:17 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Customer].[InsertTo_TableA_test]
/*
CREATED: 04/11/2019
*/
AS
BEGIN
INSERT INTO [Customer].[TableA_test] ([CustomerID], [VisitID], [TransactionId], [ArrivalDT], [DataA], [DataB], [DataC], [SnapDate])
SELECT
b.CustomerID,
b.VisitID,
b.TransactionID,
b.ArrivalDT,
b.DataA,
b.DataB,
b.DataC,
SnapDate = GETDATE()
FROM
[Customer].[TableA_test] a
LEFT JOIN
[Customer].[TableB] b ON a.VisitID = b.VisitID
AND a.TransactionId = b.TransactionID
WHERE
a.TransactionID IS NULL
END
GO
Example of a row of results when running the query from the stored procedure:
100010 [VisitID]
20000281542 [TransactionID]
2014-07-09 15:44:42.000 [ArrivalDT]
0032011 [CustomerID]
147 [DataA]
71 [DataB]
69 [DataC]
2019-04-12 11:54:23.753 [SnapDate]

From what I have seen in your comments, you said you are trying to insert from TableA_test to TableB. If that is the case, then your query should be:
INSERT INTO [Customer].[TableB] ([CustomerID],[VisitID],[TransactionId],[ArrivalDT],[DataA],[DataB],[DataC],[SnapDate])
SELECT
a.CustomerID,
a.VisitID,
a.TranactionID,
a.ArrivalDT,
a.DataA,
a.DataB,
a.DataC,
SnapDate = GETDATE()
FROM [Customer].[TableA_test] a
LEFT JOIN [Customer].[TableB] b
ON a.VisitID = b.VisitID
AND a.TransactionId = b.TransactionID
WHERE b.TransactionID IS NULL

Related

SQL Merge Statement Assistance

Good afternoon,
I'm trying to do a SQL merge with a few steps before this one.
Drop Temp Table (If it exists)
Create a temp table (Source)
USE Kronos Create table #tempGlobal --Source ( [800#] [bigint] NOT NULL, [FirstName] [varchar](20) NOT NULL, [MI] CHAR(20) NULL, [LastName] [nvarchar](30) NOT NULL, [NickName] CHAR(15) NULL, [Position] [nvarchar](50) NULL, [Department] [varchar](30) NULL, [EmployeeStatus] [char](20) NOT NULL, [CredentialDocument] VARCHAR(10) NOT NULL, [RehireDate] [date] NULL, [DateHired] [date] NOT NULL, [DateTerminated] [date] NULL)
Bulk insert from CSV into the temp table
Merge source table and target table
I don't get any job errors, but the data doesn't get updated in my test sessions.
Step 4:
` Select t.[800#], t.[FirstName], t.[MI], t.[LastName], t.[NickName], t.[Position], t.[Department], t.[EmployeeStatus], t.[CredentialDocument], t.[RehireDate], t.[DateHired], t.[DateTerminated]
From [dbo].[Employees] t --Target
Merge [dbo].[Employees] t
using [dbo].[#tempGlobal] s --Source Temp Table
on t.[800#] = s.[800#] --Stays the same even if rehired
WHEN MATCHED
AND
(
s.[LastName] <> t.[LastName]
OR s.[Position] <> t.[Position]
OR s.[Department] <> t.[Department]
OR s.[EmployeeStatus] <> t.[EmployeeStatus]
OR s.[RehireDate] <> t.[RehireDate]
OR s.[DateTerminated] <> t.[LastName]
)
THEN
UPDATE SET LastName = s.LastName,
Position = s.Position,
Department = s.Department,
EmployeeStatus = s.EmployeeStatus,
RehireDate = s.RehireDate,
DateTerminated = s.DateTerminated
WHEN NOT MATCHED --Source table doesn't match target table so we need to update the target table to match
THEN INSERT
(
[800#],
[FirstName],
[MI],
[LastName],
[NickName],
[Position],
[Department],
[EmployeeStatus],
[CredentialDocument],
[RehireDate],
[DateHired],
[DateTerminated])
VALUES
(
s.[800#],
s.FirstName,
s.MI,
s.LastName,
s.NickName,
s.Position,
s.Department,
s.EmployeeStatus,
s.CredentialDocument,
s.RehireDate,
s.DateHired,
s.DateTerminated);`

updated record is inserting into the history table not the old record

i have two tables Test and TestHistory
CREATE TABLE [dbo].[TEST](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Test_History](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL
) ON [PRIMARY]
GO
INSERT INTO TEST ([ID],[Name],[Status],[CreatedDate])values (1,'Mohan','A',GETDATE())
Created Trigger :
ALTER TRIGGER [dbo].[trg_Test]
ON [dbo].[TEST]
FOR UPDATE
AS
Declare #ID INT;
Declare #Name varchar(10);
Declare #Status CHAR(2);
Declare #CreatedDate DATETIME;
Select #ID = I.ID from INSERTED I
Select #Name = I.Name from INSERTED I
Select #Status = I.Status from INSERTED I
Select #CreatedDate = I.CreatedDate from INSERTED I
INSERT INTO [dbo].[Test_history]
([ID]
,[Name]
,[Status]
,[CreatedDate]
)
SELECT #ID,
#Name,
#Status,
GETDATE()
FROM INSERTED I
WHERE #ID = [ID]
When I'm updating the record like
Update [TEST] SET Status = 'I' then the old record with Status = 'A' should inserted but the what ever i'm updating it has been inserting into Testhistory table not the old record
where i'm doing wrong and how to insert old value
like if i updating Status = 'I' and in history table Status = 'A' shoul be inserted
You need to INSERT from DELETED not from INSERTED.
See examples here Understanding SQL Server inserted and deleted tables for DML triggers.
Like Karl mentioned, you need to refer deleted table for old updated row information. Apart from that your existing code doesn't work when you update more than a single row. What you need is something like this.
ALTER TRIGGER [dbo].[trg_Test]
ON [dbo].[TEST]
FOR UPDATE
AS
INSERT INTO [dbo].[Test_history]
(
[ID],
[Name],
[Status],
[CreatedDate]
)
SELECT ID,
Name,
Status,
GETDATE()
FROM deleted d

update trigger to update records in another table

I have on User_Table
CREATE TABLE [dbo].[User_TB]
(
[User_Id] [varchar](15) NOT NULL,
[User_FullName] [varchar](50) NULL,
[User_Address] [varchar](150) NULL,
[User_Gender] [varchar](10) NULL,
[User_Joindate] [varchar](50) NULL,
[User_Email] [varchar](50) NULL,
[User_Branch] [varchar](50) NULL,
[User_TeamLeader] [varchar](50) NULL,
[User_Department] [varchar](50) NULL,
[User_Position] [varchar](50) NULL,
[TID] [int] NULL
)
Break_Table
CREATE TABLE [dbo].[Break_TB]
(
[Break_Id] [int] IDENTITY(1,1) NOT NULL,
[User_Id] [varchar](15) NOT NULL,
[Date] [date] NULL,
[Break_Time] [int] NULL,
[Status] [varchar](50) NULL,
[Late_time] [int] NULL,
[TL_Id] [varchar](15) NULL,
[start_Time] [time](7) NULL,
[end_Time] [time](7) NULL,
)
Log_Table
CREATE TABLE [dbo].[Log_TB]
(
[User_Id] [varchar](50) NOT NULL,
[First_Login] [time](0) NULL,
[Logout] [time](0) NULL,
[Date] [date] NULL,
[Working_Hrs] [time](0) NULL,
)
Now what am trying to do is that whenever the User_Id from User_Table is Updated , I want trying to update User_Id of Another two tables,
I have written trigger for that
Alter TRIGGER [dbo].[updateUserId] on [dbo].[User_TB]
FOR Update
AS
declare #Branch_Name varchar(50),
#User_Id varchar(15)
select #User_Id = i.User_Id from inserted i;
Update Break_TB set User_Id = #User_Id where User_Id = #User_Id;
Update Log_TB set User_Id = #User_Id where User_Id = #User_Id;
But
It only updates records from Break_TB, It not works for Log_TB
Am not very good at triggers, if am wrong please Help me.
You would need something like this - a set-based solution that takes into account that in an UPDATE statement, you might be updating multiple rows at once, and therefore your trigger also must deal with multiple rows in the Inserted and Deleted tables.
CREATE TRIGGER [dbo].[updateUserId]
ON [dbo].[User_TB]
FOR UPDATE
AS
-- update the "Break" table - find the rows based on the *old* User_Id
-- from the "Deleted" pseudo table, and set it to the *new* User_Id
-- from the "Inserted" pseudo table
SET User_Id = i.User_Id
FROM Inserted i
INNER JOIN Deleted d ON i.TID = d.TID
WHERE
Break_TB.User_Id = d.User_Id
-- update the "Log" table - find the rows based on the *old* User_Id
-- from the "Deleted" pseudo table, and set it to the *new* User_Id
-- from the "Inserted" pseudo table
UPDATE Break_TB
SET User_Id = i.User_Id
FROM Inserted i
INNER JOIN Deleted d ON i.TID = d.TID
WHERE
Break_TB.User_Id = d.User_Id
This code assumes that the TID column in the User_TB table is the primary key which remains the same during updates (so that I can join together the "old" values from the Deleted pseudo table with the "new" values after the update, stored in the Inserted pseudo table)

Why do i get this error when i do a SELECT..INSERT in SQL Server

Why do i get this error
The select list for the INSERT statement contains more items than the
insert list. The number of SELECT values must match the number of
INSERT columns.
When i run this query
INSERT INTO TempOutputOfGroupifySP
(MonthOfQuery,Associate,[NoOfClaims],[ActualNoOfLines],[AverageTATInDays],
[NoOfErrorsDiscovered],[VarianceinPercent],[NoOfClaimsAudited],[InternalQualInPercent],[ExternalQualInPercent]
)
SELECT (DATENAME(MONTH,[ClaimProcessedDate])) AS MonthOfQuery,
Temp.Associate AS Associate,
COUNT(*) AS [NoOfClaims],
SUM(NoOfLines) AS [ActualNoOfLines] ,
(SUM(DATEDIFF(dd,[ClaimReceivedDate],[ClaimProcessedDate]))/COUNT(*)) AS [AverageTATInDays],
A.[NoOfErrorsDiscovered] AS [NoOfErrorsDiscovered],
Temp.[MonthlyTarget] As [TargetNoOfLines],(Temp.[MonthlyTarget] - COUNT(*)) AS [VarianceInPercent],
B.[NoOfClaimsAudited] AS [NoOfClaimsAudited],
((A.[NoOfErrorsDiscovered]/NULLIF(B.[NoOfClaimsAudited],0))*100) AS [InternalQualInPercent],
NULL AS [ExternalQualInPercent]
FROM
(SELECT COUNT(*) AS [NoOfErrorsDiscovered] FROM TempTableForStatisticsOfAssociates T1 WHERE [TypeOfError] IS NOT NULL) AS A,
(SELECT COUNT(*) AS [NoOfClaimsAudited] FROM TempTableForStatisticsOfAssociates T2 WHERE Auditor IS NOT NULL) AS B,
TempTableForStatisticsOfAssociates Temp
GROUP BY DATENAME(MONTH,([ClaimProcessedDate])),
Temp.Associate,
A.[NoOfErrorsDiscovered],
Temp.[MonthlyTarget],
B.[NoOfClaimsAudited]
Strucuture of the target table is
CREATE TABLE [dbo].[TempOutputOfGroupifySP](
[MonthOfQuery] [nchar](10) NULL,
[Associate] [nvarchar](max) NULL,
[NoOfClaims] [int] NULL,
[ActualNoOfLines] [int] NULL,
[AverageTATInDays] [int] NULL,
[NoOfErrorsDiscovered] [int] NULL,
[VarianceInPercent] [float] NULL,
[NoOfClaimsAudited] [int] NULL,
[InternalQualInPercent] [float] NULL,
[ExternalQualInPercent] [float] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Your INSERT INTO defines 10 colums for the insertion, however, your SELECT statement return 11 columns. You are either missing a column in your INSERT statement or returning one too many in your SELECT statement.
Comparing your table structure and your SELECT and INSERT the following line in your SELECT statement doesn't have a counterpart:
Temp.[MonthlyTarget] As [TargetNoOfLines]

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