I would appreciate help with retriving the ID of the last record inserted. Have spent considerable time in forums and google but can't find anything that works for me.
Here is my VB Code
Dim queryString As String = "INSERT INTO [DUALML] ([UseriD], [Company]) VALUES (@UseriD, @Company)"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection
Dim dbParam_useriD As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_useriD.ParameterName = "@UseriD"
dbParam_useriD.Value = useriD
dbParam_useriD.DbType = System.Data.DbType.Int32
dbCommand.Parameters.Add(dbParam_useriD)
Dim dbParam_company As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_company.ParameterName = "@Company"
dbParam_company.Value = company
dbParam_company.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_company)
Dim rowsAffected As Integer = 0
dbConnection.Open
Try
rowsAffected = dbCommand.ExecuteNonQuery
Finally
dbConnection.Close
End Try
is there any way of getting the identity without using the "@@idemtity" in sql??? I'm trying to use the inserted event of ObjectDataSource, with Outputparameters, can anybody help me???
I have a table with the following structure in sql server 2005
create table app( sno int, name varchar(50), add varchar(50), city varchar(50), state varchar(50) )
it contains the follwing data ------------------------------------------ sno name add city state ------------------------------------------ 1 mark street no1 newcity newstate 2 mark street no1 newcity newstate 3 mark street no1 newcity newstate 4 mark street no1 newcity newstate 5 mark street no1 newcity newstate 6 mark street no1 newcity newstate 7 mark street no1 newcity newstate 8 mark street no1 newcity newstate 9 mark street no1 newcity newstate 10 mark street no1 newcity newstate 11 mark street no1 newcity newstate 12 mark street no1 newcity newstate 13 mark street no1 newcity newstate 14 mark street no1 newcity newstate 15 mark street no1 newcity newstate 16 mark street no1 newcity newstate 17 mark street no1 newcity newstate 18 mark street no1 newcity newstate 19 mark street no1 newcity newstate 20 mark street no1 newcity newstate
----------------------------------------
I want to retrive previous 5 records, next 5 records and the record that meet the where condition of a select query.
When I run
select sno,add,name,city,state from app where sno=7
I want the following result
------------------------------------------ sno name add city state ------------------------------------------ 2 mark street no1 newcity newstate | 3 mark street no1 newcity newstate | 4 mark street no1 newcity newstate | -- previous 5 records 5 mark street no1 newcity newstate | 6 mark street no1 newcity newstate | 7 mark street no1 newcity newstate --- searched record 8 mark street no1 newcity newstate | 9 mark street no1 newcity newstate | 10 mark street no1 newcity newstate |--- next 5 records 11 mark street no1 newcity newstate | 12 mark street no1 newcity newstate | ----------------------------------------
if there is a method to get the above result set, kindly post the query.
I've seen a lot of info on how to do this with @@IDENTITY and SCOPE_IDENTITY(), but can't get this to work in my situation. I am inserting a record into a table. The first field is a GUID (UNIQUEIDENTIFIER) that uses newid() to generate a unique GUID. Since I am not using an int, I can't set the IsIdentity property of the field. Without IsIdentity set, @@IDENTITY and SCOPE_IDENTITY() do not work. How can I get the ID (or whole record) of the last record that I inserted into a SQL database? Note that I am doing this in C#. As a last resort, I could generatate the GUID myself before the insert, but I can't find C# code on how to to this.
Hello,I would like do an insert into a table. The table has an autoincrimenting unique int id. After I do the insert how do i get theunique int id of the record that I just inserted? Is there a straightforward way of accomplishing this?Thanks,Billy
Ok I know this might not be the most accurate place to post this but I know someone here has an answer for me on it.I need to get the product_ID of the new record that is created by this insert statement INSERTINTO products ( class_ID,category_ID,product_name,product_desc,product_image,product_dimension,product_o1,product_o2,product_o3,product_ac,product_ph,product_photo ) SELECT class_ID,category_ID,product_name,product_desc,product_image,product_dimension,product_o1,product_o2,product_o3,product_ac,product_ph,product_photo FROM productsWHERE product_ID = @productID
Hi EverybodyThis Code duplicate the record in the database, can somebody help me understand why that happen. Thanks a LOT CompanyName: <asp:textbox id="txtCompanyName" runat="server" /><br />Phone:<asp:textbox id="txtPhone" runat="server" /><br /><br /><asp:button id="btnSubmit" runat="server" text="Submit" onclick="btnSubmit_Click" /><asp:sqldatasource id="SqlDataSource1" runat="server" connectionstring="<%$ ConnectionStrings:dsn %>" insertcommand="INSERT INTO [items] ([smId], [iTitleSP]) VALUES (@CompanyName, @Phone)" selectcommand="SELECT * FROM [items]"> <insertparameters> <asp:controlparameter controlid="txtCompanyName" name="CompanyName" /> <asp:controlparameter controlid="txtPhone" name="Phone" /> </insertparameters></asp:sqldatasource> VBPartial Class Default2 Inherits System.Web.UI.Page Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click SqlDataSource1.Insert() End SubEnd Class ----------------------------------------------Yes is an Identity the Primary Key of the Table items
I am using VS.net (2003) SQLcommand TEXT. with input params. SQL server 2000
Can anyone tell me how to get the Identity value (field value, Idenity col) when you do an insert? I want to get the Identity value, then redirect the user to another page and use this identity value so they can update more (other) fields that are on that page.
My code so far that works... but Where do I put @@IDENTITY ? How do I call or assign the @@IDENTITY value to a value in my aspx.vb code page?
Question: how do I get the Identity value from the ID column. Question: How do I assign that value to some variable in code, say, assign it to (Session("App_ID")) = IdentityValueOrSomething?Help... --------------------- INSERT INTO App (AppName, Acronym, Description,bla bla bla bla........) VALUES (@AppName, @Acronym, @Description, bla bla bla bla........)
-----------------------------
Private Sub btnAddApp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddApp.Click With cmdAddApp '.Parameters("@app_id").Value = Session("App_ID") .Parameters("@AppName").Value = txtAppName.Text .Parameters( bla bla bla............. .Parameters( bla bla bla............. .Parameters( bla bla bla.............
End With Try cnAppKBdata.Open() cmdAddApp.ExecuteNonQuery() cnAppKBdata.Close() ''''''''''''''Session("App_ID") = whatever the @@IDENTITY is....'''''''''''''''''''''''''''?? Response.Redirect("AppUpdate.asp") Catch ex As Exception
I have a table named invoice that contains the following columns-invoiceno - Primary key and is set to autonumber-customerno-incoicedateand on my VB code i did the following InsertCommandSqlDataSource1.InsertCommand = "INSERT INTO invoice(customerno, invoicedate) VALUES('" & Session("UID") & "', GetDate()) "SqlDataSource1.Insert()My Question is how do i get the Primary Key Value it generated during the insert operation(invoice['incoiceno'])? Besides the creationg a stored procedere like the one in the MSDN Library
Is it possible to retrieve the user name or host name of the user that inserted or updated a particular record? Is this information stored in the database's log file, in hidden fields, or anywhere else? I know I can easily add a user_name field and use triggers to add this information for new records, but I need this information for records already existing in the table. Thanks.
Hi All, i have a database, and every time when any row enter , it capture the date and time of insertation, then does any function or query available, which help to investigate me, today inserted record,yesterday inserted record,last 7 days inserted record,last 30 days inserted record and last year inserted record.. i am using asp.net and MS Access... Any idea thanx in advance... sajjad
There are loads of postings on the net about this problem but none I have found explain the cause. Whenever returning a value from a TableAdapter.Insert method followed by a SELECT SCOPE_IDENTITY() , the value returned is always 1. I have run the same select in SQL management studion and the correct value is returned but with a 1 showing in the column selector (just to the left of the first column. The column selector column is not data column. This must be the reason that issuing a SELECT after an INSERT does not work when using a TableAdapter isert method. Has anyone come across the solution for this issue? Thanks
Hi, I have 2 tables in my database PrescriptionHeader and PrescriptionDetails.My PrescriptionHeader table has the following fields:PrescriptionID -identity fieldPatientID PatientfNamePatientlname PrescriptionDetails table has the following fields:PrescriptionDetailID -identityPrescriptionID -from PrescriptionHeader table MedicineDosage The function InsertPrescription inserts values into the table PrescriptionHeader. I want the same function to then insert the value of MedicineDosage into PrescriptionDetails with the same PrescriptionID inserted into PrescriptionHeader. How do I tell the function to insert the PrescriptionID that was automatically inserted into PrescriptionHeader also into table PrescriptionDetails . How do I return the identity before proceeding to insert into PrescriptionDetails table?ThanksFunction InsertPrescription(ByVal PatientID As String, _ByVal PatientFname As String, _ByVal Patientlname As String, ByVal MedicineDosage as String)Dim DBAdapter As SqlDataAdapterDim DBDataSet As DataSetDim SQLString As StringDim DBCommandBuilder As SqlCommandBuilderSQLString = "SELECT * FROM PrescriptionHeader WHERE PrescriptionId = ''"DBAdapter = New SqlDataAdapter(SQLString, DBConnection)DBDataSet = New DataSetDBAdapter.Fill(DBDataSet)Dim AddedRow As DataRow = DBDataSet.Tables(0).NewRow()AddedRow("PatientID") = PatientIDAddedRow("PatientfName") = PatientFnameAddedRow("Patientlname") = PatientlnameDBDataSet.Tables(0).Rows.Add(AddedRow)DBCommandBuilder = New SqlCommandBuilder(DBAdapter)DBAdapter.Update(DBDataSet) End Function
Hiwhen inserting records into a table one of the fields is a date field. I am using the GETDATE() function to insert the date as the record is being inserted.when i retrieve an entire record from the table i want to be able to select this date, but also to get the number of days it has been since that record was inserted.eg: 3 daysif the record was inserted less than one day ago (<24 hrs ago) i would like it to return the number of hours. e.g. 22 hrsi dont want hours to be displayed if the days is >= 1.please can anyone guide me with this?thanks!
1 Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click 2 Dim sqlStr As String 3 Dim sqlStr2 As String 4 Dim myConnection As MySqlConnection = Nothing 5 Dim myCommand As MySqlCommand = Nothing 6 Dim myConnection2 As MySqlConnection = Nothing 7 Dim myCommand2 As MySqlCommand = Nothing 8 Dim myReader As MySqlDataReader = Nothing 9 Dim IC As String 10 11 IC = txtIC1.Text + "-" + txtIC2.Text + "-" + txtIC3.Text 12 13 14 Try 15 sqlStr2 = "SELECT * FROM User WHERE uLogin='" & txtUserName.Text.Trim() & "'" 16 17 ' Connection 18 myConnection2 = New MySqlConnection(ConfigurationManager.ConnectionStrings("dbConnection").ToString()) 19 myConnection2.Open() 20 ' Command 21 myCommand2 = New MySqlCommand(sqlStr2, myConnection2) 22 ' Reader 23 myReader = myCommand2.ExecuteReader() 24 Catch ex As Exception 25 ' Exception Error Here 26 Response.Write(Err.Number & " - " & Err.Description) 27 28 End Try 29 ' Checking 30 If myReader.Read() Then 31 32 33 Label2.Text = "Username already exist. Please choose another username" 34 Label3.Text = "*" 35 36 Else 37 38 Try 39 40 41 sqlStr = "INSERT INTO userapplication(uaName,uaIC,) VALUE (?uName,?uIC )" 42 43 44 45 ' Connection 46 myConnection = New MySqlConnection(ConfigurationManager.ConnectionStrings("dbConnection").ToString()) 47 myConnection.Open() 48 'Command 49 myCommand = New MySqlCommand(sqlStr, myConnection) 50 51 myCommand.Parameters.AddWithValue("?uName", txtName.Text) 52 myCommand.Parameters.AddWithValue("?uIC", IC) 53 54 55 myCommand.ExecuteNonQuery() 56 myConnection.Close() 57 Response.Redirect("Register.aspx", False) 58 59 Catch ex As Exception 60 ' Exception Error Here 61 Response.Write(Err.Number & " - " & Err.Description) 62 Finally 63 ' Clean Up 64 If Not IsNothing(myCommand) Then 65 myCommand.Dispose() 66 End If 67 ' 68 If Not IsNothing(myConnection) Then 69 If myConnection.State = Data.ConnectionState.Open Then myConnection.Close() 70 myConnection.Dispose() 71 End If 72 End Try 73 74 75 End If 76 77 End Sub 78 79
above is my code for the user registration page.the code that i bold,which with number 55,56 and 57,are where the problem occur. when it run,it run 55, then 57,then back to 55, then 57 again means that my db hav duplicate record being insert anyone know how to solve this problem?
Hi I have an application which get any change from database using sql dependency. When a record is inserted or updated it will fire an event and my application get that event and perform required operation. On the event handler I am usin select ID,Name from my [table]; this will return all record from database. I just want to get the record which is inserted or updated. Can u help me in that. Take care Bye
Ok I've been researching this for a day now and I'm not coming up with much. I want to store the auto-incrementing ID of the last inserted record in a session variable, so that I may put it in a foreign key column in another table, if the user wishes to fill out a form on another page. I think my stored procedure is correct. But don't know what code to add to my aspx page. Any help will be greatly appreciated.
Here is my VB ScriptProtected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim personalContactDataSource As New SqlDataSource()personalContactDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("DataConnectionString1").ToString()
I am using this code to insert a record in my table where i have assigned a guid datatype field to generate an automatic guid for each record. but now i need to retrieve the guid to use it to send a confirmation email to the user.
Best way to retrieve the identity key of the record just inserted?This question is for discussion purposes; the business process that spurred the question is currently working.Using SQL Server 2008 R2, a record is inserted from a stored procedure. Let's say the sp has something like this:
Code: BEGIN BEGIN TRANSACTION INSERT INTO tblTools ([Desc],CreateDate,Model,CreatedBy,Notes)
[code]....
In Access, when you add a new record to the recordset, the identity field comes "pre-populated" making it east to get the actual, correct identity value assigned to the record you are inserting. In SQL Server, I know options include:
Code: IDENT_CURRENT('tblX') SCOPE_IDENTITY @@IDENTITY among other methods.
Each has pros and cons, such as user privileges (IDENT_CURRENT requires the user to have Select privileges on the table, and catches records created by other things, such as users and triggers), and the other two give you the last key inserted and don't allow specifying the object (which is a problem if the insert added records to multiple tables, or you have multiple inserts).
I am using ASP.NET 3.5 with SQLDataSource, when a record is inserted is there a way to retreive the newly created GUID value in a field? I am currently using SELECT @NewID = SCOPE_IDENTITY() to retreive the newly created record unique ID field, but I need the secondary field GUID field's value instead in this case. Thank you.
I'm calling the stored procedure below to insert a record but every record is inserted into my table twice. I can't figure out why. I'm using Sql Server 2000. Thanks.CREATE PROCEDURE sp_AddUserLog(@Username varchar(100),@IP varchar(50))AS SET NOCOUNT ONINSERT INTO TUserLogs (Username, IP) VALUES (@Username, @IP)GO Sub AddUserLog(ByVal Username As String) Dim SqlText As String Dim cmd As SqlCommand Dim strIPAddress As String
'Get the users IP address strIPAddress = Request.UserHostAddress
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString) SqlText = "sp_AddUserLog" cmd = New SqlCommand(SqlText) cmd.CommandType = CommandType.StoredProcedure cmd.Connection = con
Hi, I was wondering if anyone could offer me some advice. I am currently using a stored procedure to insert records into a database. I want to be able to retrieve the ID (primar key) from the item that has just been inserted using the stored procedure. The ID I want to get back is Meter_ID This is my stored procedure:ALTER PROCEDURE dbo.quote
We are getting data feed from Oracle database in our project. Everyday we will need to track if any rows got inserted/updated/deleted in the source and get that update right into our data warehouse.
Currently we are taking a dump of the required table (as it is) to our staging DB and comparing it with previous day data to track the changes (column by column comparison). This approach is working currently but has performance bottleneck. There is no tracking column (eg. last modified date or time) in source that will give us any idea of what got changed. Also there is no identity key or primary key in the source data.
Is there a way in SQL Server to get that inserted/updated records only instead of comparing column by column to track the changes?
I want to check a record in my table which has time ins and time outs feilds. I want to check on insertionof any new record that a new record should not be inserted on same timings and before 45 mins of timein and after 45 mins of timeout. How do i do it sql query ?
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
Greetings all, I am tring to capture the ID of a newly inserted record from a form to a label that I will reference in a reciept page. I intend to pass the rowid to retrieve record information on other pages. The insert suceeds... I just need to capture the auto generated ID for the new row to a label on the page post onclick. Any thoughts?
Dim MySQL As String = "Insert into dropkick (name, status, payroll, unit, contactnumber, email, equipment, issue, timein) values (@name, @status, @payroll, @unit, @contactnumber, @email, @equipment, @issue, @timein)"Dim myConn As SqlConnection = New SqlConnection(SqlDataSource1.ConnectionString) Dim Cmd As New SqlCommand(MySQL, myConn)Cmd.Parameters.Add(New SqlParameter("@payroll", txt_payroll.Text)) Cmd.Parameters.Add(New SqlParameter("@name", txt_name.Text))Cmd.Parameters.Add(New SqlParameter("@status", "W")) Cmd.Parameters.Add(New SqlParameter("@unit", txt_dept.Text))Cmd.Parameters.Add(New SqlParameter("@contactnumber", txt_cell.Text)) Cmd.Parameters.Add(New SqlParameter("@email", txt_email.Text))Cmd.Parameters.Add(New SqlParameter("@equipment", txt_equipment.Text)) Cmd.Parameters.Add(New SqlParameter("@issue", txt_issue.Text))Cmd.Parameters.Add(New SqlParameter("@timein", lbl_datetime.Text)) myConn.Open() Cmd.ExecuteNonQuery() Label1.Visible = "true" Page.DataBind() myConn.Close() Label1.Text = "Your data has been received!" ''LABEL TO BE POPULATED WITH ID OF NEW RECORD lbl_id.Text = ID
I am using SQL Express database and where can I set the default value to my Data field to auto insert the current date-time value? I tried to find the setting but can't seem to find it. Any help is much appriciated. Thanks in advance.
Dear all, I am using C# , asp.net and sql server 2005. Let me explain the situation. I have written procedure to insert data into the table and return last inserted value by @@identity variable. Now my question is how do I execute this process so that I can Get last inserted variable values Please help thanks
My goal is to update the "PriorInsert" field with the "DateInserted" from the previously inserted record where the WorkOrder, MachineNo, and Operator are all in the same group.
While trying to get to the correct previous record, I wrote the query below.
P.S. The attached .txt file includes a create and insert tbl_tmp sampling.
select top 1 a.ID, a.WorkOrder, a.MachineNo, a.Operator, a.PriorInsert,
I have two different SQL 2008 servers, I don't have permission to create a linked server in any of them. i created a trigger on server1.table1 to insert the same record to the remote server server2.table1 using OPENROWSET
i created a stored procedure to insert this record, and i have no issue when i execute the stored procedure. it insert the recored into the remote server.
The problem is when i call the stored procedure from trigger, i get an error message.
Stored Procedure: USE [DB1] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON
[Code] ....
When i try to insert a new description value in the table i got the following error message:
No row was updated the data in row 1 was not committed Error source .Net SqlClient Data provider. Error Message: the operation could not be performed because OLE DB provider "SQLNCLI10" for linked server "(null)" returned message "The partner transaction manager has disabled its support for remote/network transaction.".
correct the errors entry or press ESC to cancel the change(s).