Insert When Using IDENTITY(1,1)

Jun 11, 2007

If I have my table setup like so...

CREATE TABLE Customer
(SID integer IDENTITY(1,1) PRIMARY KEY,
Last_Name varchar(30),
First_Name varchar(30));

How would I do an insert statement so that it auto increments and creates a unique number?

I keep getting errors.

View 4 Replies


ADVERTISEMENT

Last GASP On Insert Row In Table With Identity Field, And Get New Identity Back ?

Jul 9, 2006

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?



TIA,



Barkingdog

View 10 Replies View Related

Insert Row In Table With Identity Field, And Get New Identity Back

Jun 30, 2006

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?

View 12 Replies View Related

Problem In Using Sqlbulkcopy To Insert Data From Datatable(no Identity Column) Into Sql Server Table Having Identity Column

Jun 19, 2008

Hi,
I am having problem in bulk update of a sql server table haning identity column from a datatable( has no identity column) using sqlbulkcopy. I tried several approaches, but it does not show any error nor is the table getting updated. But the identity value seems to getting increased every time.
thanks.
varun

View 6 Replies View Related

How Do You Use An Identity Column When Doing A Bulk Insert Using The Bulk Insert Task Editor

Apr 18, 2008



Hello,

I'm just learning SSIS and I've hit my first bump. I am doing a bulk import from a tab delimited text file to an empty sql table that has a Idendity column defined. How do I tell the bulk insert task to skip that column when inserting from the text file. If I remove the identity column it imports the data fine, but I want to create the indentity column in the table too.

Thanks.

View 8 Replies View Related

Using Identity To Get The Last Insert

Nov 26, 2005

after i have inserted a row into the DB i am trying to get the last identity like this :
Dim myCommand2 As New SqlCommand("SELECT @@IDENTITY AS 'Identity'", )
Dim myReader2 As SqlDataReader
myReader2 = myCommand2.ExecuteReader()
where myConnection2 is the connection objectafter i did this i dont underdsand how do i get the 'Identity' value?i tried myReader2 ('Identity') but no luckany 1 can helpthnaks in advancepeleg

View 1 Replies View Related

Need Insert Cannot Use Identity

May 6, 2002

Let me start off by saying I have posted this on:
comp.databases.ms-sqlserver

My apologies, try not to do that again.

I have a table that I am trying to insert into with data from another
table. Here is that Query:

INSERT INTO item (identifier, name, customlgtxt1, weight,mainprice,
customnumber3, customnumber4)
Select partno, name, description, weight,price, qtyprice, qty
From Import2

This seems to work fine.

My dilemma has to do with an 'id' column in that item table. This is
incrementally updated by one..ie Natural Key. I have set it to
Identity and used Set @@IDENTITY AS 'id'...worked like a charm. But
for reasons that have to do with a front end admin tool used by the
home office I can't set this column to have an Indentity property.
Screws up the insert done with the admin tool.

This is a item/price database by the way. Name of item, price,
description, qty price..etc.

So I've tried to put this trigger on the item table
CREATE TRIGGER auto_fill ON [dbo].[item]
FOR INSERT, UPDATE
AS
BEGIN
declare @maxc int
set @maxc = (select Max(id) from item)
set @maxc = @maxc +1
Select 'id' AS '@maxc',
notorderable = '0',
createdon = getdate(),
createdat = getdate(),
createdby = 'Steve',
modifiedon = getdate(),
modifiedat= getdate(),
modifiedby = 'Steve'

END

But the Insert Into statement (see above) will not work...giving the
error
"Cannot insert the value NULL into column 'id', table
'new_Catalog1v1.dbo.item"
Which I know...that's why I set it to Identity..but that cannot be.

So the question is how to set an autonumber (or natural key or I'm not
sure of the name) that updated from the max(id)table when inserting from another table.

And then...one more.

I have to update a table named UNIQUEIDS with the lastest value of the
id column (max(ID))..UNIQUEIDS keeps track of the latest value inserted
into the id column for a number of tables. Here is another trigger I
put on the item table to update the UNIQUEIDS table.

create trigger upUniqueIds_item on [dbo].[item]
for update,Insert, delete
as
begin
Select @@Identity as 'id' from inserted
Update uniqueids
set id = @@identity
Where tablename = 'item'
End


But of course this doesn't work if I can't set the columns to
IDENTITY.

I hope someone can help and I hope my explanation had made sense.
Need to increment the id field using max(id) and update another table with the last imported value of max(id). One occurs during insert..another after the insert..i think?

View 1 Replies View Related

IDENTITY INSERT

Aug 27, 2002

I need to insert into a table that has an identity insert set to on.
I need to know how to turn it off while I insert data into the table.

Here is the senerio

column 1
1
2

View 2 Replies View Related

IDENTITY INSERT

Aug 27, 2002

I need to insert into a table that has an identity insert set to on.
I need to know how to turn it off while I insert data into the table.

Here is the senerio

column 1
1
2

View 1 Replies View Related

IDENTITY - Need To Be Able To Insert

Feb 22, 2001

Help!

I need to be able to insert into an Identity column and tried putting

SET IDENTITY_INSERT table ON

in a stored procedure , but it didn't like this if not dbo, which will be the case.

Is there anyway of globally making this setting and leaving it on permenantly

KB

View 1 Replies View Related

@@ Identity Insert

Dec 8, 2004

Is it possible to create a trigger that inserts the @@identity (primary key) from Table1 into a field in Table2?

If so, how? Thank you.
-D-

View 1 Replies View Related

INSERT @@identity At Once

Nov 10, 2006

Hi

how can I insert @@identity at once (for MS SQL 2000 / 2500)

INSERT INTO Table1 (name) VALUES ('any')

DECLARE @ID int SELECT @@Identity

INSERT INTO Table2 (id_Table1) VALUES (@ID)

does not work

thank you

View 8 Replies View Related

Insert Identity Id

Sep 7, 2007

hi all,

i have a question:
i have a table that has an identity id column called pId and also a column called ParentPid.
now my question is that i want to insert the value of pId into the ParentPid when i'm adding a new Property to a table.
any idea?
thanks

View 6 Replies View Related

Identity Insert

Apr 2, 2007

Hi All,

I tried enabling the IDENTIY_INSERT ON for 2 tabls in a database. It says that I cannot have 2 tables in a database with IDENTITY INSERT ON.

Why is this so?

Thanks,

Prakash.P

View 8 Replies View Related

IDENTITY INSERT ON

Feb 28, 2008



I have twoo tables Table A (Col1 int, Col2 varchar(10)) and Table B (Col1 Identity(1,1), Col2 varchar(10))

Table A has
1 ABC
2 XYZ
NULL JIM
NULL KIM
10 min

I want to insert this in Table B

Well I seperated teh data per the TableA.Col1 where if Null, Table B will generate its Col1

But how will I do it in SSIS when TableA.Col1 in NOT NULL.

How would I set the IDENTITY INSERT ON on Table B while Inserting through SSIS?

Please advice

View 1 Replies View Related

Retrieving Identity After Insert

Nov 14, 2006

Hey, I've been having problems - when trying to insert a new row i've been trying to get back the unique ID for that row. I've added "SELECT @MY_ID = SCOPE_IDENTITY();" to my query but I am unable get the data. If anyone has a better approach to this let me know because I am having lots of problems. Thanks,Lang 

View 2 Replies View Related

How To Get An Identity Value From An INSERT Statement

Feb 29, 2008

 I have 2 tables - tblOrders and tblOrderDetails. Every time an order is placed, 2 INSERT statements are executed. The first one enters the general order and customer information in the tblOrders table:INSERT INTO tblOrders (custname, custdetails, orderdate) VALUES (@custname, @custdetails, @orderdate)The primary key in this table is OrderID which is an Identity column. This is the foreign key in the tblOrderDetails table.I'm trying to get the Identity value from the first INSERT statement to use in the second INSERT statement:INSERT INTO tblOrderDetails (orderid, productid, productcost) VALUES (@orderid, @productid, @productcost)How do i obtain this value and how would I supply it to the second INSERT statement?

View 9 Replies View Related

Returning The Identity Value After Insert?

Apr 5, 2008

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?

View 6 Replies View Related

Retrieve Identity After Insert

Jun 1, 2006

I am a "newbie" and have been struggling with this for days!  I have users enter their residence information and insert which generates houseid.  I want to use/display that houseid on next page/step.  I am VERY FRUSTRATED and would appreciate any assistance!
<script runat="server">
Protected Sub SqlDataSource1_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles SqlDataSource1.Inserting
e.Command.Parameters("@house").Size = 5
End Sub

Protected Sub SqlDataSource1_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Inserted
Dim house = e.Command.Parameters("@house").Value
Response.Write(house)
End Sub
Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs)
End Sub
Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)

End Sub
</script>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:ic_registerConnectionString %>"
oninserted="SqlDataSource1_Inserted"
oninserting="SqlDataSource1_Inserting"
DeleteCommand="DELETE FROM [household] WHERE [householdid] = @original_householdid AND [housenum] = @original_housenum AND [streeraddr] = @original_streeraddr AND [aptnum] = @original_aptnum AND [city] = @original_city AND [state] = @original_state AND [zipcode] = @original_zipcode AND [HHPhone] = @original_HHPhone AND [timedate] = @original_timedate"
InsertCommand="INSERT INTO [household] ([housenum], [streeraddr], [aptnum], [city], [state], [zipcode], [HHPhone], [timedate]) VALUES (@housenum, @streeraddr, @aptnum, @city, @state, @zipcode, @HHPhone, { fn NOW() }); SELECT @house = SCOPE_IDENTITY()"
OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT * FROM [household]"
UpdateCommand="UPDATE [household] SET [housenum] = @housenum, [streeraddr] = @streeraddr, [aptnum] = @aptnum, [city] = @city, [state] = @state, [zipcode] = @zipcode, [HHPhone] = @HHPhone, [timedate] = @timedate WHERE [householdid] = @original_householdid AND [housenum] = @original_housenum AND [streeraddr] = @original_streeraddr AND [aptnum] = @original_aptnum AND [city] = @original_city AND [state] = @original_state AND [zipcode] = @original_zipcode AND [HHPhone] = @original_HHPhone AND [timedate] = @original_timedate" OnSelecting="SqlDataSource1_Selecting">
<InsertParameters>
<asp:Parameter Name="housenum" Type="String" />
<asp:Parameter Name="streeraddr" Type="String" />
<asp:Parameter Name="aptnum" Type="String" />
<asp:Parameter Name="city" Type="String" />
<asp:Parameter Name="state" Type="String" />
<asp:Parameter Name="zipcode" Type="String" />
<asp:Parameter Name="HHPhone" Type="String" />
<asp:Parameter Type = "String" Name="house" Direction= "Output"/>
</InsertParameters>
Next question is this easier to do using a Wizard Control and DetailsView on a "step" or using seperate pages and FormView? Or does it matter?

View 2 Replies View Related

How Do You Use A SP To Do An Insert And Return The Identity To ADO

Apr 12, 1999

I would like to use ADO in a new project but I need to find out how to return the identity field value to ADO out of a stored procedure. I have not done alot with ADO or with SQL 7.0 so if anyone has an example of the SQL and the ADO code that I would need I would greatly appriate it.

Thanks

View 1 Replies View Related

Turn Identity Off On Insert

Jun 3, 2005

Hi,

I'm nesting a bunch queries, the parent being a select, and the children being inserts. I'd like to retain the auto generated IDs from the original table, and insert them into the new tables (into identity fields). I believe that there is a command that I can use to temporarily turn identity auto numbering off for the current query - can anyone help me with this?

Cheers,

View 1 Replies View Related

How To Insert Identity Values

Oct 3, 2005

hi to the group,
i am small problem,
i am having two columns 1 is col1 which is a primary key and col2 any think .now i want to insert the data into second column at that time the first column must get the values in identity (like 1,2,3,4 etc)
with out using identity(sql server)/generated always(db2)
can any one knows please explain it

View 3 Replies View Related

How To Insert Into Identity Values

Oct 3, 2005

hi to the group,
i am small problem,
i am having two columns 1 is col1 which is a primary key and col2 any think .now i want to insert the data into second column at that time the first column must get the values in identity (like 1,2,3,4 etc)
with out using identity(sql server)/generated always(db2)
can any one knows please explain it
bye

View 1 Replies View Related

Insert Into A Table With Identity

Aug 31, 2006

I have 2 tables with same structure.only difference is, TableA has key colum which is declared as identity starting from 1.

I want to insert data from TableB into TableA where TableB.Key is all null with TableA.Key starting from 9000001

when i try to do that iam getting an error
"An explicit value for the identity column in table 'lEADlOAN' can only be specified when a column list is used and IDENTITY_INSERT is ON.
"
even when I turned IDENTITY_INSERT ON for TableA

View 4 Replies View Related

IDENTITY INSERT Error

Mar 8, 2007

Hey all, I have been working with Northwind on SQL Server Express
Trying to learn Transact-SQL. I am stuck at this point from code in the instruction manual. I don't know if I have a permission set to something that I need or what but I get the following error that is outlined at the bottom of the code. Any help would be appreciated.

USE Northwind
GO

ALTER PROC spInsertDateValidatedOrder
@CustomerIDnvarchar(5),
@EmployeeIDint,
@OrderDatedatetime= NULL,
@RequiredDatedatetime= NULL,
@ShippedDatedatetime= NULL,
@ShipViaint,
@Freightmoney,
@ShipNamenvarchar(60)= NULL,
@ShipAddressnvarchar(40)= NULL,
@ShipCitynvarchar(15)= NULL,
@ShipRegionnvarchar(15)= NULL,
@ShipPostalCodenvarchar(10)= NULL,
@ShipCountrynvarchar(15)= NULL,
@OrderIDintOUTPUT

AS


DECLARE @InsertedOrderDatesmalldatetime

--Test to see if supplied date is over seven days old. If so
--replace with NULL value otherwise, truncate the time to be midnight.

IF DATEDIFF(dd, @OrderDate, GETDATE()) > 7
BEGIN
SELECT @InsertedOrderDate = NULL
PRINT 'Invalid Order Date'
PRINT 'Supplied Order Date was greater than 7 days old'
PRINT 'The value has been reset to NULL'
END

ELSE

BEGIN
SELECT @InsertedOrderDate = CONVERT(datetime, (CONVERT(varchar,@OrderDate, 112)))
PRINT 'The Time of Day in Order Date was truncated'
END

--create the new record
INSERT INTO Orders
VALUES
(
@CustomerID,
@EmployeeID,
@InsertedOrderDate,
@RequiredDate,
@OrderDate,
@ShippedDate,
@ShipVia,
@Freight,
@ShipName,
@ShipAddress,
@ShipCity,
@ShipRegion,
@ShipPostalCode,
@ShipCountry
)

--Move the identity value from the newly inserted record into output variable.

SELECT @OrderID = @@IDENTITY


Errors received,
Msg 8101, Level 16, State 1, Procedure spInsertDateValidatedOrder, Line 46
An explicit value for the identity column in table 'Orders' can only be specified when a column list is used and IDENTITY_INSERT is ON.

Thanks

View 2 Replies View Related

Insert Into Identity Column

Sep 21, 2007

I have migrated my application from Access to sql 2005 express. In access autonumber (identity) field was random number.

fter conversion now i want identity field to be "increment". management studio does nt allow.
I have created a new database with increment identity column but during importing data using insert into statement it give error

Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF

please suggest how to do it??

View 11 Replies View Related

Cannot Insert Explicit Value For Identity...

Apr 24, 2006

I am developing an integration process between two databases. One ofthem is a SQL Server 2000 and the other is using MSDE 2000. Theintegration process is done in C# (VS2003).The main database is the SQL Server, the MSDE will contain a reallysmall subset of the data found on the main. To help diminish the amountof time taken to develop an integration process between thosedatabases, the same structure are found on both side. The onlydifference, when I insert data in the MSDE from the SQL Server, I setthe IDENTITY_INSERT to ON and use the same IDs found on the SQL Server.I can insert one set of data without problem, but from there, if I tryagain, I will always receive the "Cannot insert explicit value foridentity column in table ... when IDENTITY_INSERT is set to OFF." Isaw on Microsoft website the article ID 878501; I noticed I was usingMSDE sp3, I upgraded to SP4... and I still have the problem.I know, when I call the update function on the sqldataadapter, theadapters contain the IDENTITY_INSERT ON and it's set to OFF after theinsert. The "Cannot insert..." error is the only one I received.Can anyone help me on that issue? Take note that this approach wasused because of customer requirements; the size of the database alsocauses some problem (over 200 tables) and we decided to use the samestructure on both side to minimize the support time.

View 3 Replies View Related

Identity Insert Doubt

Jul 20, 2005

Hello,How do I get SQL server 2000 to continue the sequence of identitycolumn values after I perform an insert into the table with the setidentity_insert <table name> on statement? Eg if I insert values intothe identity column with values 1-999, how do I get the next number tobe 1000? Can the identity seed value be changed if there are records inthe table? Can the identity seed value be re-set to start again from 1?ThanksIsaac

View 3 Replies View Related

Insert Identity Value With SqlCeResultSet

Aug 20, 2007

Hi

I have a table with an identity column. This is set to increase by 1 and start on 1, and is the first column of the table.
When I insert a record into the resultset, I get an error stating that it can't be DbNull.
Th record is created from a resultset with the query "Select * from table", so the id should be included

But as I understand it, it should be increasing automatically, right? Becuase that's the behaviour of the normal sql Insert command. I have seen an article that just left the id column in the record alone before inserting it, but it didn't help me.
How can I sidestep this issue?

View 4 Replies View Related

Bug With 'enable Identity Insert On'

Mar 29, 2007

I'm using sp1, tryng to copy from 2005 db to 2005 db, selecting many tables at once, delete target rows on, identity insert ON.



choosing not to optimize for many tables:

Error: 0xC0202009 at Data Flow Task, Destination - table1 [22]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005.

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80004005 Description: "The statement has been terminated.".

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80004005 Description: "Violation of PRIMARY KEY constraint 'PK_table1'. Cannot insert duplicate key in object 'dbo.table1.".

Error: 0xC0202009 at Data Flow Task, Destination 3 - table2 [226]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005.

Etc., for each table



Optimizing for many tables:

Error: 0xC0202009 at {AB2253E6-28B4-4D5A-B843-236F8E53E075}, OLE DB Destination [2]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005.

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80004005 Description: "The statement has been terminated.".

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80004005 Description: "Violation of PRIMARY KEY constraint 'PK_table1'. Cannot insert duplicate key in object 'dbo.table1.".

Information: 0x402090E0 at {AB2253E6-28B4-4D5A-B843-236F8E53E075}, OLE DB Destination [2]: The final commit for the data insertion has ended.

When I drop and recreate the tables manually and set 'identity insert on' it doesn't bring the identity field over AT ALL.

I like that MS has tried to make it easier to move many tables at once by allowing us to set 'enable identity insert' to everything at once, but it doesn't appear to work. ( I've been puzzling over how it could work, anyway...)



Before sp 1, I had to go into each table by clicking the 'edit' button, and it would bring the correct identity value over, but the tables would no longer have the identity property on that field.



I have also tried 'run as a transaction' to no avail...

View 5 Replies View Related

How To Insert A Identity Key Through Store Procudure?

Apr 25, 2007

I want to insert 3 values to sql database through store procudure
 
--- a store procudure is like this--
 ALTER PROCEDURE dbo.FreeExperience
@identity ,
@name nvarchar(20),@gender int,
AS         begin           Insert into list(cid,name,gender)                       values (@identity,@name,@gender)
        end RETURN
-----------------------------------------------------------
the cid is a identity value . it will +1 automatically when user insert a new data..
if i ingore this column in store procudure it will cause error (becuase this column is not allow null)
please help. thanks

View 11 Replies View Related

Retrieving Scope_Entity Or Identity From An SQL Insert

Oct 2, 2007

The following code inserts a record into a table.  I now wish to retrieve the IDENTITY of that entry into a variable so that I can use it again as input for other  inserts.  Can someone offer assistance in handling this.... I tried several alternatives that I found on the internet but none seem to work...
 Thanks!
Dim objConn3 As SqlConnectionDim mySettings3 As New NameValueCollectionmySettings3 = AppSettingsDim strConn3 As StringstrConn3 = mySettings3("connString")objConn3 = New SqlConnection(strConn3)Dim strInsertPatient As StringDim cmdInsert As SqlCommandDim strddlSex As StringDim strddlPatientState As StringDim rowsAffected As Integer
strddlSex = ddlSex.SelectedItem.TextstrddlPatientState = ddlPatientState.SelectedItem.TextstrInsertPatient = "Insert ClinicalPatient ( UserID, Accession, FirstName, MI, " & _"LastName, MedRecord, ddlSex, DOB, Address1, Address2, City, Suite, strddlPatientState, " & _"ZIP, HomeTelephone, OutsideNYC, ClinicalImpression, Today_Date_Month, Today_Date_Day, " & _"Today_Date_Year) Values (@UserID, @Accession, @FirstName, @MI, @LastName, @MedRecord, " & _"'" & strddlSex & "', @DOB, @Address1, @Address2, @City, @Suite , '" & strddlPatientState & "', " & _"@ZIP, @HomeTelephone, @OutsideNYC, @ClinicalImpression, @Today_Date_Month, @Today_Date_Day, " & _"@Today_Date_Year)SELECT @@IDENTITY AS NewID SET NOCOUNT OFF"
cmdInsert = New SqlCommand(strInsertPatient, objConn3)
cmdInsert.Parameters.Add("@UserID", "Joe For Now")cmdInsert.Parameters.Add("@Accession", Accession.Text)cmdInsert.Parameters.Add("@LastName", LastName.Text)cmdInsert.Parameters.Add("@MI", MI.Text)cmdInsert.Parameters.Add("@FirstName", FirstName.Text)cmdInsert.Parameters.Add("@MedRecord", MedRecord.Text)cmdInsert.Parameters.Add("@ddlSex", strddlSex)cmdInsert.Parameters.Add("@DOB", DOB.Text)cmdInsert.Parameters.Add("@Address1", Address1.Text)cmdInsert.Parameters.Add("@Address2", Address2.Text)cmdInsert.Parameters.Add("@City", City.Text)cmdInsert.Parameters.Add("@Suite", Suite.Text)cmdInsert.Parameters.Add("@strddlPatientState", strddlPatientState)cmdInsert.Parameters.Add("@ZIP", zip.Text)cmdInsert.Parameters.Add("@HomeTelephone", Phone.Text)cmdInsert.Parameters.Add("@OutsideNYC", OutsideNYC.Text)cmdInsert.Parameters.Add("@ClinicalImpression", ClinicalImpression.Text)cmdInsert.Parameters.Add("@Today_Date_Month", Today_Date_Month.Text)cmdInsert.Parameters.Add("@Today_Date_Day", Today_Date_Day.Text)cmdInsert.Parameters.Add("@Today_Date_Year", Today_Date_Year.Text)
objConn3.Open()cmdInsert.ExecuteNonQuery()objConn3.Close()

View 1 Replies View Related

Using @@IDENTITY In The Sqldatasource Insert Command

Jan 11, 2008

I apologise if i have not posted this in the correct Topic before i start. But was uncertain where to post this query.
This is my first project in ASP.NET, MS Visual Web Developer 2005 Express and SQL Server 2005 Express. I have relatively little experience, so please bare with me.
I have managed to create a form that inserts data into a table and then inserts the Automatically Created Primary Key(as a foreign key) in another table. I have done this by inserting what is highlighted in red in the code of my InsertCommand below (Please scroll across to the end of the code):-InsertCommand="INSERT INTO [PrinterModel] ([Model], [PrinterMakeID], [CartridgeCode], [PartCode], [Duplex], [NIC], [Wireless], [Parallel], [USB], [Colour], [PrinterTypeID]) VALUES (@Model, @PrinterMakeID, @CartridgeCode, @PartCode, @Duplex, @NIC, @Wireless, @Parallel, @USB, @Colour, @PrinterTypeID) INSERT INTO [Model] ([PrinterModelID],[TypeID]) VALUES (@@IDENTITY, 3)" Can you see any problems that may arise from using this method. This project is an Asset Management System and will be used by no more than a handful of users. My Concern is the use of the @@IDENTITY (As it only stores the last Key used). Should I be using it here? If there is more than one user inserting into tables (Chances of this happening are very low), will the correct Primary key be insert to the table in the above code?Thank you for your comments.

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved