I'm new to writing SQL Server triggers. I have a table called USERS and I also a another tabled called USERS_DELTA. The difference between the two is USERS_DELTA has one additional column called change_type.
Here are the table schema:
USERS table:
CREATE TABLE [dbo].[TDR_Users]
(
[objectGUID] [varbinary](50) NOT NULL,
[distinguishedName] [nvarchar](255) NOT NULL,
[adForest] [nvarchar](50) NULL,
[adDomain] [nvarchar](50) NULL,
[accountExpires] [datetime] NULL,
[adminCount] [int] NULL,
[cn] [nvarchar](64) NULL,
[company] [nvarchar](64) NULL,
[description] [nvarchar](448) NULL,
[displayName] [nvarchar](256) NULL,
[division] [nvarchar](256) NULL,
[employeeID] [nvarchar](16) NULL
)
And USERS_DELTA table:
CREATE TABLE [dbo].[TDR_Users]
(
[objectGUID] [varbinary](50) NOT NULL,
[distinguishedName] [nvarchar](255) NOT NULL,
[adForest] [nvarchar](50) NULL,
[adDomain] [nvarchar](50) NULL,
[accountExpires] [datetime] NULL,
[adminCount] [int] NULL,
[cn] [nvarchar](64) NULL,
[company] [nvarchar](64) NULL,
[description] [nvarchar](448) NULL,
[displayName] [nvarchar](256) NULL,
[division] [nvarchar](256) NULL,
[employeeID] [nvarchar](16) NULL,
[change_Type] [nvarchar](10) NULL
)
I have an application which will be creating records in USERS table. But what I'm trying to do is capture the inserts into the USERS_DELTA. I have written a trigger on the USERS table:
CREATE TRIGGER [dbo].[TR_INSERTS_DELTAS]
ON [dbo].[Users]
FOR INSERT
AS
DECLARE #ObjectGUID varbinary(50), #DN varchar(255), #memcount int;
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Get the primary and unique keys from the inserted rows.
SELECT #DN=i.distinguishedName FROM inserted i;
SELECT #ObjectGUID = i.objectGUID FROM inserted i;
-- Check if a row already exists in the TDR_Users_Delta table with those values.
SELECT #memcount=COUNT(*) FROM Users
WHERE Users.distinguishedName = #DN
AND Users.objectGUID = #ObjectGUID ;
if(#memcount = 0)
BEGIN
INSERT INTO [dbo].[Users_Delta]
(
[objectGUID],
[distinguishedName],
[adForest],
[adDomain],
[accountExpires],
[adminCount],
[cn] ,
[company],
[description],
[displayName],
[division],
[employeeID],
[change_type]
)
VALUES
(
INSERTED.[objectGUID],
INSERTED.[distinguishedName],
INSERTED.[adForest],
INSERTED.[adDomain],
INSERTED.[accountExpires],
INSERTED.[adminCount],
INSERTED.[cn] ,
INSERTED.[company],
INSERTED.[description],
INSERTED.[displayName],
INSERTED.[division],
INSERTED.[employeeID],
'Add'
);
END
END
GO
When I execute this trigger, I get the following error:
Msg 4104, Level 16, State 1, Procedure TR_INSERTS_DELTAS, Line 94
The multi-part identifier "Inserted.objectGUID" could not be bound.
Msg 4104, Level 16, State 1, Procedure TR_INSERTS_DELTAS, Line 95
The multi-part identifier "INSERTED.distinguishedName" could not be bound.
Msg 4104, Level 16, State 1, Procedure TR_INSERTS_DELTAS, Line 96
The multi-part identifier "INSERTED.adForest" could not be bound.
Msg 4104, Level 16, State 1, Procedure TR_INSERTS_DELTAS, Line 97
The multi-part identifier "INSERTED.adDomain" could not be bound.
Msg 4104, Level 16, State 1, Procedure TR_INSERTS_DELTAS, Line 98
...
What am I doing wrong? :(
I think you just need to put a select with the table in rather than using inserted.x to signify the insert.
CREATE TRIGGER [dbo].[TR_INSERTS_DELTAS]
ON [dbo].[Users]
FOR INSERT
AS
DECLARE #ObjectGUID varbinary(50), #DN varchar(255), #memcount int;
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Get the primary and unique keys from the inserted rows.
SELECT #DN=i.distinguishedName FROM inserted i;
SELECT #ObjectGUID = i.objectGUID FROM inserted i;
-- Check if a row already exists in the TDR_Users_Delta table with those values.
SELECT #memcount=COUNT(*) FROM Users
WHERE Users.distinguishedName = #DN
AND Users.objectGUID = #ObjectGUID ;
if(#memcount = 0)
BEGIN
INSERT INTO [dbo].[Users_Delta]
(
[objectGUID],
[distinguishedName],
[adForest],
[adDomain],
[accountExpires],
[adminCount],
[cn] ,
[company],
[description],
[displayName],
[division],
[employeeID],
[change_type]
)
select
INSERTED.[objectGUID],
INSERTED.[distinguishedName],
INSERTED.[adForest],
INSERTED.[adDomain],
INSERTED.[accountExpires],
INSERTED.[adminCount],
INSERTED.[cn] ,
INSERTED.[company],
INSERTED.[description],
INSERTED.[displayName],
INSERTED.[division],
INSERTED.[employeeID],
'Add'
From inserted
END
END
GO
Related
I am trying to write a stored procedure that creates a new row of data in my table that has an Identity column. I can't figure out what I'm doing wrong to get it to store my data in the table.
Here is my table
CREATE TABLE [Promotional].[Proposals]
(
[Proposal_Uid] [int] IDENTITY(1,1) NOT NULL,
[Prime_Contract] [nvarchar](30) NULL,
[Sub_Contract] [nvarchar](30) NULL,
[Po_Id] [nvarchar](30) NULL,
[Proposal_Title] [nvarchar](50) NULL,
[Client_Name] [nvarchar](40) NULL,
[Client_Code] [nvarchar](20) NULL,
[Total_Proposal_Amount] [decimal](18, 2) NULL,
[ODC_Amount] [decimal](18, 2) NULL,
[Manager_Name] [nvarchar](30) NULL,
[Admin] [nvarchar](30) NULL,
[Due_Date] [date] NULL,
[Start_Date] [date] NULL,
[End_Date] [date] NULL,
[Proposal_Number] [nvarchar](20) NULL,
[Contract_Type] [nvarchar](16) NULL,
CONSTRAINT [Proposal_Uid]
PRIMARY KEY CLUSTERED ([Proposal_Uid] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Here is my stored procedure:
ALTER PROCEDURE [Promotional].[Proposals_Create]
(#Prime_Contract nvarchar(30),
#Sub_Contract nvarchar(30),
#Po_Id nvarchar(30),
#Proposal_Title nvarchar(50),
#Client_Name nvarchar(40),
#Client_Code nvarchar(20),
#Total_Proposal_Amount decimal(18,2),
#ODC_Amount decimal(18,2),
#Manager_Name nvarchar(30),
#Admin nvarchar(30),
#Due_Date date,
#Start_Date date,
#End_Date date,
#Proposal_Number nvarchar(20),
#Contract_Type nvarchar(16),
#NewId int output)
AS
BEGIN
IF #NewId IS NULL
BEGIN
INSERT INTO Promotional.Proposals (Prime_Contract, Sub_Contract, Po_Id, Proposal_Title, Client_Name, Client_Code,
Total_Proposal_Amount, ODC_Amount, Manager_Name, Admin, Due_Date, Start_Date, End_Date, Proposal_Number, Contract_Type)
VALUES (#Prime_Contract, #Sub_Contract, #Po_Id, #Proposal_Number, #Client_Name, #Client_Code,
#Total_Proposal_Amount, #ODC_Amount, #Manager_Name, #Admin, #Due_Date, #Start_Date, #End_Date,
#Proposal_Number, #Contract_Type)
SET #NewId = SCOPE_IDENTITY()
END
RETURN #NewId
END
GO
I know it's something small I missed. But, my OUTCOME is that when you run the procedure, it inserts the values in the correct columns, and the primary key is auto updated without having to stick your own value into the statement. My execution of the statement would be as follows
EXEC Promotional.Proposals_Create 'hj','fd','fd','fd','fd','fd','0.23','1.24','fd','fd','2020/08/30','2020/08/30','2020/08/30','fd','fd';
And I get this error:
Msg 201, Level 16, State 4, Procedure Promotional.Proposals_Create, Line 0 [Batch Start Line 0]
Procedure or function 'Proposals_Create' expects parameter '#NewId', which was not supplied.
I shouldn't have to provide that parameter because it should auto update with my PK which is Proposal_Uid. Or do I have to make my Proposal_Uid the value returned from ScopeIdentity?
#NewID should not be a parameter of the procedure since it is an IDENTITY column.
You can get the stored procedure to return the generated id by providing an output variable to store its content. This behaviour is also documented here.
declare #test int;
EXEC Proposals_Create 'hj','fd','fd','fd','fd','fd','0.23','1.24','fd','fd',
'2020/08/30','2020/08/30','2020/08/30','fd','fd', #test OUTPUT;
select #test as 'new_identity';
set #test = null; -- because of the IF statement in your procedure...
EXEC Proposals_Create 'hj','fd','fd','fd','fd','fd','0.23','1.24','fd','fd',
'2020/08/30','2020/08/30','2020/08/30','fd','fd', #test OUTPUT;
select #test as 'new_identity';
The selects return 1 and 2 respectively.
Fiddle (Remark: schema name removed in code above and in fiddle).
I've run into an issue a couple times now where I'll encase a query in BEGIN TRAN / ROLLBACK TRAN (so I can verify it works before committing any changes), and will get the error below. The BEGIN TRAN statement does not generate an error.
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION
The commands I was using the most recent time are below. I didn't save the errors at the time, but I believe that the UPDATE commands also errored because it didn't recognize ClientId as a valid column.
Each time it has done this, some statements have been rolled back, and others remained. In this case, I have neither a ClientId nor a ClientCode column.
I also can't perfectly recreate the initial run since running these outside of a transaction has caused me to lose all of my ClientCode fields, and the ClientId fields are not in the tables. Thankfully, none of the dev data was important, but because of its volume, it'll take me a little bit to repopulate.
Initially, I thought I'd just selected some of the query before running it, ommiting the BEGIN TRAN, so I reran it, careful to select everything and got the same error, as well as a host of others caused by the missing ClientCode field.
I'd like to know why this is happening so I can prevent it in the future.
EDIT: I did some additional testing on a later date and I have been unable to recreate this behavior. The transactions are being rolled back correctly, and the UPDATE command is not erroring for having an invalid column
BEGIN TRAN
ALTER TABLE tblInvoices ADD ClientId INT NULL
GO
UPDATE tblInvoices
SET ClientId = c.Id
FROM tblInvoices i
INNER JOIN Core.dbo.tblClients c
ON i.ClientCode = c.ClientCode
GO
ALTER TABLE tblInvoices ALTER COLUMN ClientId INT NOT NULL
GO
ALTER TABLE tblInvoices DROP COLUMN ClientCode
GO
ALTER TABLE tblClientSettings ADD ClientId INT NULL
GO
UPDATE tblClientSettings
SET ClientId = c.Id
FROM tblClientSettings cs
INNER JOIN Core.dbo.tblClients c
ON cs.ClientCode = c.ClientCode
GO
ALTER TABLE tblClientSettings ALTER COLUMN ClientId INT NOT NULL
GO
ALTER TABLE tblClientSettings DROP COLUMN ClientCode
GO
ROLLBACK TRAN
EDIT 2: It happened again on a small set of commands. The commands and the output messages are below.
Input:
BEGIN TRAN
CREATE TABLE tblEmailTemplates(
Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
Subject NVARCHAR(2000) NULL,
Body NVARCHAR(MAX) NULL,
Sender NVARCHAR(200) NULL,
Recipients NVARCHAR(2000) NULL,
CC NVARCHAR(2000) NULL,
BCC NVARCHAR(2000) NULL,
Html BIT NULL
)
CREATE TABLE tblContactSeries (
Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
AppId INT NOT NULL REFERENCES Foo_Apps.dbo.tblApps(Id),
Description NVARCHAR(200) NOT NULL
)
CREATE TABLE [dbo].tblEmails(
[Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
SeriesId INT NOT NULL REFERENCES tblContactSeries(Id),
TemplateId INT NULL REFERENCES tblEmailTemplates(Id),
TemplateParameters NVARCHAR(MAX) NULL,
[Sender] [nvarchar](200) NULL,
[Recipients] [nvarchar](2000) NULL,
[CC] [nvarchar](2000) NULL,
[BCC] [nvarchar](2000) NULL,
[Subject] [nvarchar](2000) NULL,
[Body] [nvarchar](max) NULL,
[Html] [bit] NOT NULL,
[ScheduledDate] [datetime] NOT NULL,
[OverdueDate] [datetime] NULL,
[Active] [bit] NOT NULL,
[Sent] [bit] NOT NULL,
[SendTime] [datetime] NULL,
[SendSuccess] [bit] NULL
)
CREATE TABLE [dbo].[tblAttachments](
[Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
EmailId [int] NOT NULL REFERENCES tblEmails(Id),
[FilePath] [nvarchar](2000) NULL,
[FileName] [nvarchar](200) NULL
)
GO
CREATE VIEW vwPendingAttachments AS
SELECT a.*
FROM tblAttachments a
INNER JOIN tblEmails e
ON a.EmailId = e.Id
WHERE e.Active = 1 AND e.Sent != 1
GO
ROLLBACK TRAN
Messages:
Msg 1763, Level 16, State 0, Line 23
Cross-database foreign key references are not supported. Foreign key 'Foo_Apps.dbo.tblApps'.
Msg 1750, Level 16, State 1, Line 23
Could not create constraint or index. See previous errors.
Msg 208, Level 16, State 1, Procedure vwPendingAttachments, Line 4 [Batch Start Line 59]
Invalid object name 'tblAttachments'.
Msg 3903, Level 16, State 1, Line 70
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
-- --------------------------------------------------------
-- Host: 192.168.62.245
-- Server version: Microsoft SQL Server 2014 - 12.0.2000.8
-- Server OS: Windows NT 6.1 <X64> (Build 7601: ) (WOW64) (Hypervisor)
-- HeidiSQL Version: 9.5.0.5196
-- --------------------------------------------------------
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES */;
/*!40014 SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping database structure for mjDB
CREATE DATABASE IF NOT EXISTS "mjDB";
USE "mjDB";
-- Dumping structure for table mjDB.PushNotificationLog
CREATE TABLE IF NOT EXISTS "PushNotificationLog" (
"pushNotificationLogId" INT(10,0) NOT NULL,
"itemType" VARCHAR(20) NULL DEFAULT NULL,
"itemId" INT(10,0) NULL DEFAULT NULL,
"servicemanId" INT(10,0) NULL DEFAULT NULL,
"title" VARCHAR(100) NULL DEFAULT NULL,
"body" VARCHAR(4000) NULL DEFAULT NULL,
"tranId" INT(10,0) NULL DEFAULT NULL,
"createdBy" INT(10,0) NULL DEFAULT NULL,
"createdDate" DATETIME(3) NULL DEFAULT NULL,
PRIMARY KEY ("pushNotificationLogId")
);
I exported this one from HeidiSQL updated to 19/12/2017, when I try to run this on SQL Server 2014 I get this error:
Msg 156, Level 15, State 1, Line 16
Incorrect syntax near the keyword 'IF'.
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near 'mjDB'.
Msg 911, Level 16, State 1, Line 17
Database 'mjDB' does not exist. Make sure that the name is entered correctly.
Your create table syntax is wrong if you are using SQL Server. Change the code like this if you wish to check the table existence before creating
IF object_id('PushNotificationLog') IS NULL
BEGIN
CREATE TABLE [PushNotificationLog]
(
pushNotificationLogId INT NOT NULL,
itemType VARCHAR(20) NULL DEFAULT NULL,
itemId INT NULL DEFAULT NULL,
servicemanId INT NULL DEFAULT NULL,
title VARCHAR(100) NULL DEFAULT NULL,
body VARCHAR(4000) NULL DEFAULT NULL,
tranId INT NULL DEFAULT NULL,
createdBy INT NULL DEFAULT NULL,
createdDate DATETIME NULL DEFAULT NULL,
PRIMARY KEY (pushNotificationLogId)
);
END
You can also do the check by checking the existence in the view sys.tables
IF NOT EXISTS(SELECT 1 FROM sys.tables WHERE name = 'PushNotificationLog')
BEGIN
END
Similarly Check in the master.sys.databases table for the existence of Database
IF NOT EXISTS(SELECT 1 FROM master.sys.databases WHERE name = 'mjDB')
BEGIN
END
Use single quotes (') instead of double quotes (")
Remove the quotes from the identifiers (DatabaseName, TableName)
Replace the quotes in the column names with square brackets ([])
IF NOT EXISTS
(
SELECT 1
FROM [master].sys.databases
WHERE [name] = 'mjDB'
)
BEGIN CREATE DATABASE mjDB; END
GO
USE mjDB;
GO
-- Dumping structure for table mjDB.PushNotificationLog
IF (OBJECT_ID('dbo.PushNotificationLog', 'U') IS NULL)
BEGIN
CREATE TABLE dbo.PushNotificationLog
(
[PushNotificationLogID] INT NOT NULL
, [ItemType] VARCHAR(20)
, [ItemID] INT
, [ServicemanID] INT
, [Title] VARCHAR(100)
, [Body] VARCHAR(4000)
, [TranId] INT
, [CreatedBy] INT
, [CreatedDate] DATETIME
, CONSTRAINT PK__PushNotificationLog PRIMARY KEY ([pushNotificationLogId])
);
END
GO
I have a 3 tables UniversityReg, SupporterReg & Login. If university or supporter register with the system, always general details goes to their table & login details goes to Login table. In here I use scope_identity.
I'm getting error when I go to save supporter reg details.
Errors
Msg 515, Level 16, State 2, Procedure SupporterReg_SP, Line 16
Cannot insert the value NULL into column 'SupporterId', table 'CounsellingDB.dbo.SupporterReg'; column does not allow nulls. INSERT fails.
Msg 515, Level 16, State 2, Procedure SupporterReg_SP, Line 20
Cannot insert the value NULL into column 'LoginID', table 'CounsellingDB.dbo.Login'; column does not allow nulls. INSERT fails.
UniversityReg SP
ALTER PROCEDURE [dbo].[UniversityReg_SP]
(
#Username varchar(50),
#Password varchar(50),
#UniversityName varchar(50) ,
#GovernmentRegNo varchar(50) ,
#Country varchar(50) ,
#CreatedBy varchar(50)
)
AS
DECLARE #LoginID int
INSERT INTO UniversityReg (UniversityName,GovernmentRegNo,Country,CreatedBy,ShortCode)values(#UniversityName,#GovernmentRegNo,#Country,#CreatedBy,'UNI')
SET #LoginID = SCOPE_IDENTITY();
INSERT INTO Login values(#LoginID,#Username,#Password,'UNI')
RETURN
SupporterReg_SP
CREATE PROCEDURE [dbo].[SupporterReg_SP]
(
#UserName varchar(50),
#Password varchar(50),
#SupporterName varchar(50),
#University varchar(50) ,
#ContactNo varchar(50),
#Email varchar(50),
#StudentLocation varchar(50)
)
AS
DECLARE #LoginID int
INSERT INTO SupporterReg(SupporterName,University,ContactNo,Email,StudentLocation,ImagePath,ShortCode)V alues(#SupporterName,#University,#ContactNo,#Email,#StudentLocation,'','SUP')
SET #LoginID = SCOPE_IDENTITY();
INSERT INTO Login values(#LoginID,#UserName,#Password,'SUP')
RETURN
UniversityReg Table
[UniversityId] [int] IDENTITY(1,1) NOT NULL,
[Username] [varchar](50) NULL,
[Password] [varchar](50) NULL,
[UniversityName] [varchar](50) NULL,
[GovernmentRegNo] [varchar](50) NULL,
[Country] [varchar](50) NULL,
[CreatedBy] [varchar](50) NULL,
[ShortCode] [varchar](50) NULL,
Login Table
[LoginID] [int] NOT NULL,
[UserName] [nvarchar](50) NOT NULL,
[Password] [nvarchar](50) NOT NULL,
[ShortCode] [nvarchar](50) NULL
SupporterReg table
[SupporterId] [int] NOT NULL,
[SupporterName] [varchar](50) NULL,
[University] [varchar](50) NULL,
[ContactNo] [varchar](50) NULL,
[Email] [varchar](50) NULL,
[StudentLocation] [varchar](50) NULL,
[ImagePath] [varchar](50) NULL,
[ShortCode] [varchar](50) NULL,
In your stored procedures #LoginID is the ID for SupporterReg or UniversityReg, not for Login
In Login, your LoginID column should be defined as int identity(1,1) and you should specify column names in your insert
INSERT INTO Login (column, names, go here)
values(#LoginID,#UserName,#Password,'SUP')
Your trouble is that your procedure is attempting to insert multiple values into the SupporterReg table however you are not including a value for the SupporterID column, which has been defined a NOT NULL.
You can either pass a value along with that insert statement, or adjust the table DDL so that it's an IDENTITY column and will fill that data for you.
Your design is wrong. You should not be using the id from two different tables in the login table as the loginid. This is a model that can not work in practice as both tables will sooner or later have the same id and you won't know which one the login relates to. You have a the parent child relationship reversed.
The correct design is to insert to Login first making the loginid the identity. Then insert to the child table of either UniversityReg or SupporterReg. When you do this you can have FKs and referntial integrity.
I am trying to create a stored procedure but am getting these errors:
Msg 207, Level 16, State 1, Procedure Insert_QuickLabDump, Line 42
Invalid column name 'Date_Collected'.
Msg 207, Level 16, State 1, Procedure Insert_QuickLabDump, Line 43
Invalid column name 'Time_Collected'.
Msg 207, Level 16, State 1, Procedure Insert_QuickLabDump, Line 43
Invalid column name 'Date_Entered'.
Msg 207, Level 16, State 1, Procedure Insert_QuickLabDump, Line 44
Invalid column name 'Time_Entered'.
Msg 207, Level 16, State 1, Procedure Insert_QuickLabDump, Line 45
Invalid column name 'Date_Completed'.
Msg 207, Level 16, State 1, Procedure Insert_QuickLabDump, Line 46
Invalid column name 'Time_Completed'.
Msg 207, Level 16, State 1, Procedure Insert_QuickLabDump, Line 47
Invalid column name 'Test_Date'.
Msg 207, Level 16, State 1, Procedure Insert_QuickLabDump, Line 48
Invalid column name 'Test_Time'.
here is the full source:
USE [SalesDWH]
GO
/****** Object: StoredProcedure [dbo].[Insert_QuickLabDump] Script Date: 12/22/2011 14:52:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER on
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
create PROCEDURE [dbo].[Insert_QuickLabDump]
-- Add the parameters for the stored procedure here
#Specimen_ID [varchar](50),
#Client_Key int,
#Outcome [varchar](50),
#Medications [varchar] (max),
#Date_Collected date,
#Time_Collected time ,
#Date_Entered date,
#Time_Entered time ,
#Date_Completed date,
#Time_Completed time ,
#Test_Date date ,
#Test_Time time ,
#Practice_Name [varchar] (500),
#Practice_Code [varchar] (500),
#Client_ID [varchar] (500),
#Requesting_Physician [varchar] (500),
#Other_Medications [varchar] (max),
#Order_Comments [varchar] (max),
#Reference_Number [varchar] (500),
#Order_Count int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
INSERT INTO [SalesDWH].[dbo].[QuickLabDump]
([Specimen ID]
,[Client Key]
,[Outcome]
,[Medications]
,[Date_Collected]
,[Time_Collected]
,[Date_Entered]
, [Time_Entered]
, Date_Completed
, Time_Completed
, Test_Date
, Test_Time
,[Practice Name]
,[Practice Code]
,[Client ID]
,[Requesting Physician]
,[Other Medications]
,[Order Comments]
,[Reference Number]
,[Order Count]
)
VALUES
(#Specimen_ID,
#Client_Key,
#Outcome,
#Medications,
#Date_Collected ,
#Time_Collected ,
#Date_Entered,
#Time_Entered ,
#Date_Completed ,
#Time_Completed,
#Test_Date ,
#Test_Time,
#Practice_Name,
#Practice_Code,
#Client_ID,
#Requesting_Physician,
#Other_Medications,
#Order_Comments,
#Reference_Number,
#Order_Count
)
END
What am I doing wrong?
here is the table structure:
USE [SalesDWH]
GO
/****** Object: Table [dbo].[QuickLabDump] Script Date: 12/22/2011 15:13:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[QuickLabDump](
[id] [int] IDENTITY(1,1) NOT NULL,
[Specimen ID] [varchar](50) NOT NULL,
[Client Key] [int] NOT NULL,
[Outcome] [varchar](50) NOT NULL,
[Medications] [varchar](max) NULL,
[Date Collected] [date] NOT NULL,
[Time Collected] [time](7) NOT NULL,
[Date Entered] [date] NOT NULL,
[Time Entered] [time](7) NOT NULL,
[Date Completed] [date] NOT NULL,
[Time Completed] [time](7) NOT NULL,
[Test Date] [date] NOT NULL,
[Test Time] [time](7) NOT NULL,
[Practice Name] [varchar](500) NOT NULL,
[Practice Code] [varchar](500) NOT NULL,
[Client ID] [varchar](500) NULL,
[Requesting Physician] [varchar](500) NULL,
[Other Medications] [varchar](max) NULL,
[Order Comments] [varchar](max) NULL,
[Reference Number] [varchar](500) NULL,
[Order Count] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
The errors are saying that there are no such columns (for example Date_Collected) in the QuickLabDump table. For insert statements, you have to have the right column names. You have a column named Date Collected, not Date_Collected, for example (note the space instead of the underscore).
It looks like you added those columns to an existing procedure. Have you added the columns to the database table you are trying to insert to?
You are using [Date_Collected] in your stored procedure, but the actual column name according to the CREATE TABLE statement is [Date Collected] (no underscore).
[Date Collected] [date] NOT NULL,
is not the same as Msg 207, Level 16, State 1, Procedure Insert_QuickLabDump, Line 42
Invalid column name 'Date_Collected'.