SQL Server using SCOPE_IDENTITY [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have 2 tables :
CREATE TABLE [dbo].[Accessoires1]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL,
[ClientID] [int] NOT NULL,
[TotalPrice] [varchar](50) NOT NULL
)
CREATE TABLE [dbo].[Accessoires2]
(
[Accessoire1_ID] [int],
[Date] [datetime] NOT NULL,
[ClientID] [int] NOT NULL,
[TotalPrice] [varchar](50) NOT NULL
)
Then I have a stored procedure Proc1 that insert values into table Accessoire1, and I have Proc2 which adds data to accessoires2 - but it needs the a specific accessoire1_ID
In my C# code, I execute those procedures at the same exact time so I need the Accessoires1.ID to be inserted into accessoires2 - how can I manage to do that?

In your first procedure do this:
CREATE PROCEDURE nameOfSp
#col1 VARCHAR(20),
#newId INT OUTPUT
AS
BEGIN
SET NOCOUNT ON
-- your code
-- assign identity to variable
SELECT #newId = SCOPE_IDENTITY()
RETURN
END
Your c# code will need to call the first stored procedure and passing it an output parameter like this:
SqlParameter newId = new SqlParameter();
newId.ParameterName = "#newId";
newId.DbType = DbType.Int32;
newId.Direction = ParameterDirection.Output;
After the first procedure is executed, your C# code can get the value of newId returned like this:
int outValue = (int) newId.Value;
Now you can pass it to your 2nd procedure.

Related

How do I get a stored procedure to insert ##identity of previous inserts AUTO ID [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Image above is order details table and the orderID is foreign key ref orders table.
This is my orders table which will generate a id when a table is inserted via this stored procedure below. PK OrderID
The stored procedure that inserts a table will happen first which will generate a orderID. I will then run this stored procedure below wanting to insert the last inserted orderID from orders into Orderdetails table using ##identity
but when I try to insert it comes up with this error saying the orderID is null
Have I written a wrong SQL statement to perform my desired action of inserting previously generated ID from one table to another
You're missing a few things.
First of all, you can't invoke ##IDENTITY. It's purpose is to save the identity value of a row you just inserted. Also, it's got issues with scoping, so you should use SCOPE_IDENTITY instead.
Your first procedure needs to return the inserted identity to the outer wrapper. This can be accomplished by using an OUTPUT parameter.
CREATE PROCEDURE dbo.testinsert333
(
#TableID TINYINT
,#OrderID INT OUTPUT
)
AS
BEGIN
INSERT INTO dbo.Orders (Orders.TableID)
VALUES (#TableID)
SET #OrderID = SCOPE_IDENTITY()
END
Your second procedure needs to just accept #OrderID. There's no way for this thread to snag an inserted identity value from a different thread. It must come in as a parameter.
CREATE PROCEDURE dbo.testinsert666
(
#OrderID INT
,#ProductID INT
,#Price INT
,#Quantity SMALLINT
,#OrderStatus BIT
)
AS
BEGIN
INSERT INTO dbo.OrderDetails
(
OrderID
,ProductID
,Price
,Quantity
,OrderStatus
)
SELECT #OrderID
,#ProductID
,#Price
,#Quantity
,#OrderStatus
END
GO
Now to tie all this together, they need to be called together, as in the example below.
BEGIN
DECLARE #OrderID INT
EXEC dbo.testinsert333 #TableID = 1, #OrderID = #OrderID OUTPUT
EXEC dbo.testinsert666
#OrderID = #OrderID
,#ProductID = #ProductID
,#Price = #Price
,#Quantity = #Quantity
,#OrderStatus = #OrderStatus
END
However, the best approach is to nest these two procedures into one, like below.
CREATE dbo.usp_AllInWonder
(
#TableID INT
,#ProductID INT
,#Price INT
,#Quantity SMALLINT
,#OrderStatus BIT
)
AS
BEGIN
DECLARE #OrderID INT
INSERT INTO dbo.Orders (Orders.TableID)
VALUES (#TableID)
SET #OrderID = SCOPE_IDENTITY()
INSERT INTO dbo.OrderDetails
(
OrderID
,ProductID
,Price
,Quantity
,OrderStatus
)
SELECT #OrderID
,#ProductID
,#Price
,#Quantity
,#OrderStatus
END
Remove line 13 from testinsert666. You're passing in the OrderID, so you don't need to assign it there. Any call to ##identity ( or preferably scope_identity()) would be in `testinsert333'.
For you to use the ##IDENTITY in testinsert666, you need you have the insert creating ##IDENTITY to happen in the procedure testinsert666. testinsert666 can only be used in the same session it was generated.
See ##IDENTITY (Transact-SQL)

INSERT in one table but it locks another table [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm now having a problem with SQL Server table lock. I'm developing in C#.
My queries run under 1 transactions.
I name it for the easiest way to recognize.
"setTransaction"
setTransaction is only for "INSERT / UPDATE / DELETE".
if I want to do SELECT. I'll use SqlDataAdapter.
If I want to do INSERT / UPDATE or DELETE, it's the time to use setTransaction.
here is the table structure of each ...
[LOG](
[log_id] [int] IDENTITY(1,1) NOT NULL,
[subject] [text] NOT NULL,
[query] [text] NOT NULL,
[log_datetime] [datetime] NOT NULL,
[user_id] [int] NOT NULL,
[emp_id] [int] NULL,
[old_value] [text] NULL
)
[RESERVATION_DETAIL](
[**reservation_detail_id**] [int] IDENTITY(1,1) NOT NULL,
[reservation_id] [int] NOT NULL,
[spa_program_id] [int] NULL,
[price] [int] NULL,
[oil] [int] NULL
)
[RESERVATION_THERAPIST](
[reservation_therapist_id] [int] IDENTITY(1,1) NOT NULL,
[**reservation_detail_id**] [int] NOT NULL,
[therapist_id] [int] NOT NULL,
[hours] [int] NULL,
[mins] [int] NULL
)
[LOG] is working independently.
[RESERVATION_DETAIL] are connected to [RESERVATION_THERAPIST] via reservation_detail_id
The problem is ....
BEGIN TRANSACTION.
I want to delete a record from "RESERVATION_DETAIL" with reservation_detail_id = 25
I select a record from "RESERVATION_DETAIL" with reservation_detail_id = 25
SELECT * FROM RESERVATION_DETAIL WHERE RESERVATION_DETAIL_ID = 25
I insert into table "LOG" with data from 2.
INSERT INTO LOG ( subject, query, log_datetime, user_id, emp_id, old_value ) VALUES (
'DELETE TEMP RESERVE FROM RES_DETAIL[RES_DETAIL_ID:25]',
'DELETE FROM RESERVATION_DETAIL WHERE RESERVATION_DETAIL_ID = 25',
CURRENT_TIMESTAMP,
1,
NULL, 'reservation_detail_id:25|reservation_id:25|spa_program_id:-1|price:|oil:'
)
now I delete from "RESERVATION_DETAIL" where reservation_detail_id = 25
Then I want to delete a record from "RESERVATION_THERAPIST" with reservation_detail_id = 25
DELETE FROM RESERVATION_DETAIL WHERE RESERVATION_DETAIL_ID = 25
I select a record from "RESERVATION_THERAPIST" with reservation_detail_id = 25 <----- I GOT THE LOCK HERE !!
SELECT * FROM RESERVATION_THERAPIST WHERE RESERVATION_DETAIL_ID = 25
I insert into table "LOG" with data from 5.
Finally I will delete from "RESERVATION_THERAPIST" where reservation_detaiil_id = 25
Above steps were run consequently.
the step 5 (which is about table "RESERVATION_THERAPIST") is now wait on step 3 (about table "LOG") to finished but It never finished.
I don't understand why I insert into table LOG but it put the lock onto the table B !? or this is not a lock !?
there were the queries before the above step that insert into LOG without any problem.
Now I can solve my problem.
The queries and steps are already OK.
But I forgot that the table "RESERVATION_DETAIL" has a trigger that will run right after the DELETE query is committed.
So the trigger will go to delete a record in "RESERVATION_THERAPIST" automatically and this step is under the transaction.
So "RESERVATION_THERAPIST" was locked up after "DELETE FROM RESERVATION_DETAIL" but before I can "SELECT * FROM RESERVATION_THERAPIST"
Several things could cause the table to be locked until the deletion is through:
You are directly deleting from the table you are trying to select from
You have cascade delete turned on for a parent table to the one that is locked.
You have a trigger on another table that you are taking an action from that also deletes from the table.
You are trying to delete the tables out of order (child table are always deleted first, then parent ones. When deleting from a parent table, it will check to see if child records exist. This of course takes longer than a straight delete and will cause a rollback if the child data exists which takes longer yet.
You have deadlock between two process running at the same time.
You got the lock on B because you deleted from it.

How to get some extra info description of a mysql table

I found in stackoverflow a link who explains this question. I wrote a procedure who does that but the retreived data is not as it's expected by mysql
Here is data that I receive using procedure (this gives an error when I use it for creating a table in this form, the error is syntax error near id int(11))
CREATE TABLE IF NOT EXISTS `atelier`(
`id` int(11) NO PRI auto_increment
`nom` varchar(30) NO UNI
`at_date` date NO
`pax` int(11) NO
`prix` double NO
`vente` double YES
`note` varchar(200) YES
`cr_user` varchar(15) NO
`cr_date` datetime NO
`up_user` varchar(15) YES
`up_date` datetime YES
And here is the data given by phpmyadmin
CREATE TABLE `Atelier` (
`id` int(11) NOT NULL auto_increment,
`nom` varchar(30) NOT NULL,
`date` date NOT NULL,
`pax` int(11) NOT NULL,
`prix` double NOT NULL,
`vente` double default NULL,
`note` varchar(200) default NULL,
`cr_user` varchar(15) NOT NULL,
`cr_date` datetime NOT NULL,
`up_user` varchar(15) default NULL,
`up_date` datetime default NULL,
PRIMARY KEY (`id`)
) ENGINE=Innodb DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
What I want to know should I do translation of YES AND NO within my program or there is a way to obtain it with a query, and with wich query I can obtain info of two last lines given by phpmyadmin.(I think they are usefull for the choose of ENGINE and define the unique and primary keys)
PS:Using c#, and names of the tables I get from another procedure that exist in my program. I don't get it with DESCRIBE. What I receive is between id and up_date.
Here is the link of my procedures MY PROCEDURES
You didn't show the procedure generating this output, but if you replace DESCRIBE in there with SHOW CREATE TABLE I suppose it will work.

SQL Server VARBINARY(MAX)

I have a stored procedure that inserts a varchar & VARBINARY(MAX) values in the table.
I pass a c# byte[] to the varbinary(max) field. I also see that the size of the byte[] size is 80142 which satisfies the max limit of varbinary. Stored procedure executes without any errors. But when I try to query that table I see empty values in the varbinary datatype.
SQL sp
ALTER PROCEDURE [dbo].[Test]
-- Add the parameters for the stored procedure here
#PNumber varchar(50)
,#Byte varbinary(max)
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO [Test].[dbo].[Data]
([PNumber]
,[PByte])
VALUES
(#PNumber
,#Byte)
END
C# CODE
byte[] theData = doc.GetData();
DAL_DataTableAdapters.QueriesTableAdapter qta = new DAL_DataTableAdapters.QueriesTableAdapter();
qta.Test("test", theData);
Table structure:
CREATE TABLE [dbo].[Data]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[PNumber] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PByte] [varbinary](max) NULL
) ON [PRIMARY]
How do you determine that the data is empty? I'm quite certain that SQL Server Management Studio will not display a value that is too long (I don't know the limit), even when the value is there.

Stored Procedure with IsIDenity and cmd.Parameters.Add

I am creating an ASP.NET Wiki for myself to track the knowlege I gain in C# and other language.
I have created a Stored Procedure to insert a category into a DB, the DB has two fields C_ID(int) and Category(varchar 25). In my ASP page, there is no field for C_ID, it increments automatically by IsIdentiy = true;
When I try to excute it, it fails. What is the best approach to handle this?
Code:
ALTER PROCEDURE dbo.InsertCategory
#ID int,
#CATEGORY varchar(25)
AS
INSERT INTO Wiki
(C_ID, C_Category)
Values (#ID, #CATEGORY)
/* SET NOCOUNT ON */
RETURN
Did I miss something to insert from the .aspx page?
try
{
//create a command object identifying the Stored Procedure
SqlCommand cmd = new SqlCommand("InsertCategory", conn);
//Set the command type
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("Category", txtAddCatagory));
cmd.ExecuteNonQuery();
}
Just omit the id from the insert. If you configured identity correctly, the database will take care of increasing the number. For example:
GO
ALTER PROCEDURE dbo.InsertCategory(#CATEGORY varchar(25))
AS
INSERT INTO Wiki (C_Category) Values (#CATEGORY)
GO
To verify the identity is set correctly, if you script the table, the C_id column should look like;
[C_id] [int] IDENTITY(1,1) NOT NULL,
Or even better:
[C_id] [int] IDENTITY(1,1) PRIMARY KEY,
So you're getting an exception that you cannot insert into an identity column, right? The trick is to not specify the identity column in your insert statement, because it automatically get populated... ;)
ALTER PROCEDURE dbo.InsertCategory #CATEGORY varchar(25) AS
INSERT INTO Wiki (C_Category) Values (#CATEGORY) /* SET NOCOUNT ON */ RETURN

Categories