Insert stored procedure passing parameter - sql

I have this SQL statement
INSERT housingSurvey ([nameID], [houseID], [jobID], [Active], [comment], [needsMaintenance], [lastUpdateDate)
VALUES (#NAMEID, #HOUSEID, #JOBID, 1, #DUEDATE, #COMMENT, NULL, #LASTUPDATEDATE)
I tried this stored procedure, but I don't get the current date.
CREATE PROCEDURE housingSurveyS(
#NAMEID INT,
#HOUSEID INT,
#JOBID INT,
#COMMENT BIT,
#DUEDATE NVARCHAR,
CURRENTTIME)
AS
BEGIN
INSERT INTO housingSurvey(
[nameID],
[houseID],
[jobID],
[Active],
[comment],
[dueDate],
[needsMaintenance],
[lastupdatedate])
VALUES (
#NAMEID,
#HOUSEID,
#JOBID,
1,
#COMMENT,
#DUEDATE,
NULL,
#LASTUPDATEDATE)
END
Could you please take a look at what I did wrong. Thanks
UPDATE
I changed it CURRENTTIME to DATETIME as parameter to insert current date to [lastupdatedate]... it still doesn't work...

VALUES (
...
#DUEDATE,
#COMMENT
Are in the wrong order when related to the order of fields defined in the INSERTs statements field list, switch them around.
Edit
CREATE PROCEDURE housingSurveyS(
#NAMEID INT,
#HOUSEID INT,
#JOBID INT,
#COMMENT BIT,
#DUEDATE NVARCHAR(32) --add a size, should this be DATETIME
)
AS
BEGIN
INSERT INTO housingSurvey(
[nameID],
[houseID],
[jobID],
[Active],
[comment],
[dueDate],
[needsMaintenance],
[lastupdatedate]
) VALUES (
#NAMEID,
#HOUSEID,
#JOBID,
1,
#COMMENT,
#DUEDATE,
NULL,
GETDATE()
)
END

Related

Insert new data to a table with stored procedure

I tried to make a stored procedure the insert data to a table:
create procedure AddEmployee
(
#FirstName nvarchar(20)
, #LastName nvarchar(20)
, #BirthDate datetime
, #Country nvarchar(15)
, #City nvarchar(15)
)
as
insert into Employees
values (#FirstName, #LastName, #BirthDate, #Country, #City)
go
But when I run it I get the error message:
Msg 213, Level 16, State 1, Procedure AddEmployee, Line 2 [Batch Start Line 17]
Column name or number of supplied values does not match table definition.
I looked at this question but it didn't solve my problem:
Create a stored procedure to insert new data into a table
When using insert, always include the columns names:
create procedure AddEmployee (
#FirstName nvarchar(20) ,
#LastName nvarchar(20) ,
#BirthDate datetime,
#Country nvarchar(15),
#City nvarchar(15)
) as
begin
insert into Employees (FirstName, LastName, BirthDate, Country, City)
values (#FirstName, #LastName, #BirthDate, #Country, #City);
end;
Although SQL allows you to leave out the column names, you should include them as a best-practice. This is particularly important for those learning the language, so they learn the safer way to do things.

Stored Procedure return default value?

in my database, there is a Stored Procedure with INSERT INTO statement. The problem is I want this stored procedure will return the StudentCode default value, I think it's impossible to use the SELECT TOP 1 statement to get this value because there may be multiple rows inserted at the same time. Any help or suggestions?. Thanks very much
ALTER PROC [dbo].[AddStudent]
#StudentName NVARCHAR(255),
#DoB DATETIME,
#Parent NVARCHAR(255),
#ParentContact VARCHAR(16),
#Address NVARCHAR(255),
#Class VARCHAR(6),
AS
INSERT INTO dbo.Student
( StudentCode , --I set default this column
StudentName,
DateOfBirth
NameParrent ,
PhoneContact ,
AddressParent ,
Class ,
)
VALUES ( DEFAULT , --StudentCode varchar(5)
#StudentName, --StudentName nvarchar(255)
#DoB, --DateOfBirth datetime
#Parent, --NameParrent nvarchar(255)
#ParentContact, --PhoneContact varchar(16)
#Address, --AddressParent nvarchar(255)
#Class --Class varchar(6)
)
-- How to return StudentCode field
Use OUTPUT INSERTED clause, as explained into official docs:-
INSERTED
Is a column prefix that specifies the value added by the
insert or update operation. Columns prefixed with INSERTED reflect the
value after the UPDATE, INSERT, or MERGE statement is completed but
before triggers are executed.
so your code is going to be like this:- (is not tested, but it guides you to accurate code)
ALTER PROC [dbo].[AddStudent]
#StudentName NVARCHAR(255),
#DoB DATETIME,
#Parent NVARCHAR(255),
#ParentContact VARCHAR(16),
#Address NVARCHAR(255),
#Class VARCHAR(6),
AS
DECLARE #StudentCodeInserted varchar(5)
INSERT INTO dbo.Student
( StudentCode, --I set default this column
StudentName,
DateOfBirth
NameParrent ,
PhoneContact ,
AddressParent ,
Class
)
OUTPUT inserted.StudentCode INTO #StudentCodeInserted
VALUES ( DEFAULT , --StudentCode varchar(5)
#StudentName, --StudentName nvarchar(255)
#DoB, --DateOfBirth datetime
#Parent, --NameParrent nvarchar(255)
#ParentContact, --PhoneContact varchar(16)
#Address, --AddressParent nvarchar(255)
#Class --Class varchar(6)
)
Select #StudentCodeInserted as StudentCodeInserted
You need to Return value after INSERT
DECLARE #generated_StudentCode table(StudentCode varchar(5))
INSERT INTO dbo.Student
( StudentCode, --I set default this column
StudentName,
DateOfBirth
NameParrent ,
PhoneContact ,
AddressParent ,
Class ,
)
OUTPUT inserted.StudentCode INTO #generated_keys
VALUES ( DEFAULT , --StudentCode varchar(5)
#StudentName, --StudentName nvarchar(255)
#DoB, --DateOfBirth datetime
#Parent, --NameParrent nvarchar(255)
#ParentContact, --PhoneContact varchar(16)
#Address, --AddressParent nvarchar(255)
#Class --Class varchar(6)
)
SELECT TOP 1 * FROM #generated_StudentCode
Read the following thread to have a better understanding
SQL Server - Return value after INSERT

SQL Server: How to use result from one INSERT for another INSERT

I have a stored procedure that is meant to update two tables at once.
My problem here is that the first table has an auto-incrementing ID column ("commentID") and my second table has a relationship on this so I need the newly created ID from the first INSERT in order to make the second INSERT.
I tried the following which I can save without errors but it doesnt execute as it should and does not update the tables as intended.
Can someone tell me what I am doing wrong here ?
My SQL:
ALTER PROCEDURE [dbo].[MOC_UpdateComment]
#imgID int,
#commentID int = '999999',
#comment nvarchar(1000),
#lastUpdate nvarchar(50),
#modBy varchar(50)
AS
BEGIN
DECLARE #temp AS TABLE
(
commentID int
)
SET NOCOUNT ON;
BEGIN TRANSACTION;
INSERT INTO MOC_BlogComments
(
imgID,
comment
)
OUTPUT inserted.commentID INTO #temp(commentID)
SELECT #imgID,
#comment
INSERT INTO MOC_LogComments
(
commentID,
lastUpdate,
modTime,
modBy
)
SELECT commentID,
#lastUpdate,
GETDATE(),
#modBy
FROM #temp
COMMIT TRANSACTION;
END
DECLARE #imgID INT,
#commentID INT = '999999',
#comment NVARCHAR(1000),
#lastUpdate NVARCHAR(50),
#modBy VARCHAR(50)
DECLARE #MORC_BlogComments AS TABLE
(
id INT IDENTITY(1, 1) NOT NULL,
imgid INT,
comment VARCHAR(100)
)
DECLARE #MORC_LogComments AS TABLE
(
commentid INT,
lastupdate DATETIME,
modtime DATETIME,
modby VARCHAR(100)
)
DECLARE #TEMP AS TABLE
(
commentid INT
)
SET nocount ON;
BEGIN TRANSACTION;
INSERT INTO #MORC_BlogComments
(imgid,
comment)
output inserted.id
INTO #TEMP(commentid)
VALUES (#imgID,
#comment)
INSERT INTO #MORC_LogComments
(commentid,
lastupdate,
modtime,
modby)
SELECT commentid,
#lastUpdate,
Getdate(),
#modBy
FROM #temp
SELECT *
FROM #MORC_LogComments
Function SCOPE_IDENTITY() returns the identity of last insert operation. You can use it to get the value which you need to use in second INSERT statement
You can use it like this in your statement:
INSERT INTO MORC_BlogComments (imgID, comment)
VALUES (#imgID, #comment)
INSERT INTO MORC_LogComments (commentID, lastUpdate, modTime, modBy)
VALUES (SCOPE_IDENTITY(), #lastUpdate, GETDATE(), #modBy)

Output from INSERT INTO Stored Procedure

I'm writing a stored procedure where I first insert a new row in a table. The ID that is generated by this query is then needed for another query. Is it possible to access the prevoisly generated ID with the use of OUTPUT?
This is what I have done so far and it is pretty much a guess that didnt work
ALTER PROCEDURE [dbo].[addApp]
#Name varchar(50)
, #logoUrl varchar(150)
, #siteUrl varchar(150)
, #userId int
, #canvasWidth int
, #canvasHeight int
AS
DECLARE #tempId INT
SET #tempid = INSERT INTO AppInfo (name, logoUrl, userId)
OUTPUT inserted.id
VALUES(#Name, #logoUrl, #userId);
INSERT INTO CanvasApps (id, siteUrl, canvasWidth, canvasHeight)
OUTPUT inserted.id
VALUES(#tempid, #siteUrl, #logoUrl, #userId);
You can even do it in single statement:
ALTER PROCEDURE [dbo].[addApp]
#Name VARCHAR(50)
, #logoUrl VARCHAR(150)
, #siteUrl VARCHAR(150)
, #userId INT
, #canvasWidth INT
, #canvasHeight INT
AS BEGIN
INSERT INTO dbo.AppInfo (name, logoUrl, userId)
OUTPUT Inserted.ID, #siteUrl, #canvasWidth , #canvasHeight
INTO dbo.CanvasApps (id, siteUrl, canvasWidth, canvasHeight)
VALUES (#Name, #logoUrl, #userId)
END
Try this one -
ALTER PROCEDURE [dbo].[addApp]
#Name VARCHAR(50)
, #logoUrl VARCHAR(150)
, #siteUrl VARCHAR(150)
, #userId INT
, #canvasWidth INT
, #canvasHeight INT
AS BEGIN
DECLARE #tempId INT
INSERT INTO dbo.AppInfo (name, logoUrl, userId)
SELECT #Name, #logoUrl, #userId
SELECT #tempId = SCOPE_IDENTITY()
INSERT INTO dbo.CanvasApps (id, siteUrl, canvasWidth, canvasHeight)
SELECT #tempId, #siteUrl, #logoUrl, #userId
END
Just try this after your insert statement and use this varible into second insert statement.:-
SET #BVar=SCOPE_IDENTITY()
You need to put the results of output into a table rather than just a scalar variable:
declare #tempId table (
id int
)
INSERT INTO AppInfo (name, logoUrl, userId)
OUTPUT inserted.id into #tempId
VALUES(#Name, #logoUrl, #userId);
Just use the following variable:
##IDENTITY
ALTER PROCEDURE [dbo].[addApp]
#Name varchar(50),
#logoUrl varchar(150),
#siteUrl varchar(150),
#userId int,
#canvasWidth int,
#canvasHeight int
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.AppInfo (name, logoUrl, userId)
OUTPUT inserted.id, #siteUrl, #canvasWidth, #canvasHeight
INTO dbo.CanvasApps(id, siteUrl, canvasWidth, canvasHeight)
SELECT #Name, #logonUrl, #userId;
END
GO

SQL Table Variables to insert into a different table with additional values

So I am using a cursor to loop through a bunch of records that my query returns. I have just updated some details in a table and now I want to pull the details from that table so I have used a temporary table.
So now I want to insert some values into a new table that are unrelated to the last and then the rest of the values would be a direct copy from the table variable...how can I do this?
I'll post below the section in question to help people see what I am trying to do.
The part in question is between the update status comment and the above not finished comment.
OPEN cur
FETCH NEXT FROM cur INTO #MembershipTermID , #EndDate , #MembershipID <VARIABLES>
WHILE ##FETCH_STATUS = 0
BEGIN
--PERFORM ACTION
DECLARE #TodaysDate DATETIME
SET #TodaysDate = getDate()
--CANCEL DETAIL
DECLARE #CancellationDetailID INT
INSERT INTO CancellationDetail(CancellationDetailID,RefundAmount,OldEndDate,EffectiveDate,CancelDate,ReasonCodeProgKey)
VALUES (0, 0.0, #EndDate, #TodaysDate, #TodaysDate, 'CANC_DORMANT')
SELECT #CancellationDetailID = SCOPE_IDENTITY()
INSERT INTO CancellationDetailAudit(StampUser,StampDateTime,StampAction,CancellationDetailID,RefundAmount,OldEndDate,EffectiveDate,CancelDate,ReasonCodeProgKey)
VALUES('SYSTEM', GetDate(), 'I', #CancellationDetailID, 0.0, #EndDate, #TodaysDate, #TodaysDate, 'CANC_DORMANT')
--LINK TO TERM
INSERT INTO MembershipTermCancellationDetail(CancellationDetailID,MembershipTermID)
VALUES(#CancellationDetailID, #MembershipTermID)
INSERT INTO MembershipTermCancellationDetailAudit(StampUser,StampDateTime,StampAction,MembershipTermCancellationDetailID,CancellationDetailID,MembershipTermID)
VALUES('SYSTEM', GetDate(), 'I', 0, #CancellationDetailID, #MembershipTermID)
--UPDATE STATUS
UPDATE MembershipTerm
SET MemberStatusProgKey = 'CANCELLED',
EndDate = #TodaysDate,
UpdateDateTime = #TodaysDate,
AgentID = 224,
NextTermPrePaid = 'False'
WHERE MembershipTermID = #MembershipTermID
DECLARE #MembershipTermTable TABLE
(
MembershipTermID int,
MemberStatusProgKey nvarchar (50),
StartDate datetime,
EndDate datetime,
AdditionalDiscount float,
EntryDateTime datetime,
UpdateDateTime datetime,
MembershipID int,
AgentID smallint,
PlanVersionID int,
ForceThroughReference nvarchar (255),
IsForceThrough bit,
NextTermPrePaid bit,
IsBillingMonthly bit,
LastPaymentDate datetime,
PaidToDate datetime,
IsIndeterminate bit
)
INSERT INTO #MembershipTermTable
SELECT MembershipTermID,
MemberStatusProgKey,
StartDate,
EndDate,
AdditionalDiscount,
EntryDateTime,
UpdateDateTime,
MembershipID,
AgentID,
PlanVersionID,
ForceThroughReference,
IsForceThrough,
NextTermPrePaid,
IsBillingMonthly,
LastPaymentDate,
PaidToDate,
IsIndeterminate
FROM MembershipTerm
WHERE MembershipTermID = #MembershipTermID
INSERT INTO MembershipTermAudit(StampUser,StampDateTime,StampAction,MembershipTermID,MemberStatusProgKey,StartDate,EndDate,AdditionalDiscount,EntryDateTime,UpdateDateTime,MembershipID,AgentID,PlanVersionID,ForceThroughReference,IsForceThrough,NextTermPrePaid,IsBillingMonthly,LastPaymentDate,PaidToDate,IsIndeterminate)
VALUES ('SYSTEM',#TodaysDate,'I',MembershipTermID,MemberStatusProgKey,StartDate,EndDate,AdditionalDiscount,EntryDateTime,UpdateDateTime,MembershipID,AgentID,PlanVersionID,ForceThroughReference,IsForceThrough,NextTermPrePaid,IsBillingMonthly,LastPaymentDate,PaidToDate,IsIndeterminate)
--ABOVE NOT FINISHED, NEED TO ADD AUDIT RECORD CORRECTLY
--Members
DECLARE #MembersTable TABLE
(
MembershipTermID int,
MemberStatusProgKey nvarchar (50),
StartDate datetime,
EndDate datetime,
AdditionalDiscount float,
EntryDateTime datetime,
UpdateDateTime datetime,
MembershipID int,
AgentID smallint,
PlanVersionID int,
ForceThroughReference nvarchar (255),
IsForceThrough bit,
NextTermPrePaid bit,
IsBillingMonthly bit,
LastPaymentDate datetime,
PaidToDate datetime,
IsIndeterminate bit
)
INSERT INTO #MembersTable
SELECT * FROM [MembershipTermPerson] WHERE MembershipTermID = #MembershipTermID
--Vehicles
FETCH NEXT FROM cur INTO #MembershipTermID , #EndDate , #MembershipID <VARIABLES>
END
CLOSE cur
DEALLOCATE cur
I think this would be a good case for a INSERT INTO SELECT statement
Something like
INSERT INTO MyTable (ColA, ColB, ColC)
SELECT
GETDATE(), A.MyCol, 'MyValue'
FROM MyOtherTable A
WHERE a.MyValue = 'What I Want'
Basically you skip the temp table, and just grab the value and inject everything at once.