Im using Data Adapter/Set in SQL CE, i do create the following query to insert into table and then SELECT ##IDENTITY,
I want this SELECT statement return me the Student ID each time after Inserting into table, here is my Query:
INSERT INTO [Student] ([Name], [Family], [Address], [Phonenumber])
VALUES(#Name,#Family,#Address,#Phonenumber);
SELECT ##IDENTITY;
here is how i call query:
int x = da.Insert("Albert", "Alexandra", "No4.Oxford", Telnum);
Int x suppose to return me ID...
Here is the Error im getting :
There was an error parsing the query. [ Token line number = 4,Token line offset = 1,Token in error = SELECT ]
Insert Query it self it works but once adding SELECT ## IDENTITY at the end im getting error.
I really don't know what i'm doing wrong.
The return value of ExecuteNonQuery will be number of rows effected by these query. so you need to use store procedure instead of Single Query.
According to MSDN, CE doesn't support multiple commands per execution and you need to do this as two commands synchronously.
If you'd like to do this in a single call, you need to use a stored procedure rather than Insert, because it uses ExecuteNonQuery, which does not return any records. Otherwise you'll need to perform a select in another call to determine the identity.
The return value of ExecuteNonQuery is an integer that denotes the number of rows affected by your call.
Related
I'm trying to search a sql table for a specific string, and return the number of observations found. It keeps returning -1 though, whether the string is in the table or not. Here's my code:
#{
Layout = "~/_Layout.cshtml";
Page.title = "TestArea";
var db = Database.Open("Cafeen");
string SearchWord = "Jolly";
var msg = db.Execute("SELECT COUNT(*) FROM Products WHERE ProductName = #SearchWord");
}
<p>#msg</p>
Should I perhaps use something other than COUNT(*)? What is the significance of -1? I would have assumed the expression to return 0 if the string can't be found.
You are using the WebMatrix.Data namespace. In this context you should call the QuerySingle method not the Execute one because, as many have already stated, that method is for not returning rows data.
The Execute method is used to perform non-query commands on a
database, such as the SQL Drop, Create, Delete, Update, and Insert
commands.
Moreover I suggest to change your query statement to a more performant one
var db = Database.Open("Cafeen");
string SearchWord = "Jolly";
string cmdText = #"IF EXISTS(SELECT 1 FROM Products
WHERE ProductName = #searchWord)
SELECT 1 ELSE SELECT 0";
int exists = Convert.ToInt32(db.QuerySingle(cmdText, SearchWord));
.....
Pertinent to the SQL Database, there is:
SqlCommand.ExecuteScalar Method ()
(re: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx)
Otherwise, refer to Database.QueryValue Method (re: https://msdn.microsoft.com/en-us/library/webmatrix.data.database.queryvalue(v=vs.111).aspx)
Both methods return a scalar value from the first column/ first row.
Also, instead of COUNT(*) in SQL statement you can use COUNT(1) for better performance.
Hope this may help.
In db.Execute and SqlCommand.ExecuteNonQuery:
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements like SELECT, the return value is -1. If a rollback occurs, the return value is also -1.
Have a look at the following links may be helpful:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
How to Identify whether SQL job is successfully executed or not in C#
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
My EF Remove fails with the above statement. The table (Product) has a single primary key (ProductID). Running SQL Trace produced the following SQL that causes the failure:
exec sp_executesql N'DELETE [dbo].[Product] WHERE ([ProductID] = #0)',N'#0 int',#0=620895
Full error statement:
Msg 121, Level 15, State 1, Procedure t_del_Product, Line 8 The select
list for the INSERT statement contains more items than the insert
list. The number of SELECT values must match the number of INSERT
columns.
Other similar Removes work just fine. My EDMX is fully updated against the DataSource (SQL Server 2012)
Any ideas? Anyone? Anyone?
Thanks!
UPDATE: I should have tried this earlier, but I get the same error even with a simple:
DELETE FROM Product Where ProductID = 620895
So, it is not EF.
As mentioned in my comment:
It looks like the sp is being called (possibly) when a delete occurs on dbo.Product and is producing your error. Just look on the table and see if there are triggers defined on it.
If indeed there is a trigger on the table calling this SP, then this is likely your issue and you should look into fixing the SP.
I'm trying to get the last inserted id out of the database. I've tried many different code snippets but still having no luck. Here's the code I'm using for the inserts. I need the last insert id from the first to insert as nId in the second. I've tried SELECT ##IDENTITY but null value errors appeared which I couldn't locate. Can anybody show me the correct code please?
// Insert new user
daUsers.Insert(textBoxUsername.Text, textBoxPassword.Text);
// Insert new Twitter OAuth
daTwitterOAuth.Insert(nId, textBoxConsumerKey.Text, textBoxConsumerSecret.Text, textBoxToken.Text, textBoxTokenSecret.Text);
If you're trying to add a new record, you should be calling TableAdapter.Insert, not TableAdapter.Update
You can't create a second command to the database and use ##IDENTITY to get back the ID that was previously generated... this has to be returned within the same session, otherwise SQL would have no idea which ID you are expecting to receive.
If you set the execute mode of the table adapter to scalar, then the ID will be the return value of the method call. Please see this Question and Answer on the same issue that you're experiencing.
Someone has mentioned ##Identity which is fine, but what if somebody else performs an insert elsewhere before you reach that line in SQL?
I'd do this.
Create Procedure [Proc]
#Id as int output = 0
as
Insert into Table
Select * from AnotherTable
SET #Id = (SELECT Scope_Identity)
Then in .NET add your output parameter.
Been there already! In the code above I'm using an insert method, changed the execute mode to scalar and this is my sql:
INSERT INTO [dbTblUsers]([strUsername], [strPassword])
VALUES (#p1,#p2);
SELECT ##IDENTITY;
How do I cast ##identity into an int? Like this?
nId = (int)daUsers.InsertQuery(textBoxUsername.Text, textBoxPassword.Text);
I insert a value / new row and I need the ID, but I get an error...
SQL code:
INSERT INTO [StoneTable] ([StoneName]) VALUES (#StoneName)
SELECT SCOPE_IDENTITY()
Using this code to insert row and getting the ID:
stoneTableTableAdapter = new StoneTableTabelleTableAdapter();
int id = Convert.ToInt32(stoneTableTableAdapter.InsertStoneNameAndReturnId("anything"));
//And on this 2nd Line I got an error
Error message:
There was an error parsing the query. [ Token line number = 2,Token line offset = 1,Token in error = SELECT ]
What's the problem? In my other project I use the same syntax, with no problems. Tried with ##IDENTITY, as well not working....
See the answer to this question for a suggestion on how to make your example work:
You should change your INSERT to return that inserted ID to you right away (in an OUTPUT clause)
You can only issue a single statement per batch in SQL Server Compact, and you cannot use Scope_identity, but must use ##IDENTITY (remember to keep the connection open betweeen the two calls)