I need to create a temporary table and populate it with temporary values. The variables have values assigned from a python script. My code is as follows:
ALTER PROCEDURE [dbo].[AddScrapedInfoBULK]
(
-- Parameters for the SP, (each field in the all tables)
-- ProjectInfo Fields
#ProjectInfoID AS INT,
#OrderNumber AS NVARCHAR(255),
#PeriodofPerformance AS NVARCHAR(255),
#POPEndDate AS DATETIME,
#PopStartDate AS DATETIME
AS
BEGIN
SET NOCOUNT ON;
DECLARE #temproj TABLE (ProjectInfoID INT,
OrderNumber NVARCHAR(255),
PeriodofPerformance NVARCHAR(255),
POPEndDate DATETIME,
PopStartDate DATETIME)
INSERT INTO #temproj
SELECT (#ProjectInfoID,
#OrderNumber,
#PeriodofPerformance,
#POPEndDate,
#PopStartDate)
END
but this does not work. How can I populate a temporary table with variables?
You can just use insert into .... values to make it.
INSERT INTO #temproj
(projectinfoid,
ordernumber,
periodofperformance,
popenddate,
popstartdate)
VALUES (#ProjectInfoID,
#OrderNumber,
#PeriodofPerformance,
#POPEndDate,
#PopStartDate)
Remove the parentheses around the select.
DECLARE #ProjectInfoID AS INT,
#OrderNumber AS NVARCHAR(255),
#PeriodofPerformance AS NVARCHAR(255),
#POPEndDate AS DATETIME,
#PopStartDate AS DATETIME
SET NOCOUNT ON;
DECLARE #temproj TABLE (ProjectInfoID INT,
OrderNumber NVARCHAR(255),
PeriodofPerformance NVARCHAR(255),
POPEndDate DATETIME,
PopStartDate DATETIME)
INSERT INTO #temproj
SELECT #ProjectInfoID,
#OrderNumber,
#PeriodofPerformance,
#POPEndDate,
#PopStartDate
Related
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
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)
I have a dynamic stored procedure that I run in Access 2013 by passing various parameters to it.
However, I need to now run the dynamic stored procedure in another Stored Procedure.
Currently I know how to Execute a standard stored procedure.
This is my dynamic stored procedure Execute that I use in another SP Called SP_ACTIVITY:
EXEC sp_executesql #sql, N'#ORGCODE VARCHAR(6), #COMPANYID VARCHAR(6)'
#ORGCODE, #COMPANYID;
Here is my code so far:
CREATE PROCEDURE [dbo].[ASP_SLACTIVITYPAGE]
#ORGCODE2 AS VARCHAR(6),
#COMPANYID2 AS VARCHAR(6)
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT 1 FROM tempdb..sysobjects
WHERE NAME = '#TempACTIVITY' and TYPE = 'U')
DROP TABLE #TempACTIVITY
CREATE TABLE #tempACTIVITY
(
CompanyID VARCHAR(6),
CompanyName VARCHAR(50),
PostingID INT,
EntryDate SmallDateTime,
TransType VARCHAR(2),
Ref VARCHAR(50),
Nominal INT,
Details VARCHAR(50),
SumofNetAmt DECIMAL(12,2),
SumofVATAmt DECIMAL(12,2),
SumofPaidAmt DECIMAL(12,2),
CustomerOrderNr VARCHAR(25),
WONUmber INT,
PaidStatus VARCHAR(2),
Credit DECIMAL(12,2),
Debit DECIMAL(12,2),
OutStanding DECIMAL(12,2)
);
GO
INSERT INTO #tempACTIVITY
(
CompanyID,
CompanyName,
PostingID,
EntryDate,
TransType,
Ref,
Nominal,
Details,
SumofNetAmt,
SumofVATAmt,
SumofPaidAmt,
CustomerOrderNr,
WONUmber,
PaidStatus,
Credit,
Debit,
OutStanding
)
EXEC sp_executesql SP_ACTVIITY, #ORGCODE2, #COMPANYID2 <----
---I want to execute with dynamic SP with parameters like the the one above.
I was quoting the Stored Procedure incorrectly.
The answer is:
EXEC [PROCNAME] #Param1, #Param2
I'm working on a cascading insertion where a stored procedure should return an id of the inserted row. This would not be a problem if the id of the table was an int. However, the id is a varchar and therefore I cannot use SCOPE_IDENTITY().
This is my procedure so far:
CREATE PROCEDURE NEW_ARTICLE
#id varchar(50) OUTPUT,
#name varchar(100),
#articleNr varchar(50),
#gategory varchar(50),
#containerId varchar(50),
#contPerContainer int,
#pictureId varchar(50)
AS
SET NOCOUNT OFF
INSERT INTO nextlabel.[Article] (name, article_nr, category, container_id, count_per_container, picture_id )
VALUES (#name, #articleNr, #gategory, #containerId, #contPerContainer, #pictureId)
SET #id = SCOPE_IDENTITY()
Where the last row is not correct since the column id is a varchar.
How can I return the id?
Try this:
CREATE PROCEDURE NEW_ARTICLE
#id varchar(50) OUTPUT,
#name varchar(100),
#articleNr varchar(50),
#gategory varchar(50),
#containerId varchar(50),
#contPerContainer int,
#pictureId varchar(50)
AS
SET NOCOUNT OFF
SET #id = newid()
INSERT INTO nextlabel.[Article] (id, name, article_nr, category, container_id, count_per_container, picture_id)
VALUES (#id, #name, #articleNr, #gategory, #containerId, #contPerContainer, #pictureId)
GO
Actually I have created a User defined table type in sql server 2008. Structure is given below.
I am passing it as parameter in function and that function also return that type of table type. I am facing the problem, while I declare a variable of that type in function, inserting some data in it and return that parameter.
Table type structure is:
Create Type OfferWithSubscription as Table
(
OfferID int,
OfferUserID int,
OfferImage varchar(200),
OfferExactPrice Decimal(18,2),
OfferContent varchar(max),
OfferTitle varchar(100),
StartDate datetime,
EndDate datetime,
StartTime datetime,
StopTime datetime,
ShowToUser bit,
SubID int,
SubLevel varchar(100)
)
And the function, what I am trying to create is:
CREATE FUNCTION FN_ShowOffer
(
#Gold int,
#Silver int,
#Bronze int,
#table dbo.OfferWithSubscription Readonly )
RETURNS dbo.OfferWithSubscription
AS
BEGIN
DECLARE #ReturnTable AS dbo.OfferWithSubscription;
Declare #Case as varchar(20)
if(#Gold=0 and #Silver=1 and #Bronze=0 )
begin
set #Case='1S'
end
if(#Case='1S')
Begin
insert into #ReturnTable
select OfferID, OfferUserID, OfferImage,
OfferExactPrice, OfferContent,
OfferTitle, StartDate, EndDate,
StartTime, StopTime, ShowToUser,
SubID, SubLevel
from #table
where SubID=4
End
RETURN (
#ReturnTable
)
END
You'll just have to expand the type like below.
FYI - Can T-SQL function return user-defined table type?
CREATE FUNCTION FN_ShowOffer
(
#Gold int,
#Silver int,
#Bronze int,
#table dbo.OfferWithSubscription Readonly )
RETURNS #ReturnTable Table
(
OfferID int,
OfferUserID int,
OfferImage varchar(200),
OfferExactPrice Decimal(18,2),
OfferContent varchar(max),
OfferTitle varchar(100),
StartDate datetime,
EndDate datetime,
StartTime datetime,
StopTime datetime,
ShowToUser bit,
SubID int,
SubLevel varchar(100)
)
AS
BEGIN
Declare #Case as varchar(20)
if(#Gold=0 and #Silver=1 and #Bronze=0 )
begin
set #Case='1S'
end
if(#Case='1S')
Begin
insert into #ReturnTable
select OfferID,OfferUserID,OfferImage,OfferExactPrice,OfferContent,OfferTitle,
StartDate,EndDate,StartTime,StopTime,ShowToUser,SubID,SubLevel from #table where SubID=4
End
RETURN
END
And to further clarify, that's fully compatible and assignable to a variable of that table type, e.g. SQL Fiddle
declare #t OfferWithSubscription
insert #t
select * from fn_showoffer(1,2,3,#t)