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)
Related
I'm having a very strange issue. I have windows service which is failing because of a SqlException: "String or binary data would be truncated." for an INSERT statement.
Now this is a fairly basic error to solve but it is not the true error. If I do a trace and run the query straight on the database - there is NO error. All of the data in WAY shorter than the restrictions on the database.
I eventually took out some of this required columns from the query hoping to generate a different error: "Cannot insert the value NULL into column 'Type'"
I don't however get this error! I am still getting "String or binary data would be truncated."
I DO get this error if I run the query from the trace straight on the DB.
Does anyone have any ideas on what could be happening here? Thanks!
Edit to add
Here's the query that is supposed to give me the cannot insert value error. The other query is the same but with more parameters:
declare #p4 int
set #p4=60029550
exec sp_executesql N'EXECUTE ssl_GetTTDVersionCallSeq 1, #TTDVersionIDVal OUTPUT
INSERT INTO TTDVersion(Task,ID) VALUES (#P0,#TTDVersionIDVal)',N'#P0 int,#TTDVersionIDVal int output',#P0=200003762,#TTDVersionIDVal=#p4 output
select #p4
Found the cause of this error. It was not at all in the query posted above. There was a trigger on the table which set the LastUpdatedBy column.
Most of the users have a 4 char user name but the user that the service was being run as didn't. The column limit was 4.
Avoid this issue:
Triggers can be problematic. They aren't immediately visible - sp_help 'table' doesn't even return them. If they error you can't even trace the query.
What I should of tried earlier:
Running the query as the user. (I wanted to but it's an admin user and someone else was using it at the time.)
Checking all columns info vs what was in them and what was in the query. Then to check how that info is getting there. In this case a default constraint probably would of given same issue.
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 make my first LINQ with asp website so I built a database with one table and I made a stored procedure which selects from this table by the id here it is :
ALTER PROCEDURE select_article_by_id
#artcileid int
AS
select * from articles where artcileid=#artcileid
RETURN
then I dragged and droped it into my DataClasses.dbml
when I run the website this problem appear
An invalid data source is being used for articleDL.
A valid data source must implement either IListSource or IEnumerable.
and gives me this sorce Error :
Line 16: string art_id = Request.QueryString["art_id"];
Line 17: if (art_id != null)
Line 18: articleDL.DataSource = DS.select_article_by_id(int.Parse(art_id)).Single();
Line 19:
Line 20: else
You're setting the data source accordingly:
articleDL.DataSource = DS.select_article_by_id(int.Parse(art_id)).Single();
By using .Single(), you are taking the one and only record returned by select_article_by_id and trying to make that single record the data source. It's telling you that's not allowed.
A list implements IEnumerable, which it's telling you is allowed. A single record does not implement IEnumerable, which it's telling you is not allowed.
Try replacing .Single() with .ToList().
ALTER PROCEDURE select_article_by_id
#artcileid int
AS
BEGIN
SET NOCOUNT ON; --<-- to suppress the message like "(100 row(s) affected)"
select * from articles where artcileid=#artcileid
END
Also you dont need the return key word here.
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);
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.