Hy,
I have created the following 3 tables for a database:
CREATE TABLE [dbo].[Buyer] (
[Buyer_Id] INT IDENTITY (1, 1) NOT NULL,
[Last_Name] NVARCHAR (50) NOT NULL,
[First_Name] NVARCHAR (50) NOT NULL,
[Social_No] NVARCHAR (50) NOT NULL,
[Phone] NVARCHAR (50) NOT NULL,
[User_Id] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Buyer_Id] ASC),
CONSTRAINT [FK_User_Id] FOREIGN KEY ([User_Id]) REFERENCES [dbo].[User] ([User_Id])
);
CREATE TABLE [dbo].[Type] (
[Type_Id] INT IDENTITY (1, 1) NOT NULL,
[Type_Name] NCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([Type_Id] ASC)
);
CREATE TABLE [dbo].[User] (
[User_Id] INT IDENTITY (1, 1) NOT NULL,
[User_Name] NCHAR (10) NOT NULL,
[Pass] NVARCHAR (50) NOT NULL,
[Type_Id] INT NOT NULL,
PRIMARY KEY CLUSTERED ([User_Id] ASC),
CONSTRAINT [FK__Type_Id] FOREIGN KEY ([Type_Id]) REFERENCES [dbo].[Type] ([Type_Id])
);
and I have the following stored procedure
CREATE PROCEDURE [dbo].[InsertCustomer]
#Buyer_Id int output,
#Last_Name varchar(50),
#First_Name varchar(50),
#Social_No varchar(50),
#Phone varchar(50),
#User_Id int output,
#User_Name nchar(10),
#Pass varchar(50),
#Type_id int output,
#Type_Name nchar(10)
AS
BEGIN
SET NOCOUNT ON;
insert into Buyer(Last_Name,First_Name,Social_No,Phone)
values (#Last_Name,#First_Name,#Social_No,#Phone)
set #Buyer_Id = SCOPE_IDENTITY();
insert into [User](User_Name,Pass)
values(#User_Name,#Pass)
set #User_Id = SCOPE_IDENTITY();
insert into [Type](Type_Name)
values (#Type_Name)
set #Type_id = SCOPE_IDENTITY();
RETURN 0
END
and the C# code:
SqlCommand cmd = new SqlCommand("InsertCustomer", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramLastName = new SqlParameter("#Last_Name", customer.Last_Name);
SqlParameter paramFirstName = new SqlParameter("#First_Name", customer.First_Name);
SqlParameter paramSocialNo = new SqlParameter("#Social_No", customer.Social_No);
SqlParameter paramPhone = new SqlParameter("#Phone", customer.Phone_No);
SqlParameter paramUserName = new SqlParameter("User_name", user.User_Name);
SqlParameter paramPass = new SqlParameter("#Pass", user.Pass);
SqlParameter paramTypeName = new SqlParameter("#Type_Name", type.Type_Name);
SqlParameter paramBuyerId = new SqlParameter("#Buyer_Id", SqlDbType.Int);
paramBuyerId.Direction = ParameterDirection.Output;
SqlParameter paramUserId = new SqlParameter("#User_Id", SqlDbType.Int);
paramUserId.Direction = ParameterDirection.Output;
SqlParameter paramTypeId = new SqlParameter("#Type_Id", SqlDbType.Int);
paramTypeId.Direction = ParameterDirection.Output;
cmd.Parameters.Add(paramLastName);
cmd.Parameters.Add(paramFirstName);
cmd.Parameters.Add(paramSocialNo);
cmd.Parameters.Add(paramPhone);
cmd.Parameters.Add(paramUserName);
cmd.Parameters.Add(paramPass);
cmd.Parameters.Add(paramTypeName);
cmd.Parameters.Add(paramBuyerId);
cmd.Parameters.Add(paramUserId);
cmd.Parameters.Add(paramTypeId);
conn.Open();
cmd.ExecuteNonQuery();
customer.Buyer_Id = (int)paramBuyerId.Value;
type.Type_Id = (int)paramTypeId.Value;
user.User_Id = (int)paramUserId.Value;
But after I insert data into the form that uses the above code I am getting the following error:
Cannot insert the value NULL into column 'User_Id' ....
PLATFORM.MDF.dbo.Buyer'; column does not allow nulls. INSERT fails.
Cannot insert the value NULL into column 'Type_Id', table ...
PLATFORM.MDF.dbo.User'; column does not allow nulls. INSERT fails.
Please help me,
Sincerely,
You should change insert order. First of all you should insert new type
insert into [Type](Type_Name)
values (#Type_Name)
set #Type_id = SCOPE_IDENTITY();
After that you should insert new user (use #type_id for that)
insert into [User](User_Name,Pass,Type_id)
values(#User_Name,#Pass,#Type_id)
set #User_Id = SCOPE_IDENTITY();
Filnaly, use #User_Id to insert Buyer. In turn use #User_Id
insert into Buyer(Last_Name,First_Name,Social_No,Phone,User_id)
values (#Last_Name,#First_Name,#Social_No,#Phone,#User_Id)
set #Buyer_Id = SCOPE_IDENTITY();
You have errors in your stored procedure, since you are not specifying values for the User_Id or Type_Id columns but those columns don't allow null values.
You should reverse the order of the inserts and use the generated identity values in the following ones, like so:
insert into [Type](Type_Name)
values (#Type_Name)
set #Type_id = SCOPE_IDENTITY();
insert into [User](User_Name,Pass,TypeId)
values(#User_Name,#Pass,#Type_id)
set #User_Id = SCOPE_IDENTITY();
insert into Buyer(Last_Name,First_Name,Social_No,Phone,User_Id)
values (#Last_Name,#First_Name,#Social_No,#Phone,#User_Id)
set #Buyer_Id = SCOPE_IDENTITY();
Related
I am trying to insert values through stored procedure, however everything seems to run successfully but the data is not inserted into the database.
Here is the Table setup:
CREATE TABLE [dbo].[Owner]
(
[ClientID] INT IDENTITY (101, 1) NOT NULL,
[Title] NCHAR (10) NULL,
[Forename] NVARCHAR (50) NULL,
[Surname] NVARCHAR (50) NULL,
[Address1] NVARCHAR (50) NULL,
[EmailAddress] NVARCHAR (50) NULL,
[TelephoneNo] NVARCHAR (50) NULL,
[DateOfBirth] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([ClientID] ASC)
)
Here is the stored procedure:
CREATE PROCEDURE [dbo].AddOwner
#Title nvarchar(50),
#Forename nvarchar(50),
#Surname nvarchar(50),
#Address1 nvarchar(50),
#EmailAddress nvarchar(50),
#TelephoneNo nvarchar(50),
#DateOfBirth nvarchar(50)
AS
INSERT INTO Owner(Title, Forename, Surname, Address1, EmailAddress, TelephoneNo, DateOfBirth)
VALUES (#Title, #Forename, #Surname, #Address1, #EmailAddress, #TelephoneNo, #DateOfBirth)
RETURN 0
Here is the ProjectDal:
public static int AddOwner(string Title, string Forename, string Surname,string EmailAddress, string TelephoneNo, string DateOfBirth, string Address1)
{
using (SqlConnection connection = new SqlConnection(_connectionstring))
{
connection.Open();
SqlCommand insertClientCommand = new SqlCommand();
insertClientCommand.Connection = connection;
insertClientCommand.CommandType = System.Data.CommandType.StoredProcedure;
insertClientCommand.CommandText = "AddOwner";
insertClientCommand.Parameters.Add(new SqlParameter("#Title", Title));
insertClientCommand.Parameters.Add(new SqlParameter("#Forename", Forename));
insertClientCommand.Parameters.Add(new SqlParameter("#Surname", Surname));
insertClientCommand.Parameters.Add(new SqlParameter("#Address1", Address1));
insertClientCommand.Parameters.Add(new SqlParameter("#EmailAddress", EmailAddress));
insertClientCommand.Parameters.Add(new SqlParameter("#TelephoneNo", TelephoneNo));
insertClientCommand.Parameters.Add(new SqlParameter("#DateOfBirth", DateOfBirth));
// insertClientCommand.Parameters.Add(new SqlParameter("#Address2", Address2));
// insertClientCommand.Parameters.Add(new SqlParameter("#PostCode", PostCode));
int rowsAffected = insertClientCommand.ExecuteNonQuery();
connection.Close();
return rowsAffected;
}
}
Help would be greatly appreciated. Thank you
There are several things to check:
If the right database specified in the _connection string
If no truncation happens on column Title: you have the field length of 10 characters in the table, yet 50 characters in SP
What RowsAffected do you get
You should check that the property you are passing in the right format, Everything is supposed to be strings.
Also since you are using the "Using" statement, you don't need to open connection and close it again. That's redundant.
Just run your query
Creating shop application and having two main tables Product and Customer. The aim is to create an Order table where customer can choose from the productgetall list and add it to Order table.
Customer Table
CREATE TABLE [dbo].[Customer]
(
[CustomerId] INT IDENTITY (1, 1) NOT NULL,
[FirstName] NVARCHAR(40) NOT NULL,
[LastName] NVARCHAR(20) NOT NULL,
[Email] NVARCHAR(60) NOT NULL,
[Photo] VARBINARY(MAX) NULL,
[password] VARCHAR(300) NULL,
[Country] VARCHAR(50) NULL,
CONSTRAINT [PK_Customer]
PRIMARY KEY CLUSTERED ([CustomerId] ASC)
);
Product table:
CREATE TABLE [dbo].[Product]
(
[ProductId] INT IDENTITY (1, 1) NOT NULL,
[ProductName] NVARCHAR(50) NOT NULL,
[ProductDetails] TEXT NULL,
[ProductPrice] INT NOT NULL,
[ProductCategory] NVARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([ProductId] ASC)
);
Order table
CREATE TABLE [dbo].[Order]
(
[OrderId] INT IDENTITY (1, 1) NOT NULL,
[CustomerId] INT NOT NULL,
[ProductId] INT NOT NULL,
[Date] DATE NULL,
[Time] TIME(7) NULL,
CONSTRAINT [ORDER_PK]
PRIMARY KEY CLUSTERED ([OrderId] ASC),
CONSTRAINT [CUSTOMER_FK]
FOREIGN KEY ([CustomerId])
REFERENCES [dbo].[Customer] ([CustomerId])
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT [PRODUCT_FK]
FOREIGN KEY ([ProductId])
REFERENCES [dbo].[Product] ([ProductId])
ON DELETE CASCADE ON UPDATE CASCADE
);
C# code to add order
public void AddOrder(Order a)
{
using (DbConnection conn = new SqlConnection(ConnStr))
{
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandTimeout = 120;
cmd.CommandText = #"INSERT INTO [dbo].[Order] (CustomerId, ProductId, Date, Time)
VALUES (#CustomerId, #ProductId, #Date, #Time)";
cmd.AddParameter("#CustomerId", a.CustomerId, DbType.Int32);
cmd.AddParameter("#ProductId", a.ProductId, DbType.Int32);
cmd.AddParameter("#Date", a.Date, DbType.Date);
cmd.AddParameter("#Time", a.Time.ToString(), DbType.String);
conn.Open();
cmd.ExecuteScalar();
}
}
}
While creating through web forms it showing error on ExecuteScalar:
System.Data.SqlClient.SqlException: 'The INSERT statement conflicted with the FOREIGN KEY constraint "CUSTOMER_FK". The conflict occurred in database "C:\USERS\USER\DESKTOP\2019 5LVL\DBSD\TRYWISHLIST\3\00005466\00005466\APP_DATA\KFCDB.MDF", table "dbo.Customer", column 'CustomerId'. The statement has been terminated
The CustomerId you're sending does not exist in dbo.Customer, insert it.
I need a little help with this. The stored procedure below doesn't seem to ever match exiting unique identifier
ALTER PROCEDURE [dbo].[spInsertUpdateThisStuff]
#Id uniqueidentifier OUTPUT,
#Content nvarchar(255)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #tAudit table (id uniqueidentifier)
IF EXISTS(SELECT * FROM [dbo].[myData] WHERE [ID] = #Id)
-- UPDATE
BEGIN
UPDATE [dbo].[myData]
SET [ID] = #ID,
[Content] = #Content
OUTPUT inserted.[ID] INTO #tAudit
WHERE [ID] = #Id
SELECT id FROM #tAudit
END
ELSE
BEGIN
-- INSERT
SET #ID = NEWID()
INSERT INTO [dbo].CBData ([ID], [Content])
OUTPUT inserted.[ID] INTO #tAudit
VALUES(#Id, #Content)
SELECT id FROM #tAudit
END;
SET #ID = (SELECT id FROM #tAudit);
END
the C#
cmd.Parameters.Add("#ID", SqlDbType.UniqueIdentifier).Value = (currentRecord.ID == null) ? Guid.Empty : currentRecord.ID;
cmd.Parameters["#ID"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
currentRecord.ID = Guid.Parse(cmd.Parameters["#ID"].Value.ToString());
It seems the first IF statement does not ever become true, but if test (SELECT * FROM [dbo].[myData] WHERE [ID] = #Id) with a the matching UID it comes back with data.
This statement is problematic,,
DECLARE #tAudit table (id uniqueidentifier)
IF EXISTS(SELECT * FROM [dbo].[myData] WHERE [ID] = #Id)
-- UPDATE
BEGIN
#id is an Output Parameter and is null by default and you are trying to check that..
basically NEWID() won't be duplicated,so update part is redundant
How are you declaring the parameter in your code? Is it ParameterDirection.Output?
Try changing it to ParameterDirection.InputOutput. Your SQL looks okay. And you can pass an input value to a parameter declared as OUTPUT in your stored procedure. So maybe it's just that ParameterDirection.
You can also change this
IF EXISTS(SELECT * FROM [dbo].[myData] WHERE [ID] = #Id)
to
IF #Id IS NOT NULL AND EXISTS(SELECT * FROM [dbo].[myData] WHERE [ID] = #Id)
If your ID column isn't nullable then it's going to work the same either way. But this is a little more explicit, showing that it's recognized that #Id might be null because it's an OUTPUT parameter.
This is my fix.
This is my new stored procedure
ALTER PROCEDURE [dbo].[spInsertUpdatemyData]
#ID uniqueidentifier,
#IDOut uniqueidentifier OUTPUT,
#CONTENT nvarchar(255)
AS
BEGIN
--SET NOCOUNT ON;
DECLARE #tAudit table (outputID uniqueidentifier)
IF EXISTS(SELECT * FROM [dbo].[myData] WHERE [ID] = #ID)
-- UPDATE
BEGIN
UPDATE [dbo].[CBData]
SET [ID] = #ID,
[Content] = #Content
OUTPUT inserted.[ID] INTO #tAudit
WHERE [ID] = #ID
SELECT outputID FROM #tAudit;
END
ELSE
BEGIN
-- INSERT
INSERT INTO [dbo].myData
([ID],[Content])
OUTPUT inserted.[ID] INTO #tAudit
VALUES(NEWID(),#Content);
SELECT outputID FROM #tAudit
END;
set #IDOut = (SELECT outputID FROM #tAudit);
END
and the relative C#
//Add Parameter for output to sql command then Change Direction of parameter
cmd.Parameters.Add("#IDOut", SqlDbType.UniqueIdentifier).Value = Guid.Empty ;
cmd.Parameters["#IDOut"].Direction = ParameterDirection.InputOutput;
cmd.ExecuteNonQuery();
currentRecord.ID = Guid.Parse(cmd.Parameters["#IDOut"].Value.ToString());
cmd.Transaction.Commit();
I have a table that accepts a bunch of parameters and saves it as a new contact through a stored procedure using an INSERT INTO statement. For some reason I get a SqlException when some of my parameters are left null. All of the parameters left null are indeed nullable in the SQL Server table, so I don't understand the issue. My thoughts are that my INSERT statement is accepting all the parameters even if they are null and trying to insert them into my table, which I believe is a syntactical "no-no"
Anyway, here is the C# code:
try
{
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Insert_NewContact", sqlConn))
{
sqlConn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CompanyID", CompanyID);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#fax", fax);
cmd.Parameters.AddWithValue("#fName", fName);
cmd.Parameters.AddWithValue("#lName", lName);
cmd.Parameters.AddWithValue("#sendVia", sendVia);
cmd.Parameters.AddWithValue("#default", defaultContact);
cmd.Parameters.AddWithValue("#repo", repo);
cmd.Parameters.AddWithValue("#fail", fail);
cmd.Parameters.AddWithValue("#borrow", borrow);
cmd.Parameters.AddWithValue("#loan", loan);
cmd.ExecuteNonQuery();
sqlConn.Close();
}
}
}
catch (Exception e)
{
throw e;
}
and here is the stored procedure in SQL:
ALTER PROCEDURE [dbo].[Insert_NewContact]
#CompanyID INT,
#email VARCHAR(50),
#phone VARCHAR(50),
#fax VARCHAR(50),
#fName VARCHAR(50),
#lName VARCHAR(50),
#sendVia VARCHAR(50),
#default BIT,
#repo TINYINT,
#fail TINYINT,
#borrow TINYINT,
#loan TINYINT
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
INSERT INTO Master_Contacts(
companyID,
fName,
lName,
phone,
email,
fax,
send_via,
defaultcontact,
repoRole,
borrowRole,
failRole,
loanRole
)
VALUES (
#CompanyID,
#fName,
#lName,
#phone,
#email,
#fax,
#sendVia,
#default,
#repo,
#borrow,
#fail,
#loan
)
END TRY
Not sure why the AS BEGIN and NOCOUNT are so weird, but they are correct in the Stored Proc.
Anyway, if I leave the email, phone, fax, etc. empty in my application, I get this error:
SqlException was unhandled by user code
Procedure or function 'Insert_NewContact' expects parameter '#email', which was not supplied.
How can I edit my stored proc to make it work with null values?
Set the default value for the parameter as null, try this:
#CompanyID INT,
#email VARCHAR(50) = null,
#phone VARCHAR(50) = null,
#fax VARCHAR(50) = null,
#fName VARCHAR(50) = null,
#lName VARCHAR(50),
#sendVia VARCHAR(50),
#default BIT,
#repo TINYINT,
#fail TINYINT,
#borrow TINYINT,
#loan TINYINT
You should pass DBNull.Value when you have a null value. For example.
cmd.Parameters.AddWithValue("#email", email == null ? DBNull.Value : (object)email);
ALTER PROCEDURE [dbo].[Insert_NewContact]
#CompanyID INT,
#email VARCHAR(50) = null,
#phone VARCHAR(50) = null,
#fax VARCHAR(50) = null,
#fName VARCHAR(50) = null,
#lName VARCHAR(50) = null,
#sendVia VARCHAR(50) = null,
#default BIT = 0,
#repo TINYINT = 0,
#fail TINYINT = 0,
#borrow TINYINT = 0,
#loan TINYINT = 0
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
INSERT INTO Master_Contacts(
companyID,
fName,
lName,
phone,
email,
fax,
send_via,
defaultcontact,
repoRole,
borrowRole,
failRole,
loanRole
)
VALUES (
#CompanyID,
#fName,
#lName,
#phone,
#email,
#fax,
#sendVia,
#default,
#repo,
#borrow,
#fail,
#loan
)
END TRY
I am trying to write procedure for insert value into table but the value not inserted in table
for reference I am give code which i had try for it...can anyone please help me
for insert i am try this code
public int Visitor_Insert(visitor_Master visitor_obj, common_Class comm_obj)
{
DB_Connection();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT_VISITOR";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#VISITOR_NAME", visitor_obj.VisitorName);
cmd.Parameters.AddWithValue("#VISITOR_CONTACT", visitor_obj.VisitorContact);
cmd.Parameters.AddWithValue("#VISITOR_ADDRESS", visitor_obj.VisitorAddress);
cmd.Parameters.AddWithValue("#VISITOR_AGE", visitor_obj.VisitorAge);
cmd.Parameters.AddWithValue("#VISITOR_VEHICLENO", visitor_obj.VisitorVehicleNO);
//cmd.Parameters.AddWithValue("#VISITOR_AGE ", visitor_obj.VisitorAge);
int i = cmd.ExecuteNonQuery();
return i;
}
For Procedure I am written this code
USE [VPMS]
GO
/****** Object: StoredProcedure [dbo].[INSERT_VISITOR] Script Date: 07/24/2013 16:01:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[INSERT_VISITOR]
#VISITOR_NAME NVARCHAR(30),
#VISITOR_CONTACT NVARCHAR(10),
#VISITOR_ADDRESS NVARCHAR(40),
#VISITOR_AGE NVARCHAR(2),
#VISITOR_VEHICLENO NVARCHAR(20),
#VISITOR_IMAGE IMAGE,
#VISITOR_CREATEDBY NVARCHAR(20),
#VISITOR_CREDTEDON NVARCHAR(20),
#VISITOR_MODIFIEDBY NVARCHAR(20),
#VISITOR_MODIFIEDON NVARCHAR(20)
AS
DECLARE #VISITOR_ID INT,
BEGIN
SET NOCOUNT ON;
SELECT #VISITOR_ID= MAX(Visitor_Id) FROM Visitor_Master
IF (#VISITOR_ID > 0 )
BEGIN
SET #VISITOR_ID=#VISITOR_ID+1
END
ELSE
BEGIN
SET #VISITOR_ID=10
END
INSERT INTO Visitor_Master( Visitor_Id, VisitorName, Visitor_Contact, Visitor_Address, Visitor_age,
Visitor_VehicleNo, Visitor_Image, Created_By, Created_On, Modify_By, Modify_On)
VALUES(#VISITOR_ID,#VISITOR_NAME,#VISITOR_CONTACT,#VISITOR_ADDRESS,#VISITOR_AGE,#VISITOR_VEHICLENO,#VISITOR_IMAGE,#VISITOR_CREATEDBY,
#VISITOR_CREDTEDON,#VISITOR_MODIFIEDBY,#VISITOR_MODIFIEDON)
END
As you are not passing all the parameters defined in the procedure. It will throw exception.
Here I have assigned null to other parameters which you have not specified assign value as per your reqirement
ALTER PROCEDURE [dbo].[INSERT_VISITOR]
#VISITOR_NAME NVARCHAR(30),
#VISITOR_CONTACT NVARCHAR(10),
#VISITOR_ADDRESS NVARCHAR(40),
#VISITOR_AGE NVARCHAR(2),
#VISITOR_VEHICLENO NVARCHAR(20),
#VISITOR_IMAGE IMAGE = null,
#VISITOR_CREATEDBY NVARCHAR(20) = null,
#VISITOR_CREDTEDON NVARCHAR(20) = null,
#VISITOR_MODIFIEDBY NVARCHAR(20) = null,
#VISITOR_MODIFIEDON NVARCHAR(20) = null
-- rest of code
You have #VISITOR_IMAGE,#VISITOR_CREATEDBY,#VISITOR_CREDTEDON,#VISITOR_MODIFIEDBY,#VISITOR_MODIFIEDON parameters in your procedure but you have not passed value to the the above parameter.Either pass value to all the parameters or allow null
BEGIN
set #VISITOR_IMAGE = null,
set #VISITOR_CREATEDBY = null,
set #VISITOR_CREDTEDON = null,
set #VISITOR_MODIFIEDBY = null,
set #VISITOR_MODIFIEDON = null
........