insert foreign key values in store procedure sql server - sql-server

I've created a insert stored procedure with two tables like in the exapmle:
reference table :
create table customerdetails (eid int,
dsgid int Foreign Key Referencesdesg_d(d_id),
ename varchar(90),
dob datetime,addr varchar(100),pincode int,salary,int,dojdatetime)
insert into customerdetails values (1,1,'ahalyaa','05.13.1993','chennai',600024,345,'06.02.2014')
source table:
create table desg_d(d_id int primary key,desg varchar(90))
insert into desg_d values(1,'programmer')
insert into desg_d values(2,'manager')
my store procedure:
create procedure sp_i #iid int,#iname varchar(90),#idobdatetime,
#iaddr varchar(100),#ipincode int, #isalary int,#iDoj datetime
as
begin
declare #idesg int
set #idesg=1
insert into customerdetails(eid,dsgid,ename,dob,addr,pincode,salary,doj)
values(#iid,#idesg,#iname,#idob,#iaddr,#ipincode,#isalary,#iDoj)
end
if i give set=1,then always idesg value should be 1, but i need to insert idesg value randomly, pls help me.

Foreign key values are also the same with the normal insert. The difference is that foreign key values to be inserted should exist on the main table.
Also, please reconsider on naming your variable in your stored procedure. Please see sample below.
create procedure sp_i
#eid int
,#dsgid int
,#ename varchar(90)
,#dob datetime
,#addr varchar(100)
,#pincode int
, #salary int
,#Doj datetime
as
begin
declare #idesg int
insert into customerdetails
(eid,dsgid,ename,dob,addr,pincode,salary,doj)
values
(#eid,#dsgid,#ename,#dob,#addr,#pincode,#salary,#Doj)
end

Use following format in your stored procedure:
DECLARE #DesgId int
INSERT INTO Desg(COLUMN) VALUES(#VALUES)
SET #DesgId = SCOPE_IDENTITY()
INSERT INTO customerdetails ( ..., Dsgid, ...)
VALUES (..., #DesgId, ...)
You can also use following format:
INSERT INTO Desg(COLUMN) VALUES(#VALUES)
INSERT INTO customerdetails ( ..., Dsgid, ...)
VALUES (..., (Select Top(1) d_id from desg_d where desg = #Desg), ...)

Related

Compare two KeyValue types data in SQL Server 2012

I have the below data available in a table
DECLARE #AddressTbl As Table (ID int identity,Address varchar(100))
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
Next time when I enter the same value I should be notified that this value exists in the table.
For this I will use an sp with warning message that the data is available. But I want how to implement the logic to compare the data.
Create Procedure usp_InsertAddress
(
#Address varchar(100)
)
AS
DECLARE #ID INT
SELECT #ID=(SELECT ID FROM #AddressTbl WHERE Address = #Address)
IF #ID IS NULL
BEGIN
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
END;
I may enter the address like 'Dist:Prakasam,State:AndhraPradesh'
and there may be some blank spaces also. So need to parse the address and check the key and values.
I will use permanent table instead of table variable.
Appreciate your help.
You can use if exists for check. Or you can add unique CONSTRAINT in your table. The UNIQUE constraint ensures that all values in a column are different. This will return error if you are trying to insert duplicate value.
Create Procedure usp_InsertAddress
(
#Address varchar(100)
)
AS
if exists(SELECT ID FROM #AddressTbl WHERE Address = #Address)
begin
select 'Value is Already Exist in Table'---For Warning
end
else
BEGIN
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
select 'Value Inserted Sucessful'---For Success
END;

Trigger ON Table which fire INSERT into another table which has NOT NULL constraint , which has float datatype

CREATE TRIGGER studenttr ON tstudentlog
AFTER INSERT
AS
BEGIN
INSERT INTO TABLE tstudent(sname, marks)
SELECT sname,marks FROM INSERTED
END
The structure of tstudent
CREATE TABLE tstudent
(
name VARCHAR(20),
marks FLOAT NOT NULL
)
ALTER TABLE tstudent ADD DEFAULT (0) FOR marks
When I don't pass data in the marks column WHILE INSERTING record into tstudentlog
I get an error:
Cannot insert the value NULL into column 'marks', table 'tstudent'; column does not allow nulls. INSERT fails. The statement has been terminated.
I tried the following but did not work
INSERT INTO TABLE tstudent(sname)
SELECT sname
FROM INSERTED
where marks is null;
I wanted to pass NULL Values tstudent table AND wanted those situdation to be handled by 'DEFAULT VALUES kept in tstudent'
How can I achieve that?
I had a lot of problem with default values in table,
It could go well to use coalesce on insert statement?
CREATE TRIGGER studenttr ON tstudentlog
AFTER INSERT
AS
BEGIN
INSERT INTO TABLE tstudent(sname, marks)
SELECT sname,coalesce(marks,0) FROM INSERTED
END

Why am I getting error 8101 when writing a stored procedure?

I have the table called Sales
CREATE TABLE Sales
(
SaleID int IDENTITY(1,1) PRIMARY KEY
,DateOfTransaction dateTime NOT NULL
,QuantitySold int NOT NULL
,PaymentMethod nvarchar(40) NOT NULL
,EquipmentID int FOREIGN KEY REFERENCES Equipments(EquipmentID)
,CustomerID int FOREIGN KEY REFERENCES Customers(CustomerID)
,SalespersonID int FOREIGN KEY REFERENCES Salespersons(SalespersonID)
);
I am writing a stored procedure in which I want to insert the data. This is my code so far:
CREATE PROCEDURE dbo.sproc_PurchaseAdd
#SaleID INT OUTPUT
,#DateOfTransaction dateTime
,#QuantitySold int
,#PaymentMethod nvarchar(40)
,#EquipmentId int
,#CustomerID int
,#SalesPersonId int
AS
BEGIN
SET IDENTITY_INSERT Sales ON
INSERT INTO Sales
VALUES (#DateOfTransaction, #QuantitySold, #PaymentMethod, #EquipmentId, #CustomerID, #SalesPersonId)
SET #SaleID = ##IDENTITY
END
GO
But I am getting an error:
Msg 8101, Level 16, State 1, Procedure sproc_PurchaseAdd, Line 13 [Batch Start Line 75]
An explicit value for the identity column in table 'Sales' can only be specified when a column list is used and IDENTITY_INSERT is ON.
Is there any specific thing I am missing? Please help me out
SaleID is IDENTITY so it wll auto increment,
you don't need this:
SET IDENTITY_INSERT Sales ON
This is ok:
INSERT INTO Sales VALUES (#DateOfTransaction,#QuantitySold,#PaymentMethod,#EquipmentId,#CustomerID,#SalesPersonId)
If this will not work, try to specify columns:
INSERT INTO Sales (DateOfTransaction,QuantitySold,PaymentMethod,EquipmentID,CustomerID,SalespersonID) VALUES (#DateOfTransaction,#QuantitySold,#PaymentMethod,#EquipmentId,#CustomerID,#SalesPersonId)
Also try to use SCOPE_IDENTITY() instead ##IDENTITY

Create a table and default column value to a received variable parameter

I'm working on a MSSQL stored procedure.
I receive a table valued parameter (#accountPropsTVP) and a single variable (#accountID) from the C# server.
#accountPropsTVP has 2 columns:
valueTypeID int
value varchar(max)
Note: I'm never sure how many rows will be in this table.
#accountID is an int.
I need to merge everything received into one table, so that it ends up looking like so:
#temporaryTable:
#accountID (always the same for all rows)
valueTypeID
value
Below is what I have tried, but I get an error:
Msg 112, Level 15, State 4, Procedure insertAccountProps, Line 20
Variables are not allowed in the CREATE TABLE statement.
CREATE PROCEDURE insertAccountProps
-- Received parameters
#accountID int,
#accountPropsTVP accountPropsTVP READONLY
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
-- declare new table
DECLARE #accountPropsTemp TABLE
(
accountID int not null DEFAULT (#accountID),
valueTypeID int not null,
value varchar(max) not null
)
-- insert received TVP into new temp table, so that we can manipulate it (tvp's are read only :( )
INSERT INTO #accountPropsTemp
SELECT *
FROM #accountPropsTVP
-- select all from TVP and add it into temp table created above
INSERT INTO dbo.accountsProps
SELECT *
FROM #accountPropsTemp
END
GO
Maybe there's a simpler way of doing this?
Your issue is here:
DECLARE #accountPropsTemp TABLE
(
accountID int not null DEFAULT (#accountID),
valueTypeID int not null,
value varchar(max) not null
)
You're assigning a variable as a default value which as the error message clearly states is not allowed.
The best option for this is to change your syntax to:
DECLARE #accountPropsTemp TABLE
(
accountID int not null,
valueTypeID int not null,
value varchar(max) not null
)
INSERT INTO
#accountPropsTemp
SELECT
#AccountID
,ValueTypeID
,Value
FROM
#accountPropsTVP

insert a multiple rows and a common value using stored procedures?

I have custom type (Table type) in sql server 2008.
CREATE TYPE RequestingDatesType AS TABLE
(
LeaveDate datetime,
IsHoliday bit
)
I have a store procedure
CREATE PROCEDURE CreateLeaveRequest
#EmployeeId int,
#LeaveTypeId int,
#LeaveDescription varchar(50)
#TableVariable RequestingDatesType READONLY
AS
DECLARE #LeaveId INT
//1st insert command
INSERT INTO tblLeaveMaster(EmployeeId,LeaveTypeId,LeaveDescription)
VALUES(#EmployeeId,#LeaveTypeId,#LeaveDescription)
SET #LeaveId = SCOPE_IDENTITY()
//2nd insert command
INSERT INTO tblLeaveDetails(LeaveId,LeaveDate,IsHoliday)
VALUES(#LeaveId, LeaveDate(*from custom type*), IsHoliday(*from custom type*))
My question is how can i insert values for 2nd insert command
You must use something like this:
//2nd insert command
INSERT INTO tblLeaveDetails(LeaveId,LeaveDate,IsHoliday)
SELECT #LeaveId, LeaveDate, IsHoliday FROM #TableVariable

Resources