Hi all i'm trying to get the identity field after inserting into db, what am i doing wrong? thanks a lot
my sproc:
CREATE PROCEDURE ng_AddCotacao
(
...
@Codigo_cotacao int OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO
Negocios_cotacoes
(
...
)
VALUES
(
...
)
SELECT @Codigo_cotacao=SCOPE_IDENTITY()
SET NOCOUNT OFF
END
GO
class file
public class Cotacoes
{
public int codigoCotacao;
}
public class CotacaoAtualiza
{
public Cotacoes cotacoes = new Cotacoes();
public CotacaoAtualiza()
{
}
public void AdicionarCotacao(
...
)
{
SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["stringConexao"]);
SqlCommand myCommand = new SqlCommand("ng_AddCotacao", myConnection);
Hello, I have a C# application that adds records to a SQL Server database using a query something like this one:
INSERT INTO table_name (first_name, last_name, date_added) ('john', 'smith', '1/1/2005 12:00:00pm') ; SELECT SCOPE_IDENTITY() AS [Scope_Identity]
This works fine unless there's already a John Smith in the database. When that happens, Scope_Identity is null even though the date_added is different. About half the time the record is added even though Scope_Identity is null. I've added code to notify me when this happens, but it's a pain in the neck to re-run my import utility for individual records.
(The table I'm adding to does have a autonumbered key field)
While I have learned a lot from this thread I am still basically confused about the issues involved.
.I wanted to INSERT a record in a parent table, get the Identity back and use it in a child table. Seems simple.
To my knowledge, mine would be the only process running that would update these tables. I was told that there is no guarantee, because the OLEDB provider could write the second destination row before the first, that the proper parent-child relationship would be generated as expected. It was recommended that I create my own variable in memory to hold the Identity value and use that in my SSIS package.
1. A simple example SSIS .dts example illustrating the approach of using a variable for identity would be helpful.
2. Suppose I actually had two processes updating these tables, running at the same time. Then it seems the "variable" method will also have its problems. Is there a final solution other than locking the tables involved prior to updating them or doing something crazy like using a GUID for the primary key!
3. We have done the type of parent-child inserts I originally described from t-sql for years without any apparent problems. (Maybe we were just lucky.) Is the entire issue simply a t-sql one or does SSIS add a layer of complexity beyond t-sql that needs to be addressed?
I want to insert a new record into a table with an Identity field and return the new Identify field value back to the data stream (for later insertion as a foreign key in another table).
What is the most direct way to do this in SSIS?
TIA,
barkingdog
P.S. Or should I pass the identity value back in a variable and not make it part of the data stream?
I'm trying to return the identity from a stored procedure but am getting the error - "specified cast is invalid" when calling my function. Here is my stored procedure - ALTER Procedure TM_addTalentInvite @TalentID INT AS Insert INTO TM_TalentInvites ( TalentID ) Values ( @TalentID ) SELECT @@IDENTITY AS TalentInviteID RETURN @@IDENTITY
And here is my function - public static int addTalentInvite(int talentID) { // Initialize SPROCstring connectString = "Data Source=bla bla"; SqlConnection conn = new SqlConnection(connectString);SqlCommand cmd = new SqlCommand("TM_addTalentInvite", conn); cmd.CommandType = CommandType.StoredProcedure; // Update Parameterscmd.Parameters.AddWithValue("@TalentID", talentID); conn.Open();int talentUnique = (int)cmd.ExecuteScalar(); conn.Close();return talentUnique; } Any help you can give me will be greatly appreciated thanks!
I have a stored procedure that inserts a record. I call the @@Identity variable and assign that to a variable in my SQL statement in my asp.net page.
That all worked fine when i did it just like that. Now I'm using a new stored procedure that inserts records into 3 tables successively, and the value of the @@Identity field is no longer being returned.
As you can see below, since I don't want the identity field value of the 2 latter records, I call for that value immediately after the first insert. I then use the value to populate the other 2 tables. I just can't figure out why the value is not being returned to my asp.net application. Think there's something wrong with the SP or no?
When I pass the value of the TicketID variable to a text field after the insert, it gives me "@TicketID".
Hello all,I have a sqldatasource that inserts data to the database but I want to get the ID from an Identity field after I am done inserting the data. How can I best do that? I'm not using a stored procedure to do this. <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:onepduConnectionString %>" InsertCommand="INSERT INTO [tblaccounts] ([fname],[lname], [address], [city], [state], [zip], ,[phone],[credits]) VALUES (@fName,@lname, @address, @city, @state, @zip, @email, @phone, @credits)> <InsertParameters> <asp:FormParameter Name="fname" FormField="FirstNameTextBox" Type="String" /> <asp:FormParameter Name="lname" FormField="LastNameTextBox" Type="String" /> <asp:FormParameter Name="address" FormField="AddressTextBox" Type="String" /> <asp:FormParameter FormField="cityTextBox" Name="city" Type="String" /> <asp:FormParameter FormField="stateTextBox" Name="state" Type="String" /> <asp:FormParameter FormField="zipTextBox" Name="zip" Type="String" /> <asp:FormParameter FormField="emailTextBox" Name="email" Type="string" /> <asp:FormParameter FormField="phoneTextBox" Name="phone" Type="string" /> <asp:Parameter Name="credits" DefaultValue=0 /> </InsertParameters> </asp:SqlDataSource>
Hi All: I have what I'm sure is a common scenario...I have a table to track pageviews of a form, and which also tracks when a person viewing the form submits it. The table has three fields: an INT identity/PK field, a DATETIME (default getdate()) field, and a BIT field with default "false". When the page is viewed, I insert a record into the dB: Protected Sub Page_load(ByVal src As Object, ByVal e As EventArgs)
conn = New SqlConnection("Server=myserver;Database=mydb;User ID=user;Password=password;Trusted_Connection=false;") If Not IsPostBack Then AddTrack() End If End Sub Sub AddTrack()
Dim myCommand As SqlCommand Dim insertTrack As String insertTrack = "Insert PageTracker (submitted) Values (0)"myCommand = New SqlCommand(insertTrack, conn) myCommand.Connection.Open() Try myCommand.ExecuteNonQuery()tempTxt.Text = "<br>Ticked</b><br>" & insertTrack Catch ex As SqlException tempTxt.Text = ex.Number.ToString()
End Try myCommand.Connection.Close() End Sub And if I view the page, the record is inserted into the table. But now I need to know the value of the identity field, so when the form is submitted, I can update the field "submitted" from "0" to "1". The way I would do it in ASP is to add a "SELECT @@identity" to the query, and get the value using RS.nextrecordset. How would I do this in .NET? or is there a better way for me to do this?
I am currently using IDENT_CURRENT to return the Id of a new row in SQL 2000, but I am looking for a similar way to do this in SQL 7. Ihave no experience with SQL 7
I am inserting a record by calling a stored procedure in my asp.net code. I need to return the identity field from the insert to use elsewhere in my code. I have found many things regarding this but nothing has worked.
Here is the last part of my stored procedure. BTW, I have added Scope_Identity to the end of my sp and when I open my sp up, it is not there...not sure what that is about. I guess my main problem is what command do I use in ASP.net to execute the sp AND hold my returned value...
I have a table tblnetwork on which identity property is defined on column networkid.
When I issue the following command new record is getting inserted into tblnetwork and identity column is getting incremented properly. But, I am not able to get the @@identity value It is returned as NULL.
I have a createStudent SProc. When this is called it calls a createContact SProc. This in turn calls a Create Address Stored procedure. Now when I create the address, an Identity column automatically creates a new Identity for me. I need to return this value back to the calling stored procedure. I know how to return a value and all, however, how to I get the identity just entered (the corresponding identity) reliably? I know that select MAX <Identity> could suffice in this case, but is flawed as if someone was to add another object near the same time we could get the wrong identity returned...
I am storing product information in a SQL Server database table; the product information has no unique fields so I have created an Identity field called ‘uid’. Is there a way of querying the table to find out what value will be given to the next ‘uid’ field before the next record is written to the table? I need to use this as a FK in other tables.
i recently found a little error in a stored procedure that was included in a project handed over to me....
the sp was rather simple. it just inserted a record into a table and returned the identity and the timestamp as follows
IF @@ERROR>0 BEGIN SELECT @int_InterventionID = 0 RETURN @@ERROR END ELSE BEGIN SELECT @int_InterventionIDReturned = MAX(InterventionID) FROM tblIntervention SELECT @ts_TimestampReturned = [Timestamp] FROM tblIntervention WHERE InterventionID = @int_InterventionIDReturned SELECT @int_InterventionID = @int_InterventionIDReturned, @ts_Timestamp = @ts_TimestampReturned RETURN 0 END
i figured that it should be using @@Identity for the interventionIdentity rather than max(InterventionID)
so i changed to...
IF @@ERROR>0 BEGIN SELECT @int_InterventionID = 0 RETURN @@ERROR END ELSE BEGIN SELECT @int_InterventionIDReturned = @@IDENTITY SELECT @ts_TimestampReturned = [Timestamp] FROM tblIntervention WHERE InterventionID = @int_InterventionIDReturned SELECT @int_InterventionID = @int_InterventionIDReturned, @ts_Timestamp = @ts_TimestampReturned RETURN 0 END
it returns the @int_InterventionIDReturned but the timestamp now comes back as null??? why??
how can i ensure that i always get the timestamp of the record it has just inserted
I have a table with an integer field (contains test values like 2, 7,8,9,12,..) that I want to convert to an Identity field. How can this be done in t-sql?
I have a table named PERSON and a field named PERSON_ID. How can I set this field to Autonumber? I know I have to use the IDENTITY command, but when I view this field in "design" view, all the IDENTITY options are grayed out.
How can I set this field with the IDENTITY properties?
I want to get a count of how many PosAnswer are associated with the QuesToAsk 'List your top 5 favorite places'
This is the syntax I am using to achieve this, and it works, but wasn't sure if there was a better way (changing the data structure is unfortunately not an option in this situation). Here is my table structure
Code: Create Table Test ( QuesToAsk varchar(1000), PosAnswer varchar(1000)
[Code] ....
And this is the syntax I use to get the count I am after
Code: DECLARE @VariableName varchar(25) DECLARE @FormattedVariableName varchar(25) DECLARE @FieldCount int SET @VariableName =
(CASE WHEN (rtrim(crop) = '010' OR rtrim(crop) = '010W' OR rtrim(crop) = '019' OR rtrim(crop) = '019W' OR rtrim(crop) = '018') THEN 'CORN' WHEN (rtrim(crop) = '0150' OR rtrim(crop) = '0159' OR rtrim(crop) = '0150W' OR rtrim(crop) = '159W' OR rtrim(crop) = '158') THEN 'RICE' ELSE '' END) AS Product, TestStartDate, TestEndDate, ObsString FROM V_LAB WHERE (LotNo >= @lotStart) AND (LotNo <= @lotEnd)
If I run this query and filled the lotStart and lotEnd parameter with: G0424MK Then, below's the data returned. (I run the query in management studio)
010W
30A97-CLN-UNT-BULK
G0424MK
IDPMLG01
AFTER CLEANER
4982
PRCT MOIST
10.35
CORN
NULL
010W
30A97-CLN-UNT-BULK
G0424MK
IDPMLG01
AFTER CLEANER
4982
PRCT GOOD
97.5
CORN
NULL
010W
30A97-CLN-UNT-BULK
G0424MK
IDPMLG01
AFTER CLEANER
4982
PRCENTMEAN
97.75
CORN
NULL
I'd only going to retrive 3 data that i'd like to show on the report: 1. Moisture Content, with formula: =IIf(RTRIM(Fields!ObsDetail.Value) = "PRCT MOIST", Fields!ObsValue.Value, cdec(0.00)) the ObsValue value after i run on the report preview with LotStart and LotEnd G0424MK is: 10.35 (this is correct)
<!--[if !supportLists]-->2. Physical Damage, with formula: =Iif(rtrim(Fields!ObsDetail.Value) = "PRCT GOOD", Fields!ObsValue.Value, cdec(0.00)) the ObsValue value after i run on the report preview with LotStart and LotEnd G0424MK sebesar: 97.50 (this is correct)
Hi there ; This Problem is goin to make me crazy! I've got a table with couple of fields, 2 of them are DateTime, in Sql Express 05 . I used asp.net 2.0 to insert datetime values, directly, using sth like DateTime.Now.ToString() . i use 2 selects as follows : 1)select * from X where Date1='8/9/2006 11:17:41 AM' 2)select * from X where Date2='8/9/2006 11:17:41 AM' #1 is OK, but the second one returns a row with all columns set to NULL . (X is the name of the table) Thanks in advance
We currently have an SQL db running on a web server.One of these fields is a large(ish) amount of text data – up to 400characters – and has been cast variously as varchar, nchar and texttype to overcome a problem. The problem appears to be in retrievingthe data via ASP. I understand that ASP can handle string data of thissize so I am okay there.When the records are retrieved from the db, the data string length =0.I know the data is there because I have written a Delphi data managerwhich interrogates the db and shows all records and their contents.So if ASP can handle strings this size and the data is there, why do Iget a data length of zero bytes returned when I interrogate the recordset?Whichever way I cast this field I get the same result.I know the code is sound as it works locally through a MS SQL serveron my PS.Anyone have this problem or know what's causing it? I have logged asupport call with my hosting company, but they haven't replied as yetand I am stuck on an urgent project.Any suggestions?CheersGrant
I have a .NET program that can connect to either an Access 97 database or anSQL Server 7 database. In the database I have two tables which have a fieldcalled ID. When I run a query like "SELECT A.*, B.* FROM A, B", the queryreturns those fields as "A.ID" and "B.ID" when connected to Access 97, butas "ID" and "ID" in SQL Server 7. Is there anyway to get SQL Server toprepend the table name to the field name in a case like this and not returnduplicate field names like that without having to specify aliases for thefields?- Don
Hi, not too swift with anything other than simple SQL statements, soI'm looking for some help.Using SQL Server 2000 with this stored proc:(@varCust varchar(50))ASSET NOCOUNT ONSELECT d.WorkOrder, d.Customer, d.SerialNo, d.Assy, d.Station,d.WIdoc,d.Start, d.StartUser, d.Finish, d.FinishUserFROM tblWorkOrder w, tblDocs dWHERE w.WorkOrder IS NULL AND w.WorkOrder = d.WorkOrder ANDd.Customer = @varCustGOI'm trying to get a complete dataset so I can simply apply it as thedatasource to a datagrid in asp.net. I need to include a 'TimeSpan'column that is the difference between d.Start and d.Finish. I alsoneed it to present in hh:mm:ss format in the datagrid column. (A) isit possible to do this within the stored proc, and (B) how would "I"do that?Thanks!Kathy
hi friends,i have an identity column in my table.(e.x : id )and it's identity increment is 1.when i insert a row the id field is 1, and in next record the field is 2.....now , i delete second record(id=2)and now when i insert a record again , the id column is 3.i want to record be 2 instead 3.plz help me.thanks
Hi: I created a small SQL Express database/ASP.net/C# application and in the learning process. Before I implement it I would like to re-set autonumber / identity field back to 1. Also, I need to start with the blank database. I am not sure how to approach that? Can you assist? Thanks
Hello friends, I had created a web application and uploaded the application. Now the problem is with the DB. I had created the DB on the server (using script). But the fields that have identity field yes is not been set Now how I can set the fields identity field to yes. Fields are already there. Only I want to set there identity field to yes.Let me know how this can be done. Thanks & RegardsGirish Nehte
Please, How can I get the value of the identity field of the register that I was including in the data base. I am using a stored procedure in SQLSERVER in a asp .net application and I need to show that for the user, it´s like the number of the reclamation.
If my table has an IDENTITY field, say, the table schema is: CREATE TABLE BBB( id int NOT NULL IDENTITY(1,1), name varchar(20), job varchar(40)) My data file, which does not carry the IDENTITY field and its field terminator. The data file looks like this:
debbie cao,programmer John Doe,engineer Mary Smith,consultant
I tried to use a format file to bulk copy data from the data file to the table. Never had any luck. On the other hand, if I put a comma before the name field, say, the data file looks like the following:
then, bcp works fine. But, my data file is automatically generated. It does not suppose to have the leading comma. Without the leading comma, I have no idea how may I make bcp work. The SQLBOL says it can be done. Does anybody have an example to show me? Please help, thanks!
We are experiencing an identity problem on a table with 3.7 millions rows of data in the table. The identity field is not auto numbering any more and are wondering if anyone has a suggestion on how to get the auto number field working again without doing a bcp and restoring the table back to the database from bcp. Any suggestions?
Having an unusual problem - have created several (20) tables in a database. All of these tables have an identity field in them (defined as FIELDNAME int IDENTITY(1,1) NOT NULL ). In most of the tables this works as expected, but in 2, so far, when I do the first load (an insert based on a different database) the identity fields are all zero. Have recreated the tables, changed the field name and location, etc. Anyone have any clues ?