How to get auto generated Id before insertion? - c#

I have a table like the below picture, and I want to get IDwithChar column value concatenating the value with image address, and inserting that into ImageCover column at same query, how can I achieve that ?

Try to concate the two column values and Use UPDATE statement to update the value in the related column.
CREATE TABLE Test (
IdWithChar NVARCHAR(MAX),
ImageAddress NVARCHAR(MAX),
CoverImage NVARCHAR(MAX)
)
INSERT INTO Test VALUES ('B00001','Test Address','Test-Image-Url')
Query:
UPDATE TEST
SET CoverImage= IdWithChar +' '+ ImageAddress
WHERE Your_condition

first you must insert values and get the last identity and then update the field in the record.
insert into item values ('test', 'test')
declare #itemId int = ##IDENTITY
update item set item_code = #itemId where item_id = #itemId

Related

How to get before and after insert unique ID from output clause while inserting

How can one get before and after insert unique ID from output clause while inserting?
For example: I have a table named A, I need to copy some of the records via
insert into select statement
and I need to get old unique id and new unique id in to a temp table using
OUTPUT Clause
This means I need to get return type as before insert unique identifier and after inert unique identifier. For that, I tried using below query as
DECLARE #MyTableVar TABLE
(
newid UNIQUEIDENTIFIER,
oldid UNIQUEIDENTIFIER
);
INSERT A (name, description)
output inserted.guid,
d.guid
INTO #MyTableVar
SELECT name, description
FROM A d
WHERE deptID = 550;
SELECT *
FROM #MyTableVar
But I am not able to get d.guid in output clause. Please correct me if there are any other options to get before and after insert unique id as output.
You should use column names from table.In your case ,you are using Inserted.Guid which should throw syntax error
create table tt
(
id varchar(300) default newid()
)
declare #t table
(
id varchar(300)
)
insert into tt
output inserted.* into #t
default values
select * from #t
You can use
##IDENTITY
to get after insert unique id as output.

How to create multiple tables dynamiclly in view by using following data in list

My requirement is to create multiple tables dynamic
here is part numbers .table number
1. table number 1 has 2 records and table number 2 has also 2 records.
firstly create table no. 1 and fill its records
after that create new second table no. 2 and its records and soo on according to table number
in some case i have only part no. but in this we create another something html in which we display those data which does not have table no.
Declare table variable to store id and tableNo.
declare #TempTable table(id int identity,TableNo int)
Insert into this table of all distinct TableNo column data..
INSERT INTO #TempTable
SELECT DISTINCT TabloNo
FROM TableName
Declare following variable and set its value like...
declare #counter int, #totalTable int, #NoOfTable int, #StrquryInser nvarchar(max)
select #totalTable = count(id) from #TempTable
set #counter = 1
set #StrquryInser = ''
In while block select table data according to tableNo and insert it into #temp1, #temp2...dynamically using this code...
begin
select #NoOfTable = TableNo
from #TempTable
where id = #counter
set #StrquryInser = #StrquryInser + ' select * into #temp' +cast(#counter as varchar(10)) + ' from TableName where isnull([TabloNo],0)='+cast(isnull(#NoOfTable,0) as nvarchar(10))
set #StrquryInser=#StrquryInser + ' select * from #temp' +cast(#counter as varchar(10))
set #counter=#counter+1
end
execute the string Query #StrquryInser like...
exec(#StrquryInser)
In above query you can store your table data in multiple temp variables like temp1, #temp2 etc..
Apart form these #temp table you can also store your data in permanent table using above logic..

Returning data which is not found in where clause and didn't update in sql

In a c# desktop application I am getting this list of data which I am reading by barcode into text file; here is the result;
R900, 27674T07, 27438T17, 27736T21, 26609T08,
R901, 27770T12, 27833T07, 26402T12, 27771T09, 26003T13,
R902, 26003T14, 26402T11, 26246T17,
R904, 28055T09, 25356T08, 25825T07, 25556T09,
and I am transforming it to update queries;
UPDATE TABLE SET NUMBER = R900 WHERE id in ( 27674T07, 27438T17, 27736T21, 26609T08)
UPDATE TABLE SET NUMBER = R901 WHERE id in ( 27770T12, 27833T07, **26402T12**, **27771T09**, 26003T13)
UPDATE TABLE SET NUMBER = R902 WHERE id in ( 26003T14, **26402T11**, 26246T17)
UPDATE TABLE SET NUMBER = R904 WHERE id in ( 28055T09, 25356T08, 25825T07, **25556T09**)
Finally I am executing this SQL query. But the problem is I don't know which id is not found in IN clause in database. I need to report back to user which id didn't found with its NUMBER
For example the bold id's are not found in database, and couldn't update. So expected result is:
NUMBER id
R901 26402T12
R901 27771T09
R902 26402T11
R903 25556T09
how can I return this?
You could do something like this
declare #mytable as TABLE
(
Id nvarchar(20)
)
UPDATE TABLE SET NUMBER = R900
OUTPUT INSERTED.Id into #mytable
WHERE id in ( 27674T07, 27438T17, 27736T21, 26609T08)
Select * from #mytable
#mytable will contain updated Ids only.
Hope this helps.
create a temp table to store the splitted value into it.
then
SELECT temp.number, temp.Id
FROM #temp temp
LEFT OUTER JOIN TABLE ON temp.id = TABLE.id
WHERE TABLE.id is null

Uupdate values in two tables via stored procedure

I have two tables and I need to update values in them via a stored procedure. Tried too much to update but some times it update the first table only, others the second or even fail due to cannot allow duplicates. Also when it updates the WHOLE data in the table becomes the same as the new updated ones. I've now reached to this error after all these lines of codes
Cannot insert the value NULL into column 'Emp_ID',table 'DatePics'; column does not allow nulls. UPDATE fails.The statement has been terminated
Here is the SQL code :
ALTER procedure [dbo].[UpdateEmp]
#EmpName nvarchar(100),
#Nationality nvarchar(30),
#Passport nvarchar(20),
#ContractDate date,
#HealthDate date
AS
BEGIN
set nocount on;
DECLARE #IDs table (ID int )
UPDATE Employee SET
EmpName=#EmpName, Nationality=#Nationality, Visa=#Visa, Passport=#Passport,
ReceivedDate=#ReceivedDate,IDIssue=#IDIssue, IDExpiry=#IDExpiry, Sponsor=#Sponsor
output inserted.ID into #IDs (ID)
WHERE ID = #ID
UPDATE DatePics SET
FingerDate=#FingerDate, ContractDate=#ContractDate, HealthDate=#HealthDate
where Emp_ID in (select ID from #IDs);
END
After writing the stored procedure code, I wrote the C# code like this:
private void updatebtn_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = db.con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UpdateEmp";
cmd.Parameters.AddWithValue("#EmpName", NameSeartxt.Text);
cmd.Parameters.AddWithValue("#Nationality", NatSeartxt.Text);
cmd.Parameters.AddWithValue("#Passport", PassSeartxt.Text);
cmd.Parameters.AddWithValue("#ContractDate", ContractSeartxt.Text);
cmd.Parameters.AddWithValue("#HealthDate", HealthSeartxt.Text);
db.con.Open();
int up = cmd.ExecuteNonQuery();
if (up > 0)
{
MessageBox.Show("Update done ", "DONE !");
SearNametxt.Text = "";
}
else
{
MessageBox.Show("Failed to update", "FAIL !");
SearNametxt.Text = "";
}
db.con.Close();
}
Any clue?
I can see three problems with your query. 1 You declare ID, but don't assign it before using it, so it will always be NULL for the first query, so this will never update any rows:
DECLARE #ID int
UPDATE FrstTable SET
EmpName=#EmpName, Nationality=#Nationality, Passport=#Passport
WHERE ID = #ID
Secondly, you are using SCOPE_IDENTITY to attempt to get the ID of the record that has been updated. You can't do that, SCOPE_IDENTITY will return the last inserted ID, it is not affected by updates. You will need to use OUTPUT to get the Updated ID:
DECLARE #IDs TABLE (ID INT);
UPDATE FirstTable
OUTPUT inserted.ID INTO #Ids (ID)
SET EmpName = #EmpName,
Nationality = #Nationality,
Passport = #Passport;
Thirdly, your second update statement has no where clause, so will update the entire table:
UPDATE ScndTable
SET Emp_ID=#ID, ContractDate=#ContractDate, HealthDate=#HealthDate
WHERE EmpID IN (SELECT ID FROM #Ids);
Your stored procedure looks weird to me. I believe there should be a WHERE cluase for the second UPDATE otherwise it will always update the whole ScndTable table. set #ID = SCOPE_IDENTITY(); seems to be reduntant here. Are you trying to perform insert into ScndTable if there's no corresponding Emp_ID there? Finnaly explicitly create a transaction to update either both tables or none.
Hope it helps!
Please assign the value of #ID variable, before executing the first update statement.
I think you are trying to update some row, so you can pass the 'id' value from the CSHARP code. When you use the SCOPE_IDENTITY, you will get the last inserted value. Try to pass the ID value from the front end.

Update rows in Database using XML data

This is the first time I am using XML to insert data into a table.I am saving the data from the front end(all the Datagridview rows) into an xml file and sending it to database to insert into table SD_ShippingDetails.Below is the Query for reading the XML data and saving data.As you can see from the Query I am deleting the related ShippingID details and inserting again.(DELETE FROM SD_ShippingDetails WHERE ShippingID=#ShippingID).Can we update already existing rows in the SD_ShippingDetails by getting the data from XML.If Yes,Please help me with the query.
CREATE PROCEDURE SD_Insert_ShippingDetails
#PBMXML as varchar(Max),
#ShippingID as INT
AS
BEGIn
declare #i int
exec sp_xml_preparedocument #i output,#PBMXML
DELETE FROM SD_ShippingDetails WHERE ShippingID=#ShippingID
INSERT INTO SD_ShippingDetails(ShippingID,Weight,Height,TotalBoxes,Price)
SELECT ShippingID,Weight,Height,TotalBoxes,Price FROM OPENXML(#i,'Root/ShippingBox',2)
WITH (
ShippingID int,Weight varchar(20),Height varchar(20),TotalBoxes varchar(20),Price numeric(18,2))
exec sp_xml_removedocument #i
END
Thanks.
You are on SQL Server 2005 so you can use the XML datatype instead of openxml so this answer uses that instead. Using the XML datatype is not necessary for the solution. You can rewrite using openxml if you want to.
You specified in a comments that there is an ID identity field in SD_ShippingDetails (I assume that is the primary key) but you also said that the combination of ShippingID and Weight is unique. That leaves us with a table structure that looks like this.
create table dbo.SD_ShippingDetails
(
ID int identity primary key,
ShippingID int not null,
Weight varchar(20) not null,
Height varchar(20),
TotalBoxes varchar(20),
Price numeric(18,2),
unique (ShippingID, Weight)
);
The stored procedure first needs to update all rows that already exist in SD_ShippingDetails and after that it needs to insert the rows that are missing.
create procedure dbo.SD_Insert_ShippingDetails
#PBMXML as xml
as
update dbo.SD_ShippingDetails
set Height = T.N.value('(Height/text())[1]', 'varchar(20)'),
TotalBoxes = T.N.value('(TotalBoxes/text())[1]', 'varchar(20)'),
Price = T.N.value('(Price/text())[1]', 'numeric(18,2)')
from #PBMXML.nodes('Root/ShippingBox') as T(N)
where ShippingID = T.N.value('(ShippingID/text())[1]', 'int') and
Weight = T.N.value('(Weight/text())[1]', 'varchar(20)');
insert into dbo.SD_ShippingDetails(ShippingID, Weight, Height, TotalBoxes, Price)
select T.N.value('(ShippingID/text())[1]', 'int'),
T.N.value('(Weight/text())[1]', 'varchar(20)'),
T.N.value('(Height/text())[1]', 'varchar(20)'),
T.N.value('(TotalBoxes/text())[1]', 'varchar(20)'),
T.N.value('(Price/text())[1]', 'numeric(18,2)')
from #PBMXML.nodes('Root/ShippingBox') as T(N)
where not exists (
select *
from dbo.SD_ShippingDetails
where ShippingID = T.N.value('(ShippingID/text())[1]', 'int') and
Weight = T.N.value('(Weight/text())[1]', 'varchar(20)')
);
SQL Fiddle
If you have Sql Server 2005, then placing the values in #temp or #variables tables is best.
With 2008 and up, you could piggy back on the MERGE functionality.
http://msdn.microsoft.com/en-us/library/bb522522(v=sql.105).aspx
Here is a good link for xml shredding. Note, you are using the older version of OPENXML. That was a more Sql Server 2000 command. Check Plamen's blog below for 2005 and above syntax.
http://pratchev.blogspot.com/2007/06/shredding-xml-in-sql-server-2005.html
I would populate your XML into a variable table and then use an Update Statement and an Insert with a Not Exists.
If you had SQL 2008 you could replace your delete and insert statements with this...
MERGE SD_ShippingDetails AS Target
USING (SELECT ShippingID,
Weight,
Height,
TotalBoxes,
Price
FROM OPENXML(#i,'Root/ShippingBox',2)
WITH (ShippingID int,
Weight varchar(20),
Height varchar(20),
TotalBoxes varchar(20),
Price numeric(18,2)) ) AS source (ShippingID,Weight,Height,TotalBoxes,Price)
ON (target.ShippingID = source.ShippingID)
WHEN MATCHED THEN
UPDATE SET Weight = source.Weight,
Height = source.Height,
TotalBoxes = source.TotalBoxes,
Price = source.Price
WHEN NOT MATCHED THEN
INSERT (ShippingID,Weight,Height,TotalBoxes,Price)
VALUES (source.ShippingID,source.Weight,source.Height,source.TotalBoxes,source.Price);

Categories

Resources