sql case statement then insert into table - sql

i have stored procedure. the code looks like:
use nisa1415;
go
alter procedure dep.AddLessons
(
#LessonsTable nvarchar(50),
#LesDepId int,
#TeId int,
#GradeId varchar(10),
#Activated int,
#GroupId int,
#TaskTable nvarchar(50)
)
as
begin select #LessonsTable=
case #LessonsTable when 'dep.les_Biology' then
insert into dep.les_Biology(LesDepId,TeId,GradeId,Activated,GroupId,TaskTable)
values(#LesDepId,#TeId,#GradeId,#Activated,#GroupId,#TaskTable) end
return
end
it gives me an error:Incorrect syntax near 'insert'
what's the problem that i coudn't find?

ALTER procedure AddLessons
(
#LessonsTable nvarchar(50),
#LesDepId int,
#TeId int,
#GradeId varchar(10),
#Activated int,
#GroupId int,
#TaskTable nvarchar(50)
)
as
begin
if #LessonsTable = 'dep.les_Biology'
begin
insert into dep.les_Biology(LesDepId,TeId,GradeId,Activated,GroupId,TaskTable)
values(#LesDepId,#TeId,#GradeId,#Activated,#GroupId,#TaskTable) end
return
end

Related

How to insert a dynamic sql variable into a temporary table

So I want to insert the variables email, username, and age from a stored procedure into a temporary table and am running into a few issues.
Declare #email [varchar](8000)
,#user_name [varchar](8000)
, age[int]
select distinct value as value
into #temptable
from #email
,#user_name
,#age
select *
from #temptable
I am getting a syntax error. Does anybody have any advice?
Generally, I would use this syntax to insert the results of a stored procedure into a table or table variable:
INSERT #temptable EXECUTE dbo.MyStoredProcedureName
For example (table variable example):
declare #temptable table
(
name varchar(255),
field varchar(255),
filename varchar(255),
filegroup varchar(255),
size varchar(255),
maxsize varchar(255),
growth varchar(255),
usage varchar(255)
);
INSERT #temptable Exec sp_helpfile;
select * from #temptable ;
EDIT: Per your question about why can't you do this in the SP itself, the syntax would be something like:
DECLARE #Email nvarchar(4000),#UserName nvarchar(4000),#age int
declare #temptable table
(
email nvarchar(4000),
UserName nvarchar(4000),
age int
)
SELECT #Email = 'test#test.com', #UserName = 'MyName', #age = 21
INSERT INTO #temptable(Email, UserName, age) SELECT #Email, #UserName, #age
SELECT * FROM #temptable

Unable to insert the records in the tables in SQL server

This is my store procedure, when I am executing it for testing , it says records inserted successfully, but I cannot see any records in the table. Data is inserted into 3 tables- Shipment , Ship_commodity and Commodity_Hazmat. These 3 tables are inter connected.
id from shipment table=shipment id from Ship_commodity
id from Ship_commodity table=commodity id of Commodity_Hazmat table
CREATE PROC [dbo].[usp_InsertBulk]
(
#ShipmentType VARCHAR(10),
#SCACCode VARCHAR(4),
#SCNumber VARCHAR(12),
#CountryLoading VARCHAR(2),
#PortLoading VARCHAR(21),
#ShipperName VARCHAR(60),
#ShipperAddress VARCHAR(100),
#ShipperCity VARCHAR(50),
#ShipmentCountry VARCHAR(2),
#ShipmentProvince VARCHAR(3),
#ShipperZip VARCHAR(15),
#ShipperPhone VARCHAR(20),
#ShipperEmail VARCHAR(100),
#ConsigneeName VARCHAR(60),
#ConsigneeAddress VARCHAR(100),
#ConsigneeCity VARCHAR(50),
#ConsigneeCountry VARCHAR(2),
#ConsigneeState VARCHAR(3),
#ConsigneeZip VARCHAR(15),
#ConsigneePhone VARCHAR(20),
#ConsigneeEmail VARCHAR(100),
#Description VARCHAR(90),
#Quantity INT,
#QuantityUnit VARCHAR(3),
#Weight INT,
#WeightUnitCode VARCHAR(1),
#Countrycode VARCHAR(2),
#Value VARCHAR(8),
#HarmonizedCode VARCHAR(30),
#MarksNumbers VARCHAR(48),
#CmdHMCode1 VARCHAR(10),
#CmdHMName1 VARCHAR(24),
#CmdHMPhone1 VARCHAR(256),
#CmdHMCode2 VARCHAR(10),
#CmdHMName2 VARCHAR(24),
#CmdHMPhone2 VARCHAR(256),
#CmdHMCode3 VARCHAR(10),
#CmdHMName3 VARCHAR(24),
#CmdHMPhone3 VARCHAR(256),
#CustomControl VARCHAR(50),
#DateShipmentLeft VARCHAR(50),
#InbondEntryType VARCHAR(2),
#InbondDestination VARCHAR(5),
#OnwardCarrier VARCHAR(4),
#BondedCarrier VARCHAR(12),
#Inbond VARCHAR(9),
#TransferCarrier VARCHAR(12),
#ForeignPortDestination VARCHAR(12),
#EstimatedDeparture VARCHAR(8),
#MexiPediNumber VARCHAR(12),
#RetVal VARCHAR(1000) OUTPUT
)
AS
BEGIN
DECLARE #CMDId BIGINT
DECLARE #Id BIGINT
DECLARE #ShipmentID BIGINT
BEGIN TRY
BEGIN TRAN;
BEGIN
INSERT INTO
dbo.Shipment
(ShipmentType, scaccode, ShipmentControl, countryLoading, PortLoading, ShipperName,
ShipperAddressOne,
ShipperCity, ShipperCountry, ShipperProvince, ShipperZip, ShipperPhone, ShipperEmail, ConsigneeName,
ConsigneeAddressOne, ConsigneeCity, ConsigneeCountry, ConsigneeState, ConsigneeZip,
ConsigneePhone, ConsigneeEmail, ResponseCode, astrayExportDate, bondType, bondDestPort,
bondOnwardscac, bondCarrierIRS, bondNumber, bondTransferIRS, bondForeignPort, bondDepartureDate,
MexiPediNumber)
VALUES
(#ShipmentType, #SCACCode, #SCNumber, #CountryLoading, #PortLoading, #ShipperName, #ShipperAddress,
#ShipperCity, #ShipmentCountry, #ShipmentProvince, #ShipperZip, #ShipperPhone,
#ShipperEmail, #ConsigneeName, #ConsigneeAddress, #ConsigneeCity, #ConsigneeCountry, #ConsigneeState,
#ConsigneeZip,#ConsigneePhone, #ConsigneeEmail, #CustomControl, #DateShipmentLeft, #InbondEntryType,
#InbondDestination, #OnwardCarrier, #BondedCarrier, #Inbond, #TransferCarrier,
#ForeignPortDestination, #EstimatedDeparture, #MexiPediNumber)
SELECT #Id=##IDENTITY
SET #RetVal = 'true|Record Inserted Successfully|'+CAST(#Id AS VARCHAR)
END
BEGIN
SELECT #ShipmentID=#Id
INSERT INTO dbo.Ship_commodity(ShipmentID,[Description],Quantity,manifestUnitCode,
[weight],weightUnitCode,countryCode,customsShipmentValue,commodityCode,MarksNumbers)
VALUES
(#ShipmentID, #Description, #Quantity, #QuantityUnit, #Weight, #WeightUnitCode, #Countrycode,
#Value,#HarmonizedCode,#MarksNumbers)
SELECT #CMDId=##IDENTITY
SET #RetVal = 'true|Record Inserted Successfully|'+CAST(#CMDId AS VARCHAR)
END
BEGIN
IF(ISNULL(#CmdHMCode1,'')<>'')
INSERT INTO dbo.Commodity_Hazmat(CommodityID,HazmatCode,HazmatContact,HazmatComNum)
VALUES(#CMDId,#CmdHMCode1,#CmdHMName1,#CmdHMPhone1)
IF(ISNULL(#CmdHMCode2,'')<>'')
INSERT INTO dbo.Commodity_Hazmat(CommodityID,HazmatCode,HazmatContact,HazmatComNum)
VALUES(#CMDId,#CmdHMCode2,#CmdHMName2,#CmdHMPhone2)
IF(ISNULL(#CmdHMCode3,'')<>'')
INSERT INTO dbo.Commodity_Hazmat(CommodityID,HazmatCode,HazmatContact,HazmatComNum)
VALUES(#CMDId,#CmdHMCode3,#CmdHMName3,#CmdHMPhone3)
END
COMMIT TRAN;
END TRY
BEGIN CATCH
ROLLBACK TRAN;
SET #RetVal='false|Technical Error-'+ERROR_MESSAGE()+'|'+ ERROR_PROCEDURE() + ' LineNo : ' +
CONVERT(VARCHAR, ERROR_LINE()) +'|'
END CATCH
END
GO
You have a long transaction block that can fail in many different places. I might suggest that you put some auditing directly in the stored procedure.
In particular, you can add a print statement to the catch block to see if there are any other errors that are arising.
I would add a new variable, something like:
declare #auditLevel int = 0;
Then conditionally print to see where there is a problem:
if #auditLevel > 0
begin
print 'Hey, I''m here';
end;

Use an output parameter of store procedure in update Statement

Hi I have a store procedure which insert data into a table1 and there is another store procedure which insert data in table2 I need to insert table2.ID in table1 while updating I am calling second store procedure in first and it returns me the Id as an output parameter but it didn't get updated.
SP1 :
ALTER PROCEDURE [dbo].[updateSP]
#prm1 varchar(30),
#prm2 varchar(20),
#prm3 varchar(20),
#prm3 varchar(max)
AS
BEGIN
SET NOCOUNT OFF;
DECLARE #ID int
exec SPInsert #ID OUTPUT, #prm1, #prm2 , #prm3
update tbl1 set status = prm1, updated_by = prm2, updated_date = GETDATE(), reason_id = #ID where student_no = prm3
END
SP2 :
ALTER PROCEDURE [dbo].[SPInsert]
#prm1 varchar(30),
#prm2 varchar(20),
#prm3 varchar(20),
#prm3 varchar(max),
#ID output,
AS
BEGIN
Insert into tbl2 (student_no, reason_txt, created_by, created_date)Values(#prm1 ,#prm2 ,#prm3 , GETDATE())
Select #ID = Scope_Identity()
END

SQL Server Stored Procedure - Return varchar id of inserted row

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

How to make a function that take user defined table type as parameter and return same in sql?

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)