Showing posts with label identity. Show all posts
Showing posts with label identity. Show all posts

Wednesday, March 28, 2012

Return a value after insert the query

Hi!


create table testReturn
(
id int identity(100,1),
name varchar(10)
)

How can I return the value of identity column after inserting the value.

Dim objConn As SqlConnection
Dim SQLCmd As SqlClient.SqlCommand
Dim ds As New DataSet
Dim strsql As String

Try

objConn = New SqlConnection
objConn.ConnectionString = _
"Network Library=DBMSSOCN;" & _
"Data Source=localhost;" & _
"Initial Catalog=mydb;" & _
"User ID=userid;" & _
"Password=pass"

objConn.Open()

strsql = "insert into testReturn values ('a')"
SQLCmd = New SqlClient.SqlCommand(strsql, objConn)
Dim rowsAffected As Integer = 0
rowsAffected = SQLCmd.ExecuteNonQuery

Dim rv As String
rv = SQLCmd.Parameters(0).Value.ToString()
Response.Write(rv)


Catch ex As Exception
Response.Write(ex.ToString)
End Try


SeeHow do I get the IDENTITY / AUTONUMBER value for the row I inserted?

|||

strsql = "insert into testReturn values ('a'); select @.@.Identity"
SQLCmd = New SqlClient.SqlCommand(strsql, objConn)

dim Identiy as Object

Identity = SQLCmd.ExecuteScalar

|||

You need to put "Select @.@.identity" statement immediately after your insert query so it would return the ID value of the record inserted, using the preceding Insert statement.

Cheers
Ritesh

|||

Using @.@.IDENTITY is an vulnerable approach, since it returns the last inserted id of any table. If you are using SQL 2005 then you can use the OUTPUT clause.

SeeHow to get an Identity value with SQL Server 2005

|||

You can either use @.@.identity or scope_identity().

@.@.identity gives you the last generated identity value.

scope_identity() gives you the last generated identity value for current scope.

Just have a quick look at BOL for further understanding.

Hope this will help.

Monday, March 26, 2012

return @@identity for another function

What I'm trying to do is provide a solution where users can upload an image and a description, to a database, so I'm trying to insert the title and description then return the @.@.identity for the image upload function which will name the image like this
image_23.jpg (23 being the @.@.identity) resize it and save it to specified directory

I cant seem to get the identity to return to my script.
This is my SP

CREATE PROCEDURE SP_Insertad
(
@.catid int,
@.subcatid int,
@.areaid int,
@.uid int,
@.adtitle varchar(255),
@.addescription varchar(1000)
)

AS
Insert Into Tbl_ad
(ad_title, ad_description,ad_area,ad_ui_id,ad_active,ad_date,ad_ct_id,ad_sc_id,ad_location)
VALUES
(@.adtitle,@.addescription,@.areaid, @.uid, 0,convert(varchar, GETUTCDATE(), 101), @.catid, @.subcatid, 1)

select @.@.identity
return
GO

I tested in query analyser, and it works fine, so It must be my code. this is my function

Sub Insert_pic(sender as object, e as eventargs)

Dim catid = Request.form("ddcats")
Dim subcatid = Request.form("subcatrad")
Dim adtitle = Request.Form("txttitle")
Dim AdDescription = Request.form("txtdescription")
Dim uid = getUID(Context.User.Identity.Name)
Dim areaid = Request.form("ddarea")
SQLConnect = new SqlConnection(ConfigurationSettings.Appsettings("mydB"))

SQLCommander = New SQLCommand("SP_INSERTad", SQLConnect)

SQLCommander.Commandtype = Commandtype.StoredProcedure

SQLCommander.Parameters.add("@.adtitle", adtitle)
SQLCommander.Parameters.add("@.addescription", addescription)
SQLCommander.Parameters.add("@.catid", catid)
SQLCommander.Parameters.add("@.subcatid", subcatid)
SQLCommander.Parameters.add("@.uid", uid)
SQLCommander.Parameters.add("@.areaid", areaid)

'// this section not working right, it wont write return id

Dim paramreturn as SQLParameter
paramreturn = SQLCommander.Parameters.Add("ReturnValue", SQLDBType.Int)
ParamReturn.Direction = ParameterDirection.ReturnValue

response.write(SQLCommander.Parameters("ReturnValue").Value)

SQLConnect.open()
SQLCommander.ExecuteNonQuery()
SQLConnect.close()

End sub

Can anybody see anything I missing? I appreciate any imputYour existing code will work by making the following changes:

1) Take out the following lines:


Dim paramreturn as SQLParameter
paramreturn = SQLCommander.Parameters.Add("ReturnValue", SQLDBType.Int)
ParamReturn.Direction = ParameterDirection.ReturnValue

2) Make the following change to the SQLCommander.ExecuteNonQuery() line:


Dim returnVal As Integer = SQLCommander.ExecuteScalar()

See the following link about the ExecuteScalar() method:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatasqlclientsqlcommandclassexecutescalartopic.asp|||you should say "return @.@.ID..." rather than "select"|||i changed it to
...
AS
Insert Into Tbl_Ads
(ad_title, ad_description,ad_area,ad_ui_id,ad_active,ad_date,ad_ct_id,ad_sc_id,ad_location)
VALUES
(@.adtitle,@.addescription,@.areaid, @.uid, 0,convert(varchar, GETUTCDATE(), 101), @.catid, @.subcatid, 1)

return @.@.identity
GO

I think the break down is here -
Dim paramreturn as SQLParameter
paramreturn = SQLCommander.Parameters.Add("ReturnValue", SQLDBType.Int)
ParamReturn.Direction = ParameterDirection.ReturnValue

response.write(SQLCommander.Parameters("ReturnValue").Value)

it's not writing to page. Stumped|||ghost opz ,
that worked, I dont know why or how but That did the trick.

thanks a million!

striker

return

whats wrong with this SP? I want @.id to contain the row identity of the newly created row as a return value.
ALTER PROCEDURE setCountry
(
@.name varchar( 50 ) = NULL,
@.alt varchar( 24 ) = NULL,
@.code varchar( 3 ) = NULL,
@.id int = null OUT
)
AS
SET NOCOUNT ON
INSERT INTO Countries( CountryName, CountryAltName, CountryCode ) VALUES ( @.name, @.alt, @.code )
@.id = @.@.identity
RETURN

INSERT INTO Countries( CountryName, CountryAltName, CountryCode ) VALUES ( @.name, @.alt, @.code )select@.id = @.@.identity

couple of things :
if you'd like to return this id back to asp.net you need to return it as an OUTPUT parameter..check out BOL for OUTPUT Parameters in stored procs..

also i'd recommend using SCOPE_IDENTITY() rather than @.@.IDENTITY. check out BOL again for the differences between them.

hth|||Thanks - but what is BOL?|||RETURN @.id

??

personally I'd do it this way

SET NOCOUNT ON
-- do insert
...
SELECT @.@.Identity|||BOL = Books On Line - best reference for sql server 2000. Free Download from microsoft.

hth|||Thanks! - I got the BOL acronym too - duh - Books On Line. I will try it now and actually may use SCOPE_IDENTITY() in place of @.@.identity.|||Atrax, I think the "return" method is better as it won't incur a result set. Although I'd use a OUTPUT param rather than return, I prefer to have that indicate some form of "state of the operation".|||Okay - now I can retrieve the result using ExecuteScalar - or DataReader or both?? Because when I run it in VS I dont see the results of the procedures. I mean it adds the row, but I don't see any output in the OUTPUT window.|||if you just need to return the ID you'd be better off using executescalar().

in vb.net


dim userID as integer
...
'open connection
...
userid=sqlcommand.ExecuteScalar()
...
'close connection

and use OUTPUT parameter to return the output form the stored proc...BOL had some samples no how to do it..

hth

Friday, March 23, 2012

retrieving XML data from table

Hi,
I have a table with two field one of them is an identity field as record ID
and another is a ntext field named: xData
XData field contain an xml data like below:
<root>
<ta Name="bill" Job="eng"/>
<ta Name="john" Job="Mng"/>
<ta Name="Tom" Job="Sup"/>
</root>
And in the next record:
………
I can retrieve xml data from xData field for each record with openxml () to
a temptable .
Also I can update this table with SQL Statement like Delete,Update and insert.
Now after updating temptable, I want update xData filed with updated data
(as a xml format ).
Unfortunately I can not return data with XML format from temptable.
Please tell me how can I do that.
I assume you are using SQL Server 2000 (it would be much easier in SQL
Server 2005 where you can use the XML datatype and XQuery/XML-DML).
I assume that you would like to use FOR XML to reconstruct the XML and
reinsert it into the ntext field. You can do so, but you would need to write
client-code that retrieves the XML from the server and then gives it back
into the server. That code can then be called from within the SQL Server
using the sp_OA stored procs.
Also note that you will run into issues with your OpenXML approach below if
the data will be larger than 8kBytes, unless you are using some other
workaround of the limitation of SQL Server 2000 that you cannot have
variables of type ntext (note that SQL Server 2005 is better again).
Best regards
Michael
"Mehdi" <Mehdi@.discussions.microsoft.com> wrote in message
news:6E1080E4-3A0A-4E53-B8A6-616AF393FFFB@.microsoft.com...
> Hi,
> I have a table with two field one of them is an identity field as record
> ID
> and another is a ntext field named: xData
> XData field contain an xml data like below:
> <root>
> <ta Name="bill" Job="eng"/>
> <ta Name="john" Job="Mng"/>
> <ta Name="Tom" Job="Sup"/>
> </root>
> And in the next record:
> ...
> I can retrieve xml data from xData field for each record with openxml ()
> to
> a temptable .
> Also I can update this table with SQL Statement like Delete,Update and
> insert.
> Now after updating temptable, I want update xData filed with updated data
> (as a xml format ).
> Unfortunately I can not return data with XML format from temptable.
> Please tell me how can I do that.
>
sql

retrieving XML data from table

Hi,
I have a table with two field one of them is an identity field as record ID
and another is a ntext field named: xData
XData field contain an xml data like below:
<root>
<ta Name="bill" Job="eng"/>
<ta Name="john" Job="Mng"/>
<ta Name="Tom" Job="Sup"/>
</root>
And in the next record:
………
I can retrieve xml data from xData field for each record with openxml () to
a temptable .
Also I can update this table with SQL Statement like Delete,Update and inser
t.
Now after updating temptable, I want update xData filed with updated data
(as a xml format ).
Unfortunately I can not return data with XML format from temptable.
Please tell me how can I do that.I assume you are using SQL Server 2000 (it would be much easier in SQL
Server 2005 where you can use the XML datatype and XQuery/XML-DML).
I assume that you would like to use FOR XML to reconstruct the XML and
reinsert it into the ntext field. You can do so, but you would need to write
client-code that retrieves the XML from the server and then gives it back
into the server. That code can then be called from within the SQL Server
using the sp_OA stored procs.
Also note that you will run into issues with your OpenXML approach below if
the data will be larger than 8kBytes, unless you are using some other
workaround of the limitation of SQL Server 2000 that you cannot have
variables of type ntext (note that SQL Server 2005 is better again).
Best regards
Michael
"Mehdi" <Mehdi@.discussions.microsoft.com> wrote in message
news:6E1080E4-3A0A-4E53-B8A6-616AF393FFFB@.microsoft.com...
> Hi,
> I have a table with two field one of them is an identity field as record
> ID
> and another is a ntext field named: xData
> XData field contain an xml data like below:
> <root>
> <ta Name="bill" Job="eng"/>
> <ta Name="john" Job="Mng"/>
> <ta Name="Tom" Job="Sup"/>
> </root>
> And in the next record:
> ...
> I can retrieve xml data from xData field for each record with openxml ()
> to
> a temptable .
> Also I can update this table with SQL Statement like Delete,Update and
> insert.
> Now after updating temptable, I want update xData filed with updated data
> (as a xml format ).
> Unfortunately I can not return data with XML format from temptable.
> Please tell me how can I do that.
>

retrieving the BigInt value from the Identity Column after inserting

I have a database that has a tble with a field that autoincrements as a primary key. meanig that the field type is BigInteger and it is set up as my Identity Column. Now when I insert a new record that field gets updated automaticly.

How can I get this value in the same operation as my insert? meaning, in 1 sub, I insert a new record but then need to retieve the Identity Value. All in the same procedure.

Waht is the way to achive this please?

Marc

What I do is issue the two commands (the sql insert, and the sql select scope_identity) in the same execute separated by semi colon.

the trick is to set the parameter direction to output for the identity.

David H. has a good article.

http://davidhayden.com/blog/dave/archive/2006/02/16/2803.aspx

|||

Thank you very much. that did it!

Marc

Wednesday, March 21, 2012

retrieving selected join records

Hi,
I have the folowing 3 (SS2005) tables:

CREATE TABLE [dbo].[tblSubscription](
[SubscriptionID] [int] IDENTITY(1000000,1) NOT NULL,
[SubscriberID] [int] NOT NULL,
[Status] [int] NOT NULL,
[JournalID] [int] NOT NULL,

CREATE TABLE [dbo].[tblTransaction](
[TransactionID] [bigint] IDENTITY(100000000,1) NOT NULL,
[TransactionTypeID] [int] NOT NULL,
[SubscriptionID] [int] NOT NULL,
[Created] [datetime] NOT NULL,

CREATE TABLE [dbo].[tblMailing](
[MialingID] [bigint] IDENTITY(1000000000,1) NOT NULL,
[SubscriptionID] [int] NOT NULL,
[MailTypeID] [int] NOT NULL,
[MailDate] [datetime] NOT NULL

So for each subscription there can be 1 or more transactions and 0 or
more mailings, and the mailings are not necassarily related to the
transactions. What I am having difficulty doing is this:

I wish to select tblMailing.MailingID, tblMailing.MailDate,
tblMailing.SubscriptionID (or tblSubscription.SubscriptionID),
tblSubscription.SubscriberID, tblSubscription.Status,
tblTransaction.TransactionID, tblTransaction.Created, but I only wish
to retrieve rows from the transaction table where
tblTransaction.Created is the latest dated transaction for that
subscription.
I.E. (maybe this makes more sense..:) I wish to select all rows from
tblMailing along with each mailing's relevent subscription details,
including details of the LATEST TRANSACTION for each of those
subscriptions.

I am currently working along the lines of MAX(tblTransaction.Created)
and possibly GROUP BY in a subquery, but cannot quite figure out the
logic.

Any help appreciated.

Thanks, KoG

King:

Are you wanting the subscription record to appear in the report even if there are as of yet no mailings? That is, do I need to use an outer join or an inner join? I am for the moment assuming that you want the inner join.


Dave

|||

set nocount on
declare @.tblSubscription table
( subscriptionID integer not null,
subscriberID integer not null,
status integer not null,
journalID integer not null,
primary key (subscriptionID)
)

declare @.tblTransaction table
( transactionID integer not null,
transactionTypeId integer not null,
subscriptionID integer not null,
created datetime not null
primary key (transactionID),
unique (subscriptionID, transactionID)
)

declare @.tblMailing table
( mailingId bigint not null,
subscriptionID integer not null,
mailTypeId integer not null,
mailDate datetime not null,
primary key (mailingID),
unique (subscriptionId, mailingId)
)

insert into @.tblSubscription values (1000001, 1000001, 1, 1)
insert into @.tblSubscription values (1000002, 1000002, 1, 1)
insert into @.tblSubscription values (1000003, 1000001, 2, 1)
--select * from @.tblSubscription

insert into @.tblTransaction values (1000001, 1, 1000001, '3/15/6' )
insert into @.tblTransaction values (1000002, 2, 1000001, '4/7/6' )
insert into @.tblTransaction values (1000003, 1, 1000002, '4/3/6' )
insert into @.tblTransaction values (1000004, 1, 1000003, '5/8/6' )
insert into @.tblTransaction values (1000005, 2, 1000003, '10/14/6')
insert into @.tblTransaction values (1000006, 4, 1000003, '9/1/6' )
--select * from @.tblTransaction

insert into @.tblMailing values (1000001, 1000001, 1, '3/15/6' )
insert into @.tblMailing values (1000002, 1000001, 2, '4/4/6' )
insert into @.tblMailing values (1000003, 1000003, 1, '5/9/6' )
insert into @.tblMailing values (1000004, 1000003, 3, '9/3/6' )
--select * from @.tblMailing

--set statistics io on
select m.mailingId,
m.MailDate,
s.subscriptionId,
s.subscriberId,
s.Status,
t.TransactionId,
t.created
from @.tblSubscription s
inner join @.tblMailing m
on s.subscriptionId = m.subscriptionId
inner join
( select q.subscriptionId,
q.transactionId,
row_number () over
( partition by q.subscriptionId
order by q.created desc, q.transactionId desc
) as Seq,
created
from @.tblTransaction q
) t
on t.subscriptionId = s.subscriptionId
and seq = 1
--set statistics io off


-- -- Sample Output: -

-- mailingId MailDate subscriptionId subscriberId Status TransactionId created
-- -- -- -- -- - --
-- 1000001 2006-03-15 00:00:00.000 1000001 1000001 1 1000002 2006-04-07 00:00:00.000
-- 1000002 2006-04-04 00:00:00.000 1000001 1000001 1 1000002 2006-04-07 00:00:00.000
-- 1000003 2006-05-09 00:00:00.000 1000003 1000001 2 1000005 2006-10-14 00:00:00.000
-- 1000004 2006-09-03 00:00:00.000 1000003 1000001 2 1000005 2006-10-14 00:00:00.000

|||Hi Dave,

I only wish to select subscription rows where there is a mailing associated with the subscription. In fact, the driver of the query should be the mailings table, so for each row in tblMailing get the relevent subscription (& latest transaction) data. That means there may be several rows where the data in the subscription-related columns (& hence transaction related ones too) are the same, as a subscription may have several mailings.

I assume that means the inner join is required..

Thanks, Nick
sql

Retrieving Scope_Entity or Identity from an SQL Insert

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 objConn3As SqlConnection
Dim mySettings3AsNew NameValueCollection
mySettings3 = AppSettings
Dim strConn3AsString
strConn3 = mySettings3("connString")
objConn3 =New SqlConnection(strConn3)
Dim strInsertPatientAsString
Dim cmdInsertAs SqlCommand
Dim strddlSexAsString
Dim strddlPatientStateAsString
Dim rowsAffectedAsInteger

strddlSex = ddlSex.SelectedItem.Text
strddlPatientState = ddlPatientState.SelectedItem.Text

strInsertPatient ="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()

Try this - a zillion ways to get Scope_Identity back:http://www.mikesdotnetting.com/Article.aspx?ArticleID=54

Tuesday, March 20, 2012

Retrieving Identity Value after using DataAdapter.Update on DataTable

I am trying to retrieve the Identity Value on an Inserted Table Row.. However, I am inserting this row by creating a new DataRow, inserting it into the DataTable, and using SqlDataAdapter.Update (which would then auto-create the insertion string, insert, and then close the connection ).

I want to retrieve the Identity Value of what I just inserted.. I tried using a "SELECT @.@.IDENTITY", but that returned null.. I think its because @.@.IDENTITY only works for a connection session, and the SqlDataAdapter closes the connection after it inserts..

Any ideas / workarounds would be welcome! Thanks!

I posted this to the MySQL forum by accident too Sorry! :\Write your own insert function & attach it into SqlDataAdapter.InsertCommand property.|||How will writing my own insertion string allow me to retrieve the Identity value after its inserted?|||1st of all: try to use stored procedures. It's more robust & more elegant solution than inline SQL statements. Example statement (for Northwind database):


CREATE PROCEDURE CategoryInsert
(
@.CategoryName nvarchar(15)
)
AS
INSERT INTO Categories (CategoryName) VALUES (@.CategoryName )
SELECT @.@.IDENTITY
<code>
And in code-behind:
<code>
SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
conn.Open();
SqlCommand sqlInsert = new SqlCommand("CategoryInsert", conn);
sqlInsert.CommandType = CommandType.StoredProcedure;

SqlParameter paramCategoryName = new SqlParameter("@.CategoryName", SqlDbType.NVarChar, 15);
paramCategoryName.Value = "New category";
sqlInsert.Parameters.Add(paramCategoryName);

object o = sqlInsert.ExecuteScalar();
if(o != null)
lblFeedback.Text = o.ToString();

conn.Close();

Retrieving Identity after insert

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

hi,

can you try using @.@.Identity please.

morever please put some code what exactly you've done.

regards,

satish.

|||

Scope Identity is safer than @.@.Identity. @.@.Identity could possibly give you the wrong ID back if your table has triggers that also insert records.

Is @.MY_ID being returned as an output parameter or is this something you are simply doing in a stored procedure with no object/class interaction ?

Retrieving ID after insert

Hi, I have a Stored procedure doind an INSERT which then returns @.@.Identity.

I have set this parameters direction to output, however, when i run it I get an error saying procedure is expecting this output parameter..

Not sure where I am going wrong...

Can someone please help with retrieving the ID after an insert. What is the correct code in .NET?

Many ThanksShow your SP, and how you call it. You can get info like htis back as an output parameter, or as a return code. Absent knowing what you are doing, it is impossible to help.|||This is just a suggestion.

First define the input parameters and assign its values.

'Define the output parameter
With cmd.Parameters.Add("@.outputField", SqlDbType.Int)
.Direction = ParameterDirection.Output
End With

'Read the result
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim returnId As Integer
If dr.Read Then
returnId = dr("OutputField")
End If
dr.Close()

My cmd is the reference to the SqlCommand.
OutputField – Field which you want to return.

Hope this might give you some help.|||Use Scope_Identity() instead of @.@.Identity.

Also..

cmd.ExecuteNonReader()

returnID = cmd.Parameters("@.outputField").Value
cmd.Dipose()

Friday, March 9, 2012

Retrieving all Child and Grandchild and Great Grandchild etc Nodes

Given this table:
CREATE TABLE Nodes (
[NodeID] [int] IDENTITY (1, 1) NOT NULL ,
[NodeName] [varchar] (50) NOT NULL ,
[ParentNodeID] [int] NULL ,
[SequenceUnderParent] [int] NULL
)
I would like to have one SELECT statement, if possible, that returns [all of
the descendent nodes] of a given node -- i.e., all of the given node's child
nodes AND all of their child nodes {grand child nodes}, etc... down to 4
possible "generations".
NOTE: It will not be possible (per "business rules" and of course the table
structure, obviously) for any node to have more than one parent node.
If not in one SELECT statement, then how can I accomplish this?
Thanks!See another post few poasts before
Bill of material (SQL2000)
"Jordan S." <A@.B.COM> wrote in message
news:%23$fKXzkXGHA.4212@.TK2MSFTNGP02.phx.gbl...
> Given this table:
> CREATE TABLE Nodes (
> [NodeID] [int] IDENTITY (1, 1) NOT NULL ,
> [NodeName] [varchar] (50) NOT NULL ,
> [ParentNodeID] [int] NULL ,
> [SequenceUnderParent] [int] NULL
> )
> I would like to have one SELECT statement, if possible, that returns [all
> of the descendent nodes] of a given node -- i.e., all of the given node's
> child nodes AND all of their child nodes {grand child nodes}, etc... down
> to 4 possible "generations".
> NOTE: It will not be possible (per "business rules" and of course the
> table structure, obviously) for any node to have more than one parent
> node.
> If not in one SELECT statement, then how can I accomplish this?
> Thanks!
>|||There are many ways to represent a tree or hierarchy in SQL. This is
called an adjacency list model and it looks like this:
CREATE TABLE OrgChart
(emp CHAR(10) NOT NULL PRIMARY KEY,
boss CHAR(10) DEFAULT NULL REFERENCES OrgChart(emp),
salary DECIMAL(6,2) NOT NULL DEFAULT 100.00);
OrgChart
emp boss salary
===========================
'Albert' NULL 1000.00
'Bert' 'Albert' 900.00
'Chuck' 'Albert' 900.00
'Donna' 'Chuck' 800.00
'Eddie' 'Chuck' 700.00
'Fred' 'Chuck' 600.00
Another way of representing trees is to show them as nested sets.
Since SQL is a set oriented language, this is a better model than the
usual adjacency list approach you see in most text books. Let us define
a simple OrgChart table like this.
CREATE TABLE OrgChart
(emp CHAR(10) NOT NULL PRIMARY KEY,
lft INTEGER NOT NULL UNIQUE CHECK (lft > 0),
rgt INTEGER NOT NULL UNIQUE CHECK (rgt > 1),
CONSTRAINT order_okay CHECK (lft < rgt) );
OrgChart
emp lft rgt
======================
'Albert' 1 12
'Bert' 2 3
'Chuck' 4 11
'Donna' 5 6
'Eddie' 7 8
'Fred' 9 10
The organizational chart would look like this as a directed graph:
Albert (1, 12)
/ \
/ \
Bert (2, 3) Chuck (4, 11)
/ | \
/ | \
/ | \
/ | \
Donna (5, 6) Eddie (7, 8) Fred (9, 10)
The adjacency list table is denormalized in several ways. We are
modeling both the Personnel and the organizational chart in one table.
But for the sake of saving space, pretend that the names are job titles
and that we have another table which describes the Personnel that hold
those positions.
Another problem with the adjacency list model is that the boss and
employee columns are the same kind of thing (i.e. names of personnel),
and therefore should be shown in only one column in a normalized table.
To prove that this is not normalized, assume that "Chuck" changes his
name to "Charles"; you have to change his name in both columns and
several places. The defining characteristic of a normalized table is
that you have one fact, one place, one time.
The final problem is that the adjacency list model does not model
subordination. Authority flows downhill in a hierarchy, but If I fire
Chuck, I disconnect all of his subordinates from Albert. There are
situations (i.e. water pipes) where this is true, but that is not the
expected situation in this case.
To show a tree as nested sets, replace the nodes with ovals, and then
nest subordinate ovals inside each other. The root will be the largest
oval and will contain every other node. The leaf nodes will be the
innermost ovals with nothing else inside them and the nesting will show
the hierarchical relationship. The (lft, rgt) columns (I cannot use the
reserved words LEFT and RIGHT in SQL) are what show the nesting. This
is like XML, HTML or parentheses.
At this point, the boss column is both redundant and denormalized, so
it can be dropped. Also, note that the tree structure can be kept in
one table and all the information about a node can be put in a second
table and they can be joined on employee number for queries.
To convert the graph into a nested sets model think of a little worm
crawling along the tree. The worm starts at the top, the root, makes a
complete trip around the tree. When he comes to a node, he puts a
number in the cell on the side that he is visiting and increments his
counter. Each node will get two numbers, one of the right side and one
for the left. Computer Science majors will recognize this as a modified
preorder tree traversal algorithm. Finally, drop the unneeded
OrgChart.boss column which used to represent the edges of a graph.
This has some predictable results that we can use for building queries.
The root is always (left = 1, right = 2 * (SELECT COUNT(*) FROM
TreeTable)); leaf nodes always have (left + 1 = right); subtrees are
defined by the BETWEEN predicate; etc. Here are two common queries
which can be used to build others:
1. An employee and all their Supervisors, no matter how deep the tree.
SELECT O2.*
FROM OrgChart AS O1, OrgChart AS O2
WHERE O1.lft BETWEEN O2.lft AND O2.rgt
AND O1.emp = :myemployee;
2. The employee and all their subordinates. There is a nice symmetry
here.
SELECT O1.*
FROM OrgChart AS O1, OrgChart AS O2
WHERE O1.lft BETWEEN O2.lft AND O2.rgt
AND O2.emp = :myemployee;
3. Add a GROUP BY and aggregate functions to these basic queries and
you have hierarchical reports. For example, the total salaries which
each employee controls:
SELECT O2.emp, SUM(S1.salary)
FROM OrgChart AS O1, OrgChart AS O2,
Salaries AS S1
WHERE O1.lft BETWEEN O2.lft AND O2.rgt
AND O1.emp = S1.emp
GROUP BY O2.emp;
4. To find the level of each emp, so you can print the tree as an
indented listing. Technically, you should declare a cursor to go with
the ORDER BY clause.
SELECT COUNT(O2.emp) AS indentation, O1.emp
FROM OrgChart AS O1, OrgChart AS O2
WHERE O1.lft BETWEEN O2.lft AND O2.rgt
GROUP BY O1.lft, O1.emp
ORDER BY O1.lft;
5. The nested set model has an implied ordering of siblings which the
adjacency list model does not. To insert a new node, G1, under part G.
We can insert one node at a time like this:
BEGIN ATOMIC
DECLARE rightmost_spread INTEGER;
SET rightmost_spread
= (SELECT rgt
FROM Frammis
WHERE part = 'G');
UPDATE Frammis
SET lft = CASE WHEN lft > rightmost_spread
THEN lft + 2
ELSE lft END,
rgt = CASE WHEN rgt >= rightmost_spread
THEN rgt + 2
ELSE rgt END
WHERE rgt >= rightmost_spread;
INSERT INTO Frammis (part, lft, rgt)
VALUES ('G1', rightmost_spread, (rightmost_spread + 1));
COMMIT WORK;
END;
The idea is to spread the (lft, rgt) numbers after the youngest child
of the parent, G in this case, over by two to make room for the new
addition, G1. This procedure will add the new node to the rightmost
child position, which helps to preserve the idea of an age order among
the siblings.
6. To convert a nested sets model into an adjacency list model:
SELECT B.emp AS boss, E.emp
FROM OrgChart AS E
LEFT OUTER JOIN
OrgChart AS B
ON B.lft
= (SELECT MAX(lft)
FROM OrgChart AS S
WHERE E.lft > S.lft
AND E.lft < S.rgt);
7. To convert an adjacency list to a nested set model, use a push down
stack. Here is version with a stack in SQL/PSM.
-- Tree holds the adjacency model
CREATE TABLE Tree
(node CHAR(10) NOT NULL,
parent CHAR(10));
-- Stack starts empty, will holds the nested set model
CREATE TABLE Stack
(stack_top INTEGER NOT NULL,
node CHAR(10) NOT NULL,
lft INTEGER,
rgt INTEGER);
CREATE PROCEDURE TreeTraversal ()
LANGUAGE SQL
DETERMINISTIC
BEGIN ATOMIC
DECLARE counter INTEGER;
DECLARE max_counter INTEGER;
DECLARE current_top INTEGER;
SET counter = 2;
SET max_counter = 2 * (SELECT COUNT(*) FROM Tree);
SET current_top = 1;
--clear the stack
DELETE FROM Stack;
-- push the root
INSERT INTO Stack
SELECT 1, node, 1, max_counter
FROM Tree
WHERE parent IS NULL;
-- delete rows from tree as they are used
DELETE FROM Tree WHERE parent IS NULL;
WHILE counter <= max_counter- 1
DO IF EXISTS (SELECT *
FROM Stack AS S1, Tree AS T1
WHERE S1.node = T1.parent
AND S1.stack_top = current_top)
THEN BEGIN -- push when top has subordinates and set lft value
INSERT INTO Stack
SELECT (current_top + 1), MIN(T1.node), counter, NULL
FROM Stack AS S1, Tree AS T1
WHERE S1.node = T1.parent
AND S1.stack_top = current_top;
-- delete rows from tree as they are used
DELETE FROM Tree
WHERE node = (SELECT node
FROM Stack
WHERE stack_top = current_top + 1);
-- housekeeping of stack pointers and counter
SET counter = counter + 1;
SET current_top = current_top + 1;
END;
ELSE
BEGIN -- pop the stack and set rgt value
UPDATE Stack
SET rgt = counter,
stack_top = -stack_top -- pops the stack
WHERE stack_top = current_top;
SET counter = counter + 1;
SET current_top = current_top - 1;
END;
END IF;
END WHILE;
-- SELECT node, lft, rgt FROM Stack;
-- the top column is not needed in the final answer
-- move stack contents to new tree table
END;
I have a book on TREES & HIERARCHIES IN SQL which you can get at
Amazon.com right now.

Retrieving @@Identity

Hi,
I have the following proc:
CREATE PROCEDURE SP_CadastraPessoaFisica
(
@.Email Varchar(60) = '',
@.Senha Varchar(10) = '',
@.Nome Varchar(50) = '',
@.Sobrenome Varchar(50) = '',
@.DataNascimento DateTime,
@.Sexo Char(1),
@.CPF Varchar(12)
)
As
Set Nocount On
Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
GO
Simple.Isn't it ? So...I need to retrieve the ID from this insert command
when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
use @.@.Identity!
Thanks in advance,
Daniel Groh
Daniel
If you are using SQL Server 2000 you can use SCOPE_IDENITY() function
INSERT INTO Table (col) VALUES (1)
SELECT SCOPE_IDENITY()
Note : there is a difference between @.@.IDENTITY and SCOPE_IDENTITY() which
may bring unexpected result
See BOL for details
"Daniel Groh" <newsgroupms@.gmail.com> wrote in message
news:u4mnT$8TFHA.3308@.TK2MSFTNGP14.phx.gbl...
> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>
|||Please don't multipost ,it is answered in .programming
"Daniel Groh" <newsgroupms@.gmail.com> wrote in message
news:u4mnT$8TFHA.3308@.TK2MSFTNGP14.phx.gbl...
> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>
|||Hi
You can use this:
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
This will help you solve the problem
thanks and regards
Chandra
"Daniel Groh" wrote:

> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>
>

Retrieving @@Identity

Hi,
I have the following proc:
CREATE PROCEDURE SP_CadastraPessoaFisica
(
@.Email Varchar(60) = '',
@.Senha Varchar(10) = '',
@.Nome Varchar(50) = '',
@.Sobrenome Varchar(50) = '',
@.DataNascimento DateTime,
@.Sexo Char(1),
@.CPF Varchar(12)
)
As
Set Nocount On
Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
GO
Simple.Isn't it ? So...I need to retrieve the ID from this insert command
when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
use @.@.Identity!
Thanks in advance,
Daniel GrohDaniel
If you are using SQL Server 2000 you can use SCOPE_IDENITY() function
INSERT INTO Table (col) VALUES (1)
SELECT SCOPE_IDENITY()
Note : there is a difference between @.@.IDENTITY and SCOPE_IDENTITY() which
may bring unexpected result
See BOL for details
"Daniel Groh" <newsgroupms@.gmail.com> wrote in message
news:u4mnT$8TFHA.3308@.TK2MSFTNGP14.phx.gbl...
> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>|||Please don't multipost ,it is answered in .programming
"Daniel Groh" <newsgroupms@.gmail.com> wrote in message
news:u4mnT$8TFHA.3308@.TK2MSFTNGP14.phx.gbl...
> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>|||Hi
You can use this:
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
This will help you solve the problem
thanks and regards
Chandra
"Daniel Groh" wrote:

> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>
>|||Hi, I tryed
CREATE PROCEDURE SP_CadastraPessoaFisica
(
@.Email Varchar(60) = '',
@.Senha Varchar(10) = '',
@.Nome Varchar(50) = ''
)
As
Declare @.CdUsuario Int
Set Nocount On
Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
Select @.CdUsuario = @.@.Identity
Insert Into Teste(CdUsuario,Nome) Values(@.CdUsuario,'Daniel Groh')
GO
I have this error now:
Server: Msg 8152, Level 16, State 9, Procedure SP_CadastraPessoaFisica, Line
15
String or binary data would be truncated.
The statement has been terminated.
Atenciosamente,
Daniel Groh
CTF Technologies do Brasil Ltda.
Analista Programador
Fone: 11 3837-4203
E-mail: dgroh@.ctf.com.br
"Chandra" <Chandra@.discussions.microsoft.com> escreveu na mensagem
news:2A563E0C-350B-44CE-9C5D-4B1DD1C2F42F@.microsoft.com...
> Hi
> You can use this:
> SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
> This will help you solve the problem
> thanks and regards
> Chandra
>
> "Daniel Groh" wrote:
>|||Hi
Just see the data capacity for
Teste(CdUsuario, Nome)
Is the column: Nome (Name) more than 11 chars '
thanks and regards
Chandra
"Daniel Groh" wrote:

> Hi, I tryed
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = ''
> )
> As
> Declare @.CdUsuario Int
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> Select @.CdUsuario = @.@.Identity
> Insert Into Teste(CdUsuario,Nome) Values(@.CdUsuario,'Daniel Groh')
> GO
>
> I have this error now:
> Server: Msg 8152, Level 16, State 9, Procedure SP_CadastraPessoaFisica, Li
ne
> 15
> String or binary data would be truncated.
> The statement has been terminated.
> --
> Atenciosamente,
> Daniel Groh
> CTF Technologies do Brasil Ltda.
> Analista Programador
> Fone: 11 3837-4203
> E-mail: dgroh@.ctf.com.br
> "Chandra" <Chandra@.discussions.microsoft.com> escreveu na mensagem
> news:2A563E0C-350B-44CE-9C5D-4B1DD1C2F42F@.microsoft.com...
>
>|||Yes, That was the problem
Thanks in advance!
Atenciosamente,
Daniel Groh
CTF Technologies do Brasil Ltda.
Analista Programador
Fone: 11 3837-4203
E-mail: dgroh@.ctf.com.br
"Chandra" <Chandra@.discussions.microsoft.com> escreveu na mensagem
news:5B01A3DD-F70E-49E8-A5C0-C077C0E45223@.microsoft.com...
> Hi
> Just see the data capacity for
> Teste(CdUsuario, Nome)
> Is the column: Nome (Name) more than 11 chars '
> thanks and regards
> Chandra
> "Daniel Groh" wrote:
>

Retrieving @@Identity

Hi,
I have the following proc:
CREATE PROCEDURE SP_CadastraPessoaFisica
(
@.Email Varchar(60) = '',
@.Senha Varchar(10) = '',
@.Nome Varchar(50) = '',
@.Sobrenome Varchar(50) = '',
@.DataNascimento DateTime,
@.Sexo Char(1),
@.CPF Varchar(12)
)
As
Set Nocount On
Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
GO
Simple.Isn't it ? So...I need to retrieve the ID from this insert command
when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
use @.@.Identity!
--
Thanks in advance,
Daniel GrohDaniel
If you are using SQL Server 2000 you can use SCOPE_IDENITY() function
INSERT INTO Table (col) VALUES (1)
SELECT SCOPE_IDENITY()
Note : there is a difference between @.@.IDENTITY and SCOPE_IDENTITY() which
may bring unexpected result
See BOL for details
"Daniel Groh" <newsgroupms@.gmail.com> wrote in message
news:u4mnT$8TFHA.3308@.TK2MSFTNGP14.phx.gbl...
> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>|||Please don't multipost ,it is answered in .programming
"Daniel Groh" <newsgroupms@.gmail.com> wrote in message
news:u4mnT$8TFHA.3308@.TK2MSFTNGP14.phx.gbl...
> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>|||Hi
You can use this:
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
This will help you solve the problem
thanks and regards
Chandra
"Daniel Groh" wrote:
> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>
>

Retrieving @@Identity

Hi,
I have the following proc:
CREATE PROCEDURE SP_CadastraPessoaFisica
(
@.Email Varchar(60) = '',
@.Senha Varchar(10) = '',
@.Nome Varchar(50) = '',
@.Sobrenome Varchar(50) = '',
@.DataNascimento DateTime,
@.Sexo Char(1),
@.CPF Varchar(12)
)
As
Set Nocount On
Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
GO
Simple.Isn't it ? So...I need to retrieve the ID from this insert command
when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
use @.@.Identity!
Thanks in advance,
Daniel GrohDaniel
If you are using SQL Server 2000 you can use SCOPE_IDENITY() function
INSERT INTO Table (col) VALUES (1)
SELECT SCOPE_IDENITY()
Note : there is a difference between @.@.IDENTITY and SCOPE_IDENTITY() which
may bring unexpected result
See BOL for details
"Daniel Groh" <newsgroupms@.gmail.com> wrote in message
news:u4mnT$8TFHA.3308@.TK2MSFTNGP14.phx.gbl...
> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>|||Please don't multipost ,it is answered in .programming
"Daniel Groh" <newsgroupms@.gmail.com> wrote in message
news:u4mnT$8TFHA.3308@.TK2MSFTNGP14.phx.gbl...
> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>|||Hi
You can use this:
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
This will help you solve the problem
thanks and regards
Chandra
"Daniel Groh" wrote:

> Hi,
> I have the following proc:
> CREATE PROCEDURE SP_CadastraPessoaFisica
> (
> @.Email Varchar(60) = '',
> @.Senha Varchar(10) = '',
> @.Nome Varchar(50) = '',
> @.Sobrenome Varchar(50) = '',
> @.DataNascimento DateTime,
> @.Sexo Char(1),
> @.CPF Varchar(12)
> )
> As
> Set Nocount On
> Insert Into Usuario(Email,Senha) Values(@.Email,@.Senha)
> GO
> Simple.Isn't it ? So...I need to retrieve the ID from this insert command
> when inserted. Should I use @.@.Identity ? How do i do ? I don't know how to
> use @.@.Identity!
> --
> Thanks in advance,
> Daniel Groh
>
>

Wednesday, March 7, 2012

Retrieve the ID of the record just added

I would like to retreive the identity field value of a record that was just added to the table.

In other words, I have a form and on submission, if it is a new record, I would like to know the identity value that the SQL Server has assigned it.

This may be overkill, but here is my code to process the form:

Protected Sub processForm(ByVal thisID As String, ByVal myAction As String)
Dim sqlConn As New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))
sqlConn.Open()
Dim sql As String
Select Case myAction
Case "save"
If thisID > 0 Then
sql = "update INCIDENT set " & _
"RegionID = @.RegionID, " & _
"DistrictID = @.DistrictID, " & _
"DateReported = @.DateReported, " & _
..CODE...
"WHERE IncidentID = " & myIncidentID
Else
sql = "insert into INCIDENT(" & _
"RegionID, " & _
"DistrictID, " & _
"DateReported, " & _
...CODE...
") " & _
"values(" & _
"@.RegionID, " & _
"@.DistrictID, " & _
"@.DateReported, " & _
...CODE...
")"
End If
Case "delete"
sql = "delete from INCIDENT where IncidentID = " & myIncidentID
Case Else
End Select

Dim sqlComm As New SqlCommand(sql, sqlConn)
sqlComm.Parameters.Add(New SqlParameter("@.RegionID", SqlDbType.NVarChar))
sqlComm.Parameters.Add(New SqlParameter("@.DistrictID", SqlDbType.NVarChar))
sqlComm.Parameters.Add(New SqlParameter("@.DateReported", SqlDbType.NVarChar))
...CODE...

sqlComm.Parameters.Item("@.RegionID").Value = ddRegionID.SelectedValue
sqlComm.Parameters.Item("@.DistrictID").Value = ddDistrictID.SelectedValue
sqlComm.Parameters.Item("@.DateReported").Value = db.handleDate(txtDateReported.SelectedDate)
...CODE...

Dim myError As Int16 = sqlComm.ExecuteNonQuery
'Response.Redirect("incident.aspx?id=" & )
End Sub

The response.redirect at the end of the sub is where I would like to put the identity field value.

This has been a popular question over the past 2 days.Check out these posts, you should find what you need:415207 and416141

____________________________________________________________________

Updated hyperlinks on January 9, 2006

|||Thanks! That did it.|||

Hi

I have the same problem but those posts are no longer there. Are you able to help me out?

I couldn't work it out so I created a date/time field called StartDate for when each record is entered. I was trying to use that to grab the particular eventID.

Dim EventID =""

tbEventIDTest.Text =""

Dim EventDataSource1AsNew SqlDataSource()

EventDataSource1.ConnectionString = ConfigurationManager.ConnectionStrings("ASPNETDBConnectionString").ToString

EventDataSource1.SelectCommandType = SqlDataSourceCommandType.Text

EventDataSource1.SelectCommand ="SELECT EventID FROM Event "WHERE ([StartDate] = @.StartDate)"

EventID = EventDataSource1.SelectParameters.Item(EventID)

tbEventIDTest.Text = EventID

Thanks, any help will be appreciated.

|||

Hi

Call SCOPE_IDENTITY() to retrieve Identity.

Take a look atRetrieving Identity or Autonumber Valuesfor sample code.

|||thanks alot|||

gevans:

I have the same problem but those posts are no longer there.

Sorry I'm so late to reply. I've now updated that post so that the hyperlinks work; the old links only worked with the older version of the software used here.

Saturday, February 25, 2012

Retrieve Identity on insert: what if table has 2 identity columns

I have a table with 2 identity columns:
ID int identity(200100,1) not null,
OrderNo int Identity(550000,1) not null,
OrderName varchar(60) not null,
etc.
How do I get the values set by SQL server for ID and OrderNo when I insert
a new row in the table ?
Thanks in advance,Eve
If you are sitting on SQL Server 2000 then perform after inserting
SELECT SCOPE_IDENTITY()
Otherwise SELECT @.@.IDENTITY
"Eve" <Eve@.discussions.microsoft.com> wrote in message
news:F1824CDF-BC5D-4E89-98DA-6364A036B577@.microsoft.com...
> I have a table with 2 identity columns:
> ID int identity(200100,1) not null,
> OrderNo int Identity(550000,1) not null,
> OrderName varchar(60) not null,
> etc.
> How do I get the values set by SQL server for ID and OrderNo when I
insert
> a new row in the table ?
> Thanks in advance,
>|||It seems that there is a relationship between the two numbers.Seeing as you
can't have two identity columns. Why don't you use a formula for the ordern
o
Alter table <table> add OrderNo As ID + 300000.
"Eve" wrote:

> I have a table with 2 identity columns:
> ID int identity(200100,1) not null,
> OrderNo int Identity(550000,1) not null,
> OrderName varchar(60) not null,
> etc.
> How do I get the values set by SQL server for ID and OrderNo when I inser
t
> a new row in the table ?
> Thanks in advance,
>|||And on another note. I can't see why you need and ID since the OrderNo is
already unique...
Why is this ?
"Eve" wrote:

> I have a table with 2 identity columns:
> ID int identity(200100,1) not null,
> OrderNo int Identity(550000,1) not null,
> OrderName varchar(60) not null,
> etc.
> How do I get the values set by SQL server for ID and OrderNo when I inser
t
> a new row in the table ?
> Thanks in advance,
>|||I think you are mistaken. Only one IDENTITY column per table is permitted.
Please post the CREATE TABLE statement for your table so that we can
understand what you mean.
In SQL Server 2000 use SCOPE_IDENTITY() to retrieve the last inserted
IDENTITY value.
David Portas
SQL Server MVP
--

Retrieve Identity Field Value from a stored procedure into a form

OK first time poster, so hello everyone in advance. Right i'm sure this is a simple problem to solve, but I'm just getting the hang of SQL 2000. What I've got is a form where I input the values and then through a procedure these values are inserted into a table. That's fine. However I now need to open a subform which is linked by the ID field created through the first procedure. How do I retrieve that value back into the form??

The procedure code is

CREATE PROCEDURE InsertFamilyDetails

@.CarerIDvarChar(6),
@.FamilyNamevarChar(30),
@.Address1varChar(30),
@.Address2varChar(30),
@.Address3varChar(30),
@.PostCodeMain varChar(4),
@.PostCodeSubvarChar(30),
@.PhoneNovarChar(16),
@.LocalTransport varChar(200),
@.Leisure varChar(200),
@.School varChar(200),
@.RulesvarChar(250),
@.Resultint OUTPUT

AS

DECLARE @.FamilyID int;

BEGIN TRANSACTION

-- Insert New Family

SELECT @.FamilyID=@.@.Identity

INSERT INTO tblWfsFamilyDetails

(intCarerID,txtFamilyName,txtAddress1,txtAddress2, txtAddress3,txtPostCodeMain,txtPostCodeSub,txtPhon eNo,memoLocalTransport, memoLeisure, memoSchool,memoRules)

VALUES

(@.CarerID,@.FamilyName,@.Address1,@.Address2,@.Address 3,@.PostCodeMain,@.PostCodeSub,@.PhoneNo,@.LocalTransp ort,@.Leisure,@.School,@.Rules)

IF @.RESULT<1

BEGIN

ROLLBACK TRANSACTION;

RETURN -1

END

SET @.RESULT=1

COMMIT TRANSACTION
GO

Whereas, the VB Code is

Private Sub cmdInsert_Click()
Set cmd = New ADODB.Command
cmd.ActiveConnection = con
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "insertFamilyDetails"

' FieldNames Assigned to FormControls

cmd.Parameters.Append cmd.CreateParameter("CarerID", adInteger, adParamInput, 6, txtCarerID)
cmd.Parameters.Append cmd.CreateParameter("FamilyName", adVarChar, adParamInput, 30, txtFamilyName)
cmd.Parameters.Append cmd.CreateParameter("Address1", adVarChar, adParamInput, 30, txtAddress1)
cmd.Parameters.Append cmd.CreateParameter("Address2", adVarChar, adParamInput, 30, txtAddress2)
cmd.Parameters.Append cmd.CreateParameter("Address3", adVarChar, adParamInput, 30, txtAddress3)
cmd.Parameters.Append cmd.CreateParameter("PostCodeMain", adVarChar, adParamInput, 4, txtPostCodeMain)
cmd.Parameters.Append cmd.CreateParameter("PostCodeSub", adVarChar, adParamInput, 4, txtPostCodeSub)
cmd.Parameters.Append cmd.CreateParameter("PhoneNo", adVarChar, adParamInput, 12, txtPhoneNo)
cmd.Parameters.Append cmd.CreateParameter("LocalTransport", adVarChar, adParamInput, 200, memoLocalTransport)
cmd.Parameters.Append cmd.CreateParameter("Leisure", adVarChar, adParamInput, 200, memoLeisure)
cmd.Parameters.Append cmd.CreateParameter("School", adVarChar, adParamInput, 200, memoSchool)
cmd.Parameters.Append cmd.CreateParameter("Rules", adVarChar, adParamInput, 200, memoRules)
cmd.Parameters.Append cmd.CreateParameter("Result", adInteger, adParamOutput) ' OutPut Returns Result Parameter a Value

cmd.Execute

Res = cmd("Result")

If (Res = 1) Then
MsgBox "Family Inserted Successfully", , "Insert Family"
End If

Set cmd.ActiveConnection = Nothing

End Sub

Apologise for wasting your time if this something obvious, but like I say I'm learning.pretty simple - in your stored procedure immediately after the line values(....) do this: set @.retval = @.@.IDENTITY

that will automatically put the new ID into the variable @.retval. Then you can do
Set @.RESULT = @.retval|||

Quote:

Originally Posted by scripto

pretty simple - in your stored procedure immediately after the line values(....) do this: set @.retval = @.@.IDENTITY

that will automatically put the new ID into the variable @.retval. Then you can do
Set @.RESULT = @.retval


scope_identity() function is a better choice than @.@.IDENTITY as there might be some triggers defined on tblWfsFamilyDetails table.

Retrieve Identity after Insert

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!

<

scriptrunat="server">ProtectedSub SqlDataSource1_Inserting(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.SqlDataSourceCommandEventArgs)Handles SqlDataSource1.Inserting

e.Command.Parameters(

"@.house").Size = 5EndSubProtectedSub SqlDataSource1_Inserted(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.SqlDataSourceStatusEventArgs)Handles SqlDataSource1.InsertedDim house = e.Command.Parameters("@.house").Value

Response.Write(house)

EndSubProtectedSub Wizard1_FinishButtonClick(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.WizardNavigationEventArgs)EndSubProtectedSub SqlDataSource1_Selecting(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)EndSub</script>

<

asp:SqlDataSourceID="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:ParameterName="housenum"Type="String"/><asp:ParameterName="streeraddr"Type="String"/><asp:ParameterName="aptnum"Type="String"/><asp:ParameterName="city"Type="String"/><asp:ParameterName="state"Type="String"/><asp:ParameterName="zipcode"Type="String"/><asp:ParameterName="HHPhone"Type="String"/><asp:ParameterType="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?

Can anybody help me with this please?|||

I believe that you want to handle the Inserted event. Here's a snippet from the help that should lead you on the right direction.

Sub On_Inserted(ByVal sender As Object, ByVal e As SqlDataSourceStatusEventArgs)
Dim command As DbCommand
command = e.Command

' The label displays the primary key of the recently inserted row.
Label1.Text = command.Parameters("@.PK_New").Value.ToString()

' Explicitly call DataBind to refresh the data
' and show the newly inserted row.
GridView1.DataBind()
End Sub 'On_Inserted