I have a table SupplierMaster in a SQL Server database with a column SUPPLIERNAME.
I want to edit saved supplier name using stored procedure with below query
ALTER PROCEDURE [dbo].[usp_SupplierMasterUpdateDetails]
(
#SUPPLIERNAME NVARCHAR(50)
)
AS
BEGIN
UPDATE [dbo].[SupplierMaster]
SET [SUPPLIERNAME] = #SUPPLIERNAME
WHERE [SUPPLIERNAME] = #SUPPLIERNAME
END
and I run the BELOW code through "UPDATE BUTTON" to update the data.
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("usp_SupplierMasterUpdateDetails", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// Parameter
cmd.Parameters.AddWithValue("SUPPLIERNAME", AddSupplierTextBox.Text);
// Open Connection
conn.Open();
// ExecuteReader (Select Statement)
// ExecuteScalar (Select Statement)
// ExecuteNonQuery (Insert, Update or Delete)
cmd.ExecuteNonQuery();
MessageBox.Show("SUCCESSFULLY UPDATED", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
But its not updating the selected data.
Please advice and assist me to correct the code for proper work.
You have multiple issues there.
First you need to fix your update query just as Thomas Levesque suggested.
a SQL Server table needs a primary key to be able to uniquely identify a record, for updates for example.
The easiest thing you could do is set that primary key to be identity of type int and make it self generating. Your supplier table could look like this :
SupplierID int, Primary Key, identity
SupplierName nvarchar(100)
Now, when you do an update, you would do it like this:
Update SupplierMaster
Set SupplierName = #supplierName
Where SupplierID = #suplierID
Such a SQL statement will return an int value. This return value will tell you how many SQL rows this update statement has changed. If it says 0 then it means that the SQL statement could not find that id you passed through and nothing changed. If it says 1, then the record was found and updated, if you get more than 1 you have an issue with the SQL statement and multiple rows were updated.
In your code check for this return value and that's how you determine if your update statement was successful or not.
Related
I have a sql table temp.it has 4 columns, 3 of which are primary keys(composite). While doing a insert to a table I need to check if the composite PK exists already in table. If yes I need to update the row else I need to insert a new row to temp table. Can I proceed this way. I don't know hoe to check for PK in table. Kindly guide me. Below is the Insert
string constr = ConfigurationManager.ConnectionStrings["constr"].ToString();
using (OdbcConnection con = new OdbcConnection(constr))
{
try
{
string query = "Insert into temp_table(Name,DeptName,Alias,City) values(name,dept,alias,city)";
con.Open();
OdbcCommand cmd = new OdbcCommand(query, con);
cmd.ExecuteNonQuery();
}
here name, dept and city are composite primary key.
Try to update first, if the record does not exists than the update will fail and then you can do an insert.
This is more efficient because each time the update succeeds then only one statement will be called.
update temp_table
set Alias = #alias
where Name = #name
and DeptName = #dept
if ##rowcount = 0 then
begin
insert into temp_table (Name, DeptName, Alias, City)
values (#name, #dept, #alias, #city)
end
your solution
if not exists (Select * from temp_table where Name=#name and DeptName=#dept and City=#city)
begin
Insert into temp_table
(Name,DeptName,Alias,City)
values(#name,#dept,#alias,#city)
end
else
begin
update temp_table set Alias=#alias where Name=#name and DeptName=#dept and City=#city
end
The Merge Command combine check, insert and update into one command.
Syntax is here:
https://msdn.microsoft.com/en-us/library/bb510625.aspx
I'm trying to insert two data columns into my SQL Server database but I get an error at the code line -> cmd.ExecuteNonQuery();
Cannot insert the value NULL into column OrderID, table RestaurantApp.dbo.Junc_Order; column does not allow nulls. INSERT fails.
The OrderID column is actually the primary key in my data table. I set it identity(1, 1) and want to insert other data and meanwhile it can insert 1, 2, 3, 4....automatically.
Here is the part of my code:
string insertString = "INSERT INTO Junc_Order(ID, Quantity)values (#ID, #Quantity)";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("#ID", r_ID);
cmd.Parameters.AddWithValue("#Quantity", r_Quantity);
cmd.ExecuteNonQuery();
I already get connection with database ahead of these codes, so the problem should not be that.
Updated Junc_Order table design:
OrderID (PK,FK,int,not null)
ID(FK,int,not null)
Quantity(int,not null)
By viewing your question, it seems that your insert query is not correct:
First of all, you don't need to insert "OrderID" as it is primary key identity so sql server automatically insert it.
second, somewhere you are getting "r_ID" as null that's why you are facing error.Verify it and modify your code with the following:
string insertString = "INSERT INTO Junc_Order(Quantity) values(#Quantity)";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("#Quantity", r_Quantity);
cmd.ExecuteNonQuery();
I have a C# app with have to use SQL Server database with 1 table (All_Data) and 5 columns (ID, Name, Surename, Age,Location)
Before inserting a new row how can I find out or get the value of the last ID in the table
I have a following code but it,a not work well
string query = "SELECT MAX(ID) FROM All_Data";
SqlCommand comSelect;
comSelect = new SqlCommand(query, connection);
int ID = (int)comSelect.ExecuteScalar();
ERROR message:
ExecuteScalar: Connection property has not been initialized
Please help me
First, from your code it is not clear what is the value of the variable connection.
From the error message it seems that you don't have initialized this variable and thus you get the error. (connection = new SqlConnection(....);)
However, this is not the correct way to handle this scenario.
You need to make the ID column an IDENTITY column and then don't try to retrieve its value before executing any INSERT.
An IDENTITY column receives its value directly from the database when there is a new record to insert. And letting the database code work on this data it is the best option if you want to be safe from concurrency issues.
If you need to retrieve the ID value after an INSERT query because you need it as a Foreign Key in other tables or for your own code, then you could simply use the T-SQL command
SELECT SCOPE_IDENTITY()
For example, suppose you have to insert a record in that table, and you want to know the IDENTITY value assigned to the ID column
string query = #"INSERT INTO All_Data(Name,Surename,Age,Location)
VALUES(#name, #surname, #age, #loc);
SELECT SCOPE_IDENTITY()";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
cmd.Parameters.AddWithValue("#name", yourNameValue);
.... other parameters ...
int newID = Convert.ToInt32(cmd.ExecuteScalar());
}
As you can see, this code doesn't try to pass a value for the ID column. It pass just the other fields with a parameterized query. But at the end of the first query there is a call to SELECT SCOPE_IDENTITY() and this returns whatever value the database has assigned to the column ID (of course you should have set the IDENTITY property on the field).
This will work correctly in multiuser and concurrent scenario
The error fires when the command doesn't have a connection. Please check connection is open.
Error saysExecuteScalar: Connectio property has not been initialized
double Check your connection string whether it is defined properly. You can check here to know how to define connection string.
you have not opened connection so open it before use :
comSelect = new SqlCommand(query, connection);
connection.Open();
int ID = (int)comSelect.ExecuteScalar();
connection.Close();
For the web app that I am working on, whenever a user adds a new record to the database, the system validates if the record has successfully been added or not:
if (txnHnd.AddNewTxnDetails(txnDetails) == true && txnHnd.AddNewTxnName(txnName) == true)
{
string message = "Record has been saved.";
lblErrorMsg.Text = message;
Response.Redirect("FXTxnList.aspx");
}
else
{
string message = "Saving record failed.";
lblErrorMsg.Text = message;
}
Now, IF the record has been successfully added, only then will the system insert a sort of Reference Number to the newly-added record. My table has a primary key called TxnID of type int. It's an auto-increment number BTW. The question is, how do I extract the TxnID of the newly added record from the database? I need to put the code inside the if part of the if-else statement, where it says that the Record has been saved.
Update/Create the SP like
CREATE PROC SP_Insert
(
#name VARCHAR(50),
#id INT OUTPUT
)
AS
INSERT INTO Table (ColumnName) VALUES (#name)
SET #id=SCOPE_IDENTITY()
and then call this sp from ado.net like below
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SP_Insert";
SqlParameter param = new SqlParameter();
param.Name = "#id";
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
int id = (int)param.Value;
If you can modify the stored proc/command you use to insert a new record, you should use SCOPE_IDENTITY() to return the last generated identity value:
SELECT CAST(SCOPE_IDENTITY() AS INT)
If you're using a stored proc and cannot modify it, you need to use ##IDENTITY, as SCOPE_IDENTITY() works only in the same scope (in this case within a stored proc). Be careful though, as ##IDENTITY will return the last identity not limited by scope which can be affected e.g. by triggers.
SELECT CAST(##IDENTITY AS INT)
More on MSDN.
In my project I use System.Data.SQLite. Database has table Tags, which contains autoincrement primary field ID (type Integer). When I write:
using (SQLiteCommand command = conn.CreateCommand())
{
command.CommandText = "insert into Tags(name) values(#name) returning into #id";
command.Parameters.Add("#id", DbType.Int32).Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
}
Visual Studio said that the operation is not supported. How to fix it?
Error occurs on line:
command.Parameters.Add("#id", DbType.Int32).Direction = ParameterDirection.Output;
I found working query:
SELECT last_insert_rowid()
SQLite 3.35.0 and newer supports RETURNING clause:
The RETURNING clause is designed to provide the application with the values of columns that are filled in automatically by SQLite.
The code could look like:
INSERT INTO Tags(name) VALUES(#name) RETURNING ID;
I advice to use Stored Procedure.
IN SQL Server has ##IDENTITY system Variable . it returns the last autoincrement value
CREATE PROCEDURE SPGetLastAutoInc #name varchar, #lastAutoResult INT OUTPUT AS
INSERT INTO Tags(name) values(#name)
SET #lastAutoResult = ##IDENTITY
-- Return the number of all items ordered.
RETURN lastAutoResult
GO