Check for new/existing values and update in sql - c#

I have a SQL table with Project Column value as 'Project1,Project2,Project3'
I need to update this row if they select a different value like 'Project4' from the telerik dropdown list as 'Project1,Project2,Project3,Project4'
I get the value from the dropdown same as 'Project1,Project2,Project3',so I will send this as a paramter to SQL.
Suppose if they select 'Project5,Project1'...Project1 should not be added as its already there.
Can some one suggest how do I check for new and existing values and update accordingly.
My simple update is not working for this scenario.Kind of struck.
Thanks

You can create a stored procedure and use merge to insert or update as necessary like the example below
DECLARE #nameField VarChar(50) = 'some data'
MERGE dbo.MyTable t
USING (SELECT #nameField [field]) s
ON t.myData = s.field
WHEN MATCHED THEN
UPDATE
SET t.myData = #nameField
WHEN NOT MATCHED THEN
INSERT (myData)
VALUES (#nameField);
If you want to limit redundant updates, e.g. if updating Project Column with the exact same data and block such updates, then you'll need to create an update trigger to check and block the update.

Related

Update Display Order Column for Multiple Records in One Statement

I am building a C#/ASP.NET application that calls a stored procedure to update the database.
I have a table in SQL Server with a column to control the Display Sort Order on output windows / print sheets.
[ProductID] [ProductName] [ProductDescription] [ProductSortOrder]
I am trying to update all Products (in this case) at one time. I am ONLY updating the Sort Order column in this call but want to avoid hitting the database one time for each product.
I was able to get it working by passing the Product ID to the stored procedure, but wondered about passing a list somehow.
UPDATE Products SET ProductSortOrder = 2 WHERE ProductID = 1
I'd like to hit the database once and do the processing there to parse the list and update the records based on the value of the list. I'd pass something like [ProductID1]|[SortOrderValue1],[ProductID2]|[SortOrderValue2] and split it by , then loop through and split each of those by | and pass that to the update statement.
I am not sure if this is possible or how to do it in SQL Server.
You can pass a table variable into a stored procedure
https://learn.microsoft.com/en-us/sql/relational-databases/tables/use-table-valued-parameters-database-engine?view=sql-server-2017.
You can then do your insert in one statement

Get last generated ID and add it to another table ASP.NET

How can I get get generated ID from primary key and then add it to another table in ASP.NET via SCOPE_IDENTITY?
For example:
Last generated ID on column NRRENDOR is number 26, I have deleted the rows. Now when I add datas to the database the nexy generated ID on NRRENDOR will be number 27. That number I want it to add to column NRD.
In your INSERT code, assuming it's in a stored procedure, using SCOPE_IDENTITY will get you the last identity that was inserted, which you can either reuse in the stored procedure or return to your app to use in another statement.
Some dummy SQL to demonstrate:
INSERT INTO NRRENDOR(SomeColumn) VALUES(1)
DECLARE #LastID int
// set #LastID to the last id inserted
SELECT #LastID = SCOPE_IDENTITY()
// to use in same procedure
INSERT INTO NRD (SomeColumn) VALUES(#LastID)
// to return it to code - or you could use an output parameter
SELECT #LastID
What has this got to do with ASP.NET? SQL would suffice.
INSERT INTO [Table2]( NRD)
SELECT MAX(NRRENDOR)
FROM Table1
' WITH (ROWLOCK, XLOCK, HOLDLOCK)
The correct way to do it will be to use #SCOPE_IDENTITY after you perform insertion as Tanner suggested. It will be worth noting that there is another way to get the current identity, ie, IDENT_CURRENT. You can use it like this
SELECT IDENT_CURRENT('Table1') + 1 as Current_Identity
Please note this too
Be cautious about using IDENT_CURRENT to predict the next generated
identity value. The actual generated value may be different from
IDENT_CURRENT plus IDENT_INCR because of insertions performed by other
sessions.
This comment from marc_s sums it all. How to get the next identity value from SQL Server

How can I set the primary key value to other col in table when I insert a new row in SQL Server

I am using LINQ-to-SQL class. I am inserting a new row using LINQ method object.InsertOnSubmit().
I need to set same value which is generate by SQL Server (using Identity) for table primary key column.
Now I need the same value at the time of inserting new row into table. And set the same value for other column in the same table at the time of insert only.
As I cannot update as after inserting because table has UPDATE TRIGGER.
I tried the following
_db.EmpNews.InsertOnSubmit(_EmpNews);
...
_db.DisplaySeq = _EmpNews.ID;
...
_db.SubmitChanges();
Where ID is the auto-generated (Identity) column.
The first question really is: why would you need to store the same value in two separate columns in the same table? What do you need this for? Doesn't seem to make a lot of sense to me....
Since the value of the IDENTITY column is only available once the row has actually been inserted, there is no way to get that value and set it to another column before the row has indeed been saved to the database table.
That basically leaves three options to get that value and store it somewhere else:
you can write an AFTER INSERT trigger that just set the other column to the value that's just been inserted in the IDENTITY column
you could wrap the whole saving process into a stored procedure which you call from your C# code (instead of just saving the object) and you would do the INSERT of the row, then get the newly created IDENTITY value and update the row again with that new value. But that would cause an UPDATE to happen - which you seem to say is impossible for you because of an UPDATE trigger (not quite clear on why this should be a problem....)
you can write two lines of C# code to get the IDENTITY value after it's been inserted (and available in the ID property of your object) and then store the object a second time. But that, too, would cause an UPDATE to happen - which you seem to say is impossible for you because of an UPDATE trigger (not quite clear on why this should be a problem....)
So I guess your best option would be an INSERT trigger to do this.
Try something like this:
CREATE TRIGGER trInsertEmpNews
ON dbo.EmpNews AFTER INSERT
AS BEGIN
UPDATE dbo.EmpNews
SET DisplaySeq = i.ID
FROM INSERTED i
WHERE dbo.EmpNews.ID = i.ID
END

How to save a new record when the id key is auto incremented

I have created a database in sql server 2008 and a table with auto increment id field
Also I develop a project in c#.net 2008
The problem occurs on click "save data" after of "add new" from BindingNavigator
for example I click "add new", fill all fields except id text (blanked id) and then click 'save data' then occurs the errors
The runtime exception is "notNullAllowedException: the column 'id' not allowed null.
But it is not required from the user to fill this field but has to returned from database after the save
I also set the properties of the id: (both c# project and sql server)
AutoIncrement = True
AutoIncrementStep = -1 (also I tested 1)
AutoIncrementSeed = -1 (also I tested 1)
No results.
How I could handled that?
Thanks
Don't include the identity column in your Insert statement.
If your statement is
INSERT INTO MyTable (ID, SomeField, SomeOtherField) VALUES (null, 'SomeValue', 'AnotherValue')
simply change it to
INSERT INTO MyTable ( SomeField, SomeOtherField) VALUES ( 'SomeValue', 'AnotherValue')
It sounds like you have two problems.
First, you're always inserting - what logic do you use to decide whether 'save' should be an insert or an update? I think this is the case becuase of the errors you're getting: "Cannot insert explicit..."
Second, you need to get the ID that SQL assinged on your insert so you can write it to your ID field for the next save=update. There are a couple of ways to do this, the way I prefer is to use a stored procedure to do the insert and pass an OUTPUT parameter that gets SCOPE_IDENTITY(). Something like this:
CREATE PROC xyz
(
#data...
#NEWID INT OUTPUT
)
AS
... do your INSERT ...
SET #NewID = SCOPE_IDENTITY()
)
double-check my syntax - not sure what version of SQL you're using

C# database update

I'm stuck on a little problem concerning database.
Once a month I get a XML file with customer information (Name, address, city,etc.). My primary key is a customer number which is provided in the XML file.
I have no trouble inserting the information in the database;
var cmd = new SqlCommand("insert into [customer_info]
(customer_nr, firstname, lastname, address_1, address_2, address_3.......)");
//some code
cmd.ExecuteNonQuery();
Now, I would like to update my table or just fill it with new information. How can I achieve this?
I've tried using TableAdapter but it does not work.
And I'm only permitted to add one XML because I can only have one customer_nr as primary key.
So basically how do I update or fill my table with new information?
Thanks.
One way would be to bulk insert the data into a new staging table in the database (you could use SqlBulkCopy for this for optimal insert speed). Once it's in there, you could then index the customer_nr field and then run 2 statements:
-- UPDATE existing customers
UPDATE ci
SET ci.firstname = s.firstname,
ci.lastname = s.lastname,
... etc
FROM StagingTable s
INNER JOIN Customer_Info ci ON s.customer_nr = ci.customer_nr
-- INSERT new customers
INSERT Customer_Info (customer_nr, firstname, lastname, ....)
SELECT s.customer_nr, s.firstname, s.lastname, ....
FROM StagingTable s
LEFT JOIN Customer_Info ci ON s.customer_nr = ci.customer_nr
WHERE ci.customer_nr IS NULL
Finally, drop your staging table.
Alternatively, instead of the 2 statements, you could just use the MERGE statement if you are using SQL Server 2008 or later, which allows you to do INSERTs and UPDATEs via a single statement.
If I understand your question correctly - if the customer already exists you want to update their information, and if they don't already exist you want to insert a new row.
I have a lot of problems with hard-coded SQL commands in your code, so I would firstly be very tempted to refactor what you have done. However, to achieve what you want, you will need to execute a SELECT on the primary key, if it returns any results you should execute an UPDATE else you should execute an INSERT.
It would be best to do this in something like a Stored Procedure - you can pass the information to the stored procedure at then it can make a decision on whether to UPDATE or INSERT - this would also reduce the overhead of making several calls for your code to the database (A stored procedure would be much quicker)
AdaTheDev has indeed given the good suggestion.
But in case, you must insert/update from .NET code then you can
Create a stored procedure that will handle insert/update i.e. instead of using a direct insert query as command text, you make a call to stored proc. The SP will check if row exists or not and then update (or insert).
User TableAdapter - but this would be tedious. First you have to setup both insert & update commands. Then you have to query the database to get the existing customer numbers and then update the corresponding rows in the datatable making the Rowstate as Updated. I would rather not go this way.

Categories