all groups > sql server new users > february 2007 >
You're in the

sql server new users

group:

executescalar doesn't work


executescalar doesn't work michel
2/19/2007 6:05:30 PM
sql server new users:
Hi,

i have to insert values into two tables.
The first table (base table) has a primary key (type 'int') which is
incremented automatically with each insert.
The second table (detail table) contains a field (type 'int') which must get
the value of the primarty key of the last record in table 1.
So if the primary key value of the last record in table1 is e.g. 24, then
one field in table 2 must get that value.

I tried this but doesn't work: (nrec is always 0)

Dim nrec As Integer
insert into table1 (field1, ....) values( ....)
....
nrec = comd.ExecuteScalar()
comd.ExecuteNonQuery()

insert into table2 (field1, ....) values(nrec ....)
comd.ExecuteNonQuery()


Thanks for help
Michel

Re: executescalar doesn't work Anthony Thomas
2/19/2007 6:30:49 PM
First of all, for a table defined with an IDENTITY attribute, you cannot
include that field in the INSERT statement list.

Next, SET @var = SCOPE_IDENTITY() will retrieve the last IDENTITY value
generated within the scope of your batch. (Be careful; there is also an
@@IDENTITY function, but it will return the last inserted IDENTITY in the
database, not necessarily within the same scope as yours).

You can then use the @var variable just populated to INSERT into dependent
tables.

Sincerely,


Anthony Thomas


--

[quoted text, click to view]

Re: executescalar doesn't work Bob Simms
2/19/2007 11:04:19 PM
[quoted text, click to view]

You don't tell us what the command text for the comd is. The general way to
find out the last identity value issued is to call the SCOPE_IDENTITY
function. So the command text of the command object should be "SELECT
SCOPE_IDENTITY()". Run that up the flagpole and see if anyone salutes it.

--

Bob Simms
www.xpertise.co.uk

Re: executescalar doesn't work michel
2/20/2007 12:00:00 AM
Thanks both

"Anthony Thomas" <ALThomas@kc.rr.com> schreef in bericht
news:%23ewzhZIVHHA.3500@TK2MSFTNGP05.phx.gbl...
[quoted text, click to view]

AddThis Social Bookmark Button