##Identity return same value on each insert - sql-server

I have a stored procedure where which insert an statement and returns ##Identity.
This ## Identity returns always 1. When removed the ##Idnetity to Identity_Scope it returns the correct expected value, which was always incremented by 1. so this is good. but the question is. Why ## Identity columns is returning 1.
i checked and removed all the trigger and checked all the function but have no idea why i am getting 1 with ##Identity. Seems like there is a table that is being truncated and then a value is being inserted.
Any clue guys why ##Identity is returning 1 all the time. Is there server settings that is doing something?

Please note that:
The ##identity function returns the last identity created in the same
session.
The scope_identity() function returns the last identity
created in the same session and the same scope.
The ident_current(Name) returns the last identity created for a specific
table or view in any session.
So please send us your code for better assistance. You may use ##Identity in a wrong way.

Related

SQL Server returns no data in stored procedure via ASP.NET Web API

I use a key with every API request to ensure that the API can't be used by anyone besides those who must.
In my SQL Server stored procedure, I check if the key is correct, and if it is, it returns my data, if not, it returns nothing (SELECT TOP 0 FROM my_Table). But, I see that whenever I run this stored procedure, it always returns nothing. So I guess the problem lies within what I check should be true. What I need is to check if a row exists where the Key column = the key I gave.
This is what I've tried to check whether the row exists:
IF (EXISTS (SELECT * FROM my_KeyTable WHERE [keyColumn] = #KeyParam))
BEGIN
--return my data
END
I've also tried using the SELECT COUNT() method and checking whether the amount of returned rows is greater than 0 (> 0).
So to get back to my problem, my SQL IF statement never seems to be true. Thus returning nothing as told to in the ELSE statement. So any help would really be appreciated.

VB6 application - automatically incremented number check

I'm building a small application and I came across an issue that I need to resolve. When I insert a new client into the SQL-SERVER I need to create an ID number to go with the client. I have a value, say - 1000 in a reference table, that gets pulled from the table, incremented by 1, then put back into the ref table, and the value 1001 gets assigned to the client. Before it gets saved to the client, I add 'TOL' to the number - so when save is complete, the ID is TOL1001. The issue I need to resolve is to check the tblClient_TABLE, to make sure that ID TOL1001 doesn't exist already before doing the insert for a new client.
I'm not really sure where I should do it, because on SAVE, I call the function that increments the number, assigns TOL to it and stores the value in an invisible textbox, so when I do my insert, it just pulls the value from the textbox...
strSQL = "INSERT into tblClient_TABLE (ID) values ("txtIDnumber.text")
I obviously have more data to insert, it's just i'm struggling with finding a logic way to check for the already existing ID.
Thanks for any ideas, help!
Your database is able to use identity columns (=autoincrement). So, if you insert a new record, an identity column will get the next value (you can rely on the uniqueness).
How do you get this number? The insert statement has (for mssql) an "output inserted" clause, and if you use ado with executescalar you get your inserted id.
The SQL command (add the vb6 code for ado command you must)
INSERT INTO [TABLENAME] ( [COL1], [COL2] ) OUTPUT INSERTED.MYID VALUES ( #COL1, #COL2 )
... add your Parameter values here ....
result = adoCommand.ExecuteScalar()
(something like that, donĀ“t have VB6 at the office ...)

SELECT SCOPE_IDENTITY() Always Returns 1

I'm using this query:
INSERT INTO [LepidoliteDB].[dbo].[EGelLayerWeighingData] ([EGelWeighingDataID], [Amount], [ContainerID], [Portions],
[PortionNumber], [Canceled], [LayerID], [WeighingDone], [InsertDone],
[MeasuresDone], [StartDateAndTime], [EndDateAndTime])
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
SELECT SCOPE_IDENTITY()
But SCOPE_IDENTITY() always returns 1.
What am I missing?
Maybe you have an instead-of / for trigger there? what version of MSSQL are you using? Have you tried doing this without a database name? Have you tried this with a begin-end block?
Have you read this article ##IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT
I know this is an old thread, but I was having this same issue, and I managed to solve it by going into my XSD and on the query, changing the ExecuteMode of the query from NonQuery to Scalar. This stopped it always returning 1 and instead returning the ID of the previously added row.
It was probably down to me trying to add the SELECT to the INSERT afterwards, rather than doing it all at once and the UI making it correctly for me.
Best way to write it is ..
RETURN SCOPE_IDENTITY()
You can also use ##IDENTITY and IDENT_CURRENT for this
SCOPE_IDENTITY, IDENT_CURRENT, and ##IDENTITY are similar functions because they return values that are inserted into identity columns.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT (Transact-SQL).
SCOPE_IDENTITY and ##IDENTITY return the last identity values that are generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; ##IDENTITY is not limited to a specific scope.
Therefore RETURN SCOPE_IDENTITY() is the best one.
I had this problem and I must admit it was a dumb mistake, but I thought it may happen to someone else. I was using the Execute command that returns the number of rows affected instead of a Query command.
By the way, I was combining my Insert and SELECT SCOPE_IDENTITY() together in one command, which is why I started with the Execute command. I was still able to combine them, but I used ExecuteScalar instead.
Late to the thread, but if someone is using Dapper ORM and they are doing an UPDATE or INSERT a single row and want to know the primary key of that updated record:
var connection = new SqlConnection("ConnectionString");
string sql=#"INSERT INTO [dbo].[Student] ([Name],[Subject])
VALUES (#Name,#Subject)
SET #StudentId=CAST(SCOPE_IDENTITY() as int)";
For the above SQL string, if you execute the SQL connection like:
Result=connection.Execute(sql,new {Name,Subject});
The value of Result will be the number of rows affected, in this case only one since we have inserted only one row.
Instead do this:
Result=connection.Query<int>(sql,new {Name,Subject}).Single();
Now Result will have the primary key value of the newly inserted/updated column.
Remember, this answer is only relevant to single row insertion/update

Stored procedure problem in MS Access caused by ReturnsRecords (accdb)

I have a relatively simply stored procedure that runs an insert, and then attempts to return the last inserted ID. This is done so I can the ID via SCOPE_IDENTITY(). This was working great for me. But then, I got reports that on some machines, the stored proc would cause duplicate results.
After investigating it, I found that the cause was the use of the property ReturnsRecords. When true, it will run a query twice! For a select; who cares. For this case though, it is causing duplicates in my database.
Setting ReturnsRecords to false gets rid of the problem, but then it defeats the purpose of the stored proc (I absolutely must get the proper last inserted ID for the record)!
My question is simply this: How would I go about inserting this record and getting the ID of the new record, while getting around this problem?
Additional Info:
I am currently using DAO
I have tried the ADO.Command method, but it is
very error prone and doesn't seem to
work with output parameters for me.
I am using the stored proc solely for the purpose of retaining scope. I do not have my heart set on using a stored proc. I simply need a reliable way to get the id of the last inserted row.
This is an ACCDB
This is happening in access 2007
my DB backend is MSSQL Server 2008
Any help or insight is appreciated.
One of your parameters in the procedure can be set to output. Still don't return any rows, but set the value of that parameter to Scope_Identity()
create proc ReturnTheNewID
#NewValue int
, #ReturnNewID int output
as
set nocount on
insert ....
set #ReturnNewID = Scope_identity()

DataAdapter Update() requires input parameter for Auto increment primary key column

While updating a DataTable to a SQL Server database I get the error message "Column 'PK_Column' does not allow nulls" after calling GetErrors()
I don't want to provide a value for PK_Column because it is a auto increment primary key column in the database. My insert statement looks like this:
INSERT INTO [Order] ([Customer_Id], [OrderTime], [OrderType])
VALUES(#Customer_Id, #OrderTime, #OrderType)
SELECT CAST(SCOPE_IDENTITY() AS int) AS '#PK_Column'
It works as expected in SQL Server Management Studio, so the query is obviously not the problem.
I have four parameters on the insert command, one output parameter (#PK_Column) and three input parameters (#Customer_Id, #OrderTime, #OrderType). I figured out that I don't get the error if I set #PK_Column to InputOutput parameter, but then the PK_Column value does not get updated with the correct value created by the database.
Try
SELECT #PK_Column = SCOPE_IDENTITY()
This way, you assign to the local variable #PK_Column, which is picked up as a parameter.
When you do ... AS '#PK_Column', you are creating a data set with one column called "#PK_Column", when you want to assign a value to local var/parameter #PK_Column
Note: ... AS #PK_Column would fail because this is column alias. You're relying on a setting that allows '#PK_Column' to be a valid alias where as #PK_Column would fail

Resources