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
Related
I'm currently learning to work with databases and SQL. I'm getting an error which I can't seem to resolve. The error I'm getting is stated in the title.
This is my table definition:
CREATE TABLE [dbo].[Filmstbl]
(
[Id] INT NOT NULL IDENTITY,
[FilmTitel] NVARCHAR (50) NULL,
[Duratie] NVARCHAR (50) NULL,
[Genre] NVARCHAR (50) NULL,
[Director] NVARCHAR (50) NULL,
[Acteur] NVARCHAR (50) NULL,
[JaarVanUitgave] NVARCHAR (50) NULL,
[Omschrijving] NVARCHAR (MAX) NULL,
[GastID] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
The query im using looks like this:
public void AddFilms(string titel, string lengte, string genre, string director, string acteur, string jaaruitgave, string omschrijving, int PersoonID)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string query = "INSERT INTO Filmstbl Values (#FilmTitel, #Duratie, #Genre, #Director, #Acteur, #JaarVanUitgave, #Omschrijving, #GastID)";
using (SqlCommand addfilms = new SqlCommand(query, connection))
{
addfilms.Parameters.AddWithValue("#FilmTitel", titel);
addfilms.Parameters.AddWithValue("#Duratie", lengte);
addfilms.Parameters.AddWithValue("#Genre", genre);
addfilms.Parameters.AddWithValue("#Director", director);
addfilms.Parameters.AddWithValue("#Acteur", acteur);
addfilms.Parameters.AddWithValue("#JaarVanUitgave", jaaruitgave);
addfilms.Parameters.AddWithValue("#Omschrijving", omschrijving);
addfilms.Parameters.AddWithValue("#GastID", PersoonID);
addfilms.ExecuteNonQuery();
}
}
}
The datatypes are pretty much always a random string, except the last parameter which is a random int.
private void FilmToevoegenBtn_Click(object sender, EventArgs e)
{
sql.AddFilms(FilmTitelTBox.Text, FilmLengteTBox.Text, FilmGenreTBox.Text, FilmDirectorTBox.Text, FilmActeurTBox.Text, FilmJaarUitgaveTBox.Text, FilmOmschrijvingTBox.Text, gebruiker.GebruikerID);
UpdateListBoxes();
}
I'm adding data to another table the same way without a problem, so i'm wondering why it doesn't work with this one. I hope someone knows the answer. Thank you.
Please re-check table ID field.It should be auto increment with 1. e.g.:
[Id] [int] IDENTITY(1,1)
I am working with C# and I want to insert some values to my SQL Server database, here is my data base definition:
CREATE TABLE [dbo].[Users]
(
[Id] INT NOT NULL IDENTITY (1,1) PRIMARY KEY DEFAULT 1000,
[FullName] VARCHAR(50) NULL,
[Pseudo] VARCHAR(50) NULL,
[Mail] VARCHAR(50) NULL,
[Password] VARCHAR(50) NULL,
[Organism] VARCHAR(50) NULL,
[RegistredAt] DATETIME NULL,
[Confirmed] INT NULL
)
and this how I am trying to insert the values to the database using C#:
SqlCommand command = new SqlCommand("INSERT INTO Users VALUES(#FullName, #Pseudo, #Mail, #Password, #Organism, #RegistredAt, #Confirmed)", con);
command.Parameters.AddWithValue("#FullName", FullName);
command.Parameters.AddWithValue("#Pseudo", Pseudo);
command.Parameters.AddWithValue("#Mail", Mail);
command.Parameters.AddWithValue("#Password", Password);
command.Parameters.AddWithValue("#Organism", Organism);
command.Parameters.AddWithValue("#RegistredAt", DateTime.Now);
command.Parameters.AddWithValue("#Confirmed", Confirmed);
con.Open();
int i = command.ExecuteNonQuery();
con.Close();
When I execute the code, the instruction command.ExecuteNonQuery(); returns an exception:
Column name or number of supplied values does not match table definition
Where is the error?
You might need to supply the column names in your query:
INSERT INTO Users (FullName, Pseudo, Mail, Password, Organism, RegistredAt, Confirmed)
VALUES (#FullName, #Pseudo, #Mail, #Password, #Organism, #RegistredAt, #Confirmed)
If you don't supply the column names, it assumes you want to use all columns, including the ID field. That's the reason for the error -- you're supplying 7 values for a table with 8 columns. Since you are using a subset, you need to specify them.
Also, I'm not sure if you are at a stage where it can be fixed, but you have a typo in "RegistredAt" -- it should be "RegisteredAt".
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();
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
........