Monday, March 26, 2012
How to get the name of the column that is an Identity Column
is an IDENTITY column. I need to remove the IDENTITY property on all tables
.
Thankshi,
Using syscolumns system table allocated in every db.
"CSHARPITPRO" wrote:
> I would like to know the best method of getting the name of the column if
it
> is an IDENTITY column. I need to remove the IDENTITY property on all tabl
es.
> Thanks|||There is no way to just remove the IDENTITY property using T-SQL, unless you
are just going to drop the column altogether.
If you just want a list so you can go deal with this manually:
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY
(
OBJECT_ID(TABLE_NAME), COLUMN_NAME, 'IsIdentity'
) = 1
ORDER BY TABLE_NAME;
"CSHARPITPRO" <CSHARPITPRO@.discussions.microsoft.com> wrote in message
news:2603575C-72FA-4FB5-A74D-AEA9B32C6EC4@.microsoft.com...
>I would like to know the best method of getting the name of the column if
>it
> is an IDENTITY column. I need to remove the IDENTITY property on all
> tables.
> Thanks|||this will get you a list of all identity columns for user defined tables:
select o.name, col_name(i.object_id, column_id)
from sys.objects o join sys.identity_columns i on o.object_id = i.object_id
where o.type = 'U'
order by o.name|||Thanks Aaron,
This information is very helpful. I am just going to handle it
manually. Thank you very much!
"Aaron Bertrand [SQL Server MVP]" wrote:
> There is no way to just remove the IDENTITY property using T-SQL, unless y
ou
> are just going to drop the column altogether.
> If you just want a list so you can go deal with this manually:
> SELECT TABLE_NAME, COLUMN_NAME
> FROM INFORMATION_SCHEMA.COLUMNS
> WHERE COLUMNPROPERTY
> (
> OBJECT_ID(TABLE_NAME), COLUMN_NAME, 'IsIdentity'
> ) = 1
> ORDER BY TABLE_NAME;
>
>
> "CSHARPITPRO" <CSHARPITPRO@.discussions.microsoft.com> wrote in message
> news:2603575C-72FA-4FB5-A74D-AEA9B32C6EC4@.microsoft.com...
>
>|||> this will get you a list of all identity columns for user defined tables:
> select o.name, col_name(i.object_id, column_id)
> from sys.objects o join sys.identity_columns i on o.object_id =
> i.object_id
> where o.type = 'U'
> order by o.name
Sure, in SQL Server 2005. The user didn't post their target version.
The query I posted works in 2000 as well.|||Thanks Enric
"Enric" wrote:
> hi,
> Using syscolumns system table allocated in every db.
> "CSHARPITPRO" wrote:
>|||Thanks!
"PhxSam" wrote:
> this will get you a list of all identity columns for user defined tables:
> select o.name, col_name(i.object_id, column_id)
> from sys.objects o join sys.identity_columns i on o.object_id = i.object_i
d
> where o.type = 'U'
> order by o.namesql
Friday, March 23, 2012
how to get the inserted record id
You must be specifying some criteria for the deletes. When
you specify, do a select on that field.
>--Original Message--
>hi all
>I have auto number field in my table with title ID
>I wantted to know when we add a record in table, SQL
server takes the responsibility of increntin / adding auto
number in field.
>Please advise if there is any way to get this auto number
from table. Like we have table inserted and deleted ... (
getting maximum is not working in multiple user
environemnt ) Is there any stored procedure or variable i
can query ?
>thanks.
>Khurram Alam
>In SQL Server 2000, @.@.IDENTITY will work, however, in a high volume
multi-user environment, the BOL suggest that you use the SCOPE_IDENTITY()
function instead.
For more information, please see the Books Online
Rick Sawtell
MCT, MCSD, MCDBA
"ChrisR" <anonymous@.discussions.microsoft.com> wrote in message
news:0a4a01c47afa$aa5f6e10$a501280a@.phx.gbl...[vbcol=seagreen]
> Select @.@.identity will give you the record just inserted.
> You must be specifying some criteria for the deletes. When
> you specify, do a select on that field.
>
>
> server takes the responsibility of increntin / adding auto
> number in field.
> from table. Like we have table inserted and deleted ... (
> getting maximum is not working in multiple user
> environemnt ) Is there any stored procedure or variable i
> can query ?
how to get the inserted record id
You must be specifying some criteria for the deletes. When
you specify, do a select on that field.
>--Original Message--
>hi all
>I have auto number field in my table with title ID
>I wantted to know when we add a record in table, SQL
server takes the responsibility of increntin / adding auto
number in field.
>Please advise if there is any way to get this auto number
from table. Like we have table inserted and deleted ... (
getting maximum is not working in multiple user
environemnt ) Is there any stored procedure or variable i
can query ?
>thanks.
>Khurram Alam
>
In SQL Server 2000, @.@.IDENTITY will work, however, in a high volume
multi-user environment, the BOL suggest that you use the SCOPE_IDENTITY()
function instead.
For more information, please see the Books Online
Rick Sawtell
MCT, MCSD, MCDBA
"ChrisR" <anonymous@.discussions.microsoft.com> wrote in message
news:0a4a01c47afa$aa5f6e10$a501280a@.phx.gbl...[vbcol=seagreen]
> Select @.@.identity will give you the record just inserted.
> You must be specifying some criteria for the deletes. When
> you specify, do a select on that field.
>
> server takes the responsibility of increntin / adding auto
> number in field.
> from table. Like we have table inserted and deleted ... (
> getting maximum is not working in multiple user
> environemnt ) Is there any stored procedure or variable i
> can query ?
Wednesday, March 21, 2012
How to get the @@Identity for multiple Inserts?
Iam in a situtation where i have a query Which Inserts into a table from Select statement. But there is another table which is dependent on the Primay key of the inserted table.
Since the insert is multiple iam not able to use the @.@.Identity.
Can some one suggest me How can i over come this situtation.
Also Triggers cant be used as the the records are of huge numbers.
Eg:-
INSERT INTO Users (FirstName, SecondName) SELECT FirstName, SecondName From Old_Users
INSERT INTO UserDependent(UserID,OtherFields)
VALUES(@.@.Identity,'SomeOtherValue')
Thanks
Tanveerrewrite to a cursor insert
or
after the hughe insert, determine which are new and update/insert the depending table accordingly.
I'm not entirely sure what you mean by 'this situation' though.|||A better solution would be to create a temporary table .. lets say UserConsolidated like
(Userid,FirstName, SecondName,OtherFields) and then use this table to get data into User and UserDependent.|||At least for now, the @.@.identity values are processed as a block, in other words if you have five different inserts going (on different spids) at the same time, each block of the five will have a contiguous range of @.@.identity values. This means that if you insert 30 rows, the @.@.identity value will be for the first row, and @.@.identity+29 will be the value for the last row in your insert.
Note that this will change at some point in time, probably in the release after Yukon.
-PatP
Friday, February 24, 2012
How to get identity from parent Table and insert it into the child table
F_NAME L_NAME COURSE_ID COURSE_DESC
this table contains 10 records ,and I need to insert these records into 2
tables .TBSTUDENT and TBCOURSE.
in TBSTUDENT ,I have student_id which is an identity column and in TBCOURSE
,I have a foriegn key to this field. How can I isert 10 records from the
first table into TBSTUDENT AND TBCOURSE ,where I should first get the
identity generated from the first insert and use it in the second
insert(into TBCOURSE).
ThanksDECLARE @.myID int
INSERT INTO ......
VALUES ......
SELECT @.myID = SCOPE_IDENTITY()
Message posted via http://www.webservertalk.com|||I have to insert into two tables at the same time?
I didn't get it!!!
Thanks
"E B via webservertalk.com" <forum@.webservertalk.com> wrote in message
news:6bd904766fc843f1bc532d3a3cd059f1@.SQ
webservertalk.com...
> DECLARE @.myID int
> INSERT INTO ......
> VALUES ......
> SELECT @.myID = SCOPE_IDENTITY()
> --
> Message posted via http://www.webservertalk.com
How to get identity from parent Table and insert it into the child
Are you going to do this in SINGLE_USER mode?
AMB
"RayAll" wrote:
> I have a table with the following schema
> F_NAME L_NAME COURSE_ID COURSE_DESC
> this table contains 10 records ,and I need to insert these records into 2
> tables .TBSTUDENT and TBCOURSE.
> in TBSTUDENT ,I have student_id which is an identity column and in TBCOURS
E
> ,I have a foriegn key to this field. How can I isert 10 records from the
> first table into TBSTUDENT AND TBCOURSE ,where I should first get the
> identity generated from the first insert and use it in the second
> insert(into TBCOURSE).
> Thanks
>
>This is a process called by a DTS package and once at a time.
Thanks for your reply.
"Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> wrote in message
news:628A3F8D-9DF9-4EED-B061-3C22A3A266DF@.microsoft.com...
> Is this a one time process?
> Are you going to do this in SINGLE_USER mode?
>
> AMB
>
> "RayAll" wrote:
>
How to get identity from parent Table and insert it into the child
is an example of where using Surrogate keys can be a bit trickier than using
meaningful keys... In order to do this is robust way, you must have some
mechanism (Other than the Surogate Identity Key) to "connect" the child
records to the right parent record.
Now to the table schema... regarding Your "Child" table, the one you have
named TBCOURSE, from the name, it would seem to contain Course data... But i
f
that's true, it makes no sense to have a FK in it that points to one row in
a
table which contains Students.. That implies that for each course, there is
but one and only one student, or some single student that plays some special
distinct role related to that course... SO, since that makes no sense, the
next logical question is
Exactly what do the rows in these tables represent? nd then...
What exactly are you trying to do with this insert ?
"RayAll" wrote:
> I have a table with the following schema
> F_NAME L_NAME COURSE_ID COURSE_DESC
> this table contains 10 records ,and I need to insert these records into 2
> tables .TBSTUDENT and TBCOURSE.
> in TBSTUDENT ,I have student_id which is an identity column and in TBCOURS
E
> ,I have a foriegn key to this field. How can I isert 10 records from the
> first table into TBSTUDENT AND TBCOURSE ,where I should first get the
> identity generated from the first insert and use it in the second
> insert(into TBCOURSE).
> Thanks
>
>Thanks for your reply.
No,The schema of the table is not odd ,because this is a buffer table which
I amusing in a DTS package to read records from a CSV file into this table
(and do the validation during transformation) and then from here I have to
distribute the records into the relavant tables.Dose it still seem to be
odd?
I made the chema myself ,because I wanted to simplify things here are the
schema of the 3 other tables I am trying to insert into.
**************CLIENT:
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[PE_CLI_FK]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[PROGRAM_ENROLLMENT] DROP CONSTRAINT PE_CLI_FK
GO
CREATE TABLE [dbo].[CLIENT] (
[INTERNAL_ID] [numeric](12, 0) IDENTITY (1, 1) NOT NULL ,
<--this is the identity field
[CLIENT_ID] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[USERNAME] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
.....
) ON [PRIMARY]
GO
***********PROGRAM_ENROLLMENT:
CREATE TABLE [dbo].[PROGRAM_ENROLLMENT] (
[PROGRAM_ENROLLMENT_ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
[INTERNAL_ID] [numeric](12, 0) NOT NULL , <--This is
foriegn key to the Client Table
...
) ON [PRIMARY]
GO
***********PERSONAL_INFO:
CREATE TABLE [dbo].[PERSONAL_INFO] (
[FIRST_NAME] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[MIDDLE_NAME] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
...
[INTERNAL_ID] [numeric](12, 0) NOT NULL , <--this is also a foriegn
key to Client
...
[Timestamp] [timestamp] NOT NULL
) ON [PRIMARY]
GO
******************
Here is what I'm trying to do:
I am trying to get each record from my buffer table and insert it into these
three tables,but before inserting into the Programe_enrolment and
Personal_info ,I have to have the InternalID of the Client Table,then I
should use the internalID in every other table I insert the rest of the
record.
For instance let's say this is my record in buffer table:
FirstName clientID UserName
Ray 1233 ray5531 ............
First I insert this into client and I get the internalID of for instance
1000 ,then I need to use this and insert other fields of this record into
Personal_Info and PROGRAM_ENROLLMENT.
Same process for all the other records in the buffer table.
Thanks for your time.
"CBretana" <cbretana@.areteIndNOSPAM.com> wrote in message
news:A31711F6-1A30-4DDC-9741-5EF81D96CE62@.microsoft.com...
> Leaving aside for the moment your table schema, which seems a bit odd,
> This
> is an example of where using Surrogate keys can be a bit trickier than
> using
> meaningful keys... In order to do this is robust way, you must have some
> mechanism (Other than the Surogate Identity Key) to "connect" the child
> records to the right parent record.
> Now to the table schema... regarding Your "Child" table, the one you have
> named TBCOURSE, from the name, it would seem to contain Course data... But
> if
> that's true, it makes no sense to have a FK in it that points to one row
> in a
> table which contains Students.. That implies that for each course, there
> is
> but one and only one student, or some single student that plays some
> special
> distinct role related to that course... SO, since that makes no sense,
> the
> next logical question is
> Exactly what do the rows in these tables represent? nd then...
> What exactly are you trying to do with this insert ?
> "RayAll" wrote:
>|||Your table design is incomplete because you haven't declared natural keys on
these tables. Declare the proper keys and it's easy to do what you require.
See this example:
http://www.google.co.uk/groups?selm...%40giganews.com
On the other hand, replacing one surrogate key with another seems
particularly pointless anyway.
David Portas
SQL Server MVP
--|||Thanks for your reply.
Where am I replacing surrogate key with another one.I have only one
surrogate key in client and I am using this in other tables to maintanin a
link between client and other informations.What's wrong with this?
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:0t-dner_57mHRdTfRVn-vg@.giganews.com...
> Your table design is incomplete because you haven't declared natural keys
> on these tables. Declare the proper keys and it's easy to do what you
> require. See this example:
> http://www.google.co.uk/groups?selm...%40giganews.com
> On the other hand, replacing one surrogate key with another seems
> particularly pointless anyway.
> --
> David Portas
> SQL Server MVP
> --
>|||What's wrong is that IDENTITY should never be the *only* key of a table. By
definition IDENTITY should always be redundant and breaking that rule
destorys integrity. For example, you don't want duplicate clients with the
*same* Client_ID and Username. Declare the keys on the other columns and
your problem is solved. Take a look at the example I posted.
David Portas
SQL Server MVP
--|||Symantically ,there is a compund key there ,which I can rely on.However It
hasn't been created,but technically there is no record with same "ClientID"
and "Affiliate_ID".
Yes,your answer was really helpfu.I think that's the way to do so.
Thanks
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:OZadncsqxMs9QNTfRVn-jw@.giganews.com...
> What's wrong is that IDENTITY should never be the *only* key of a table.
> By definition IDENTITY should always be redundant and breaking that rule
> destorys integrity. For example, you don't want duplicate clients with the
> *same* Client_ID and Username. Declare the keys on the other columns and
> your problem is solved. Take a look at the example I posted.
> --
> David Portas
> SQL Server MVP
> --
>
How to get identity from parent Table and insert it into the c
<<<
this table contains 10 records ,and I need to insert these records into 2
tables .TBSTUDENT and TBCOURSE.
These two tables TBSTUDENT and TBCOURSE, are the tables I was directing my
comments to... In your last post, you did not mention them at all... Instead
you describe THREE Tables that are destinations for the data.
<<<<<<
...wanted to simplify things here are the
schema of the 3 other tables I am trying to insert into.
CLIENT, PROGRAM_ENROLLMENT, and PERSONAL_INFO...
So now I am triply
. In any event, in order to help, it isnecessary to have some idea about what the schema actually is, and what
abstraction (What real world biusiness "THING") each record in the table
respresents. Normally the name of the table helps with that, but when this
is noot obvious, then we have to guess based on what the joins in the code
that is uploaded for us to look at.
So: What exactly does an individual record in each of these three tables
represent?
And What does each row in the Import table represent ? (Is that the table
with schema F_NAME L_NAME COURSE_ID COURSE_DESC ')
Regards,
Charly
"RayAll" wrote:
> Thanks for your reply.
> No,The schema of the table is not odd ,because this is a buffer table whic
h
> I amusing in a DTS package to read records from a CSV file into this table
> (and do the validation during transformation) and then from here I have to
> distribute the records into the relavant tables.Dose it still seem to be
> odd?
> I made the chema myself ,because I wanted to simplify things here are the
> schema of the 3 other tables I am trying to insert into.
> **************CLIENT:
> if exists (select * from dbo.sysobjects where id =
> object_id(N'[dbo].[PE_CLI_FK]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
> ALTER TABLE [dbo].[PROGRAM_ENROLLMENT] DROP CONSTRAINT PE_CLI_FK
> GO
> CREATE TABLE [dbo].[CLIENT] (
> [INTERNAL_ID] [numeric](12, 0) IDENTITY (1, 1) NOT NULL ,
> <--this is the identity field
> [CLIENT_ID] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [USERNAME] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> ......
> ) ON [PRIMARY]
> GO
>
> ***********PROGRAM_ENROLLMENT:
> CREATE TABLE [dbo].[PROGRAM_ENROLLMENT] (
> [PROGRAM_ENROLLMENT_ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
> [INTERNAL_ID] [numeric](12, 0) NOT NULL , <--This is
> foriegn key to the Client Table
> ...
> ) ON [PRIMARY]
> GO
> ***********PERSONAL_INFO:
> CREATE TABLE [dbo].[PERSONAL_INFO] (
> [FIRST_NAME] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [MIDDLE_NAME] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> ....
> [INTERNAL_ID] [numeric](12, 0) NOT NULL , <--this is also a foriegn
> key to Client
> ....
> [Timestamp] [timestamp] NOT NULL
> ) ON [PRIMARY]
> GO
>
> ******************
> Here is what I'm trying to do:
> I am trying to get each record from my buffer table and insert it into the
se
> three tables,but before inserting into the Programe_enrolment and
> Personal_info ,I have to have the InternalID of the Client Table,then I
> should use the internalID in every other table I insert the rest of the
> record.
> For instance let's say this is my record in buffer table:
> FirstName clientID UserName
> Ray 1233 ray5531 ............
> First I insert this into client and I get the internalID of for instance
> 1000 ,then I need to use this and insert other fields of this record into
> Personal_Info and PROGRAM_ENROLLMENT.
> Same process for all the other records in the buffer table.
>
> Thanks for your time.
>
>
>
>
>
> "CBretana" <cbretana@.areteIndNOSPAM.com> wrote in message
> news:A31711F6-1A30-4DDC-9741-5EF81D96CE62@.microsoft.com...
>
>I'm sorry if I made you
.However I think I am getting close to wht Iwant(I will discuss it later)
Forget about the first post.
Ok,
Client: represents a client of our affiliates it says that this clientID
,with this AfflicateID (unique key on this two)has this Internal_ID
.Internal_ID now represents this person in all other tables.
so far so good?
Personal_Info :represents the personal information about this
guy(Unfortunately it is in another table and it's related to the client by
internal_ID) ,information like spouse name,last date he kissed somebody and
bluh bluh bluh is stored in this table
Program_enrolment :contains information about programs that client has
participated so far,this table contains programe_code ,program_startdate and
bluh bluh bluh and again it's related to the client table using Internal_ID
Is that clear so far?
Now ,each record in CSV file which I later import it to a buffer table
contains all these information in one line.for instance it says that this
guy who belongs to this affiliate and has enroled in this program and his
wife name is "Eve" and last time he kissed somebody was yesterday and bluh
bluh bluh.so for inserting this record into our database I need to sperate
each records into different portions .First I have to insert some fields
into client Table and get our own internalID ,because I need them later in
other Tables.I am not using only surrogate key in client Table because
"ClientID and Afflicate Id" is also unique.
based on this I have some idea ,I'm not sure if it works( I got the idea
from David's post,right above us)
Do you think there is something wrong with this schema up to now?
I insert into the client table ,it gives the record an identity(Internal_ID)
(which I don't care for now).
then I join my import Table with Client Table based on "ClientID and
Afflicate Id" and extract Internal_ID and insert it into two other tables.
How about this?
Thanks
"CBretana" <cbretana@.areteIndNOSPAM.com> wrote in message
news:8D5178C2-0D79-4B11-A817-59B840C86B04@.microsoft.com...
> Your original post mentioned two tables as destinations for the data,
> <<<
> this table contains 10 records ,and I need to insert these records into 2
> tables .TBSTUDENT and TBCOURSE.
> These two tables TBSTUDENT and TBCOURSE, are the tables I was directing my
> comments to... In your last post, you did not mention them at all...
> Instead
> you describe THREE Tables that are destinations for the data.
> <<<<<<
> ...wanted to simplify things here are the
> schema of the 3 other tables I am trying to insert into.
> CLIENT, PROGRAM_ENROLLMENT, and PERSONAL_INFO...
> So now I am triply
. In any event, in order to help, it is> necessary to have some idea about what the schema actually is, and what
> abstraction (What real world biusiness "THING") each record in the table
> respresents. Normally the name of the table helps with that, but when
> this
> is noot obvious, then we have to guess based on what the joins in the code
> that is uploaded for us to look at.
> So: What exactly does an individual record in each of these three tables
> represent?
> And What does each row in the Import table represent ? (Is that the table
> with schema F_NAME L_NAME COURSE_ID COURSE_DESC ')
> Regards,
> Charly
>
> "RayAll" wrote:
>|||See InLine...
"RayAll" wrote:
> I'm sorry if I made you
.However I think I am getting close to whtI
> want(I will discuss it later)
> Forget about the first post.
> Ok,
> Client: represents a client of our affiliates it says that this clientID
> ,with this AfflicateID (unique key on this two)has this Internal_ID
> ..Internal_ID now represents this person in all other tables.
> so far so good?
No, not good already... If this table represents a client... then unique key
should be on CLientID by itself, not ClientID and AffiliateID... The fact
that your key is on CLientID AND AffiliateID means that mutiple records can
exist for the same ClientID, so this table CANNOT represent Clients, it must
represent ASSOCIATIONS (of what type I don't know) between CLients and
Affiliates. And if it does, then there has to be another two tables
somewhere - one whose records actually do represesnt CLIENTS, and another
table whose records represent AFFILIATES...|||The reason we have Client Table is that each client might belong to
different affiliates ,so there is a single peice of info kept in
Personal_INFO and here in client Table we say this client belongs to this
affiliate and this is our internal_ID if we want more information.
Dose that make sense?
Thanks,
"CBretana" <cbretana@.areteIndNOSPAM.com> wrote in message
news:B80EA846-73D1-4FDC-81DA-987A1D75A78D@.microsoft.com...
> See InLine...
> "RayAll" wrote:
>
> No, not good already... If this table represents a client... then unique
> key
> should be on CLientID by itself, not ClientID and AffiliateID... The fact
> that your key is on CLientID AND AffiliateID means that mutiple records
> can
> exist for the same ClientID, so this table CANNOT represent Clients, it
> must
> represent ASSOCIATIONS (of what type I don't know) between CLients and
> Affiliates. And if it does, then there has to be another two tables
> somewhere - one whose records actually do represesnt CLIENTS, and another
> table whose records represent AFFILIATES...
>|||Do you see that your CLIENT Table is really a CLIENT-AFFILIATE ASSOCIATION
("belonging") Table, and that your Personal_INFO table is (should be) the
CLient table ?
This is because each record in the CLIENT able represents, not a client, but
an association between a Client and an Affiliate...
And does each record in the Personal_INFO table actually represent a Client?
If it did, the Primary key in the Personal_INFO table woul be ClientID, not
InternalID... The way you have it is entirely possible that 2 records in the
CLIENT Table, for the SAME CLient, (with same ClientD) could "point" to 2
DIFFERENT rows in the Personal_INFO table...
So is there a table in your system that actually IS a Client Table? i.e.,
it has CLientID as it's unique Primary Key, and there is one and only one ro
w
per client in it?
"RayAll" wrote:
> The reason we have Client Table is that each client might belong to
> different affiliates ,so there is a single peice of info kept in
> Personal_INFO and here in client Table we say this client belongs to this
> affiliate and this is our internal_ID if we want more information.
> Dose that make sense?
> Thanks,
> "CBretana" <cbretana@.areteIndNOSPAM.com> wrote in message
> news:B80EA846-73D1-4FDC-81DA-987A1D75A78D@.microsoft.com...
>
>|||See inline please
> Do you see that your CLIENT Table is really a CLIENT-AFFILIATE ASSOCIATION
> ("belonging") Table, and that your Personal_INFO table is (should be) the
> CLient table ?
Yes,you are right ,but you should know that there are some semantics which
is beyond this discussion.I think the naming for Client is not good actually
,but the role is palying is right.
> And does each record in the Personal_INFO table actually represent a
> Client?
yes,it dose
> If it did, the Primary key in the Personal_INFO table woul be ClientID,
> not
> InternalID... The way you have it is entirely possible that 2 records in
> the
> CLIENT Table, for the SAME CLient, (with same ClientD) could "point" to 2
> DIFFERENT rows in the Personal_INFO table...
The internal_ID of the Personal_INFO is not an identity ,it's getting its
value from InternalID of Client and there is a one-to-one relationship
between them,how would it be possible to have multiple client_ids there?can
you give me an example?
> So is there a table in your system that actually IS a Client Table? i.e.,
> it has CLientID as it's unique Primary Key, and there is one and only one
> row
> per client in it?
>
No,that's the only table represeting the Client.
Thanks
> "RayAll" wrote:
>|||<The internal_ID of the Personal_INFO is not an identity ,it's getting its
<value from InternalID of Client and there is a one-to-one relationship
<between them,how would it be possible to have multiple client_ids there?can
<you give me an example?
Yes, the PK in the CLIENT table is NOT CLientID, it is ClientID AND
AffiliateID.
As you said, some clients are associated with more than one Affiliate, in
that case, won't there be multiple rows in CLIENT with the same ClientID,
(one for each of the Affiliates the client isassociated with)?
And each of these rows will have it's own unique InternalID, no?
So then, Do these Multiple InternalIDs (ALL FOR THE SAME CLIENT, right?), do
they not point to different rows in the Personal_INFO table'
Multiple rows in Personal_INFO for the SAME CLIENT, then, right ?|||
> Yes, the PK in the CLIENT table is NOT CLientID, it is ClientID AND
> AffiliateID.
> As you said, some clients are associated with more than one Affiliate, in
> that case, won't there be multiple rows in CLIENT with the same ClientID,
> (one for each of the Affiliates the client isassociated with)?
> And each of these rows will have it's own unique InternalID, no?
yes,right
> So then, Do these Multiple InternalIDs (ALL FOR THE SAME CLIENT, right?),
> do
> they not point to different rows in the Personal_INFO table'
yes,right.because in personal_info the key is Internal_ID (which is coming
from Client) and Education_level (which is another field) that make the rows
unique.I think the second field is the key.
> Multiple rows in Personal_INFO for the SAME CLIENT, then, right ?
yes but with different education_level.
>
Thanks for following this up.|||So Personal Infp also has an education_Level as part of the key as well'
That adds another twist to the puzzle... Bottom line, you really, REALLY
need to read a book or article or something about database design, and
database normalization... REGARDLESS Of the level of control you might have
over the database, or opportunity to redesign it properly.
The current design schema of your database is incredibly bad, and
uncorrectted, it will produce a nightmare of coding problems, data
inconsistency issues and maintenance headaches... The more you know about wh
y
and how it is messed up, the better you will be prepared to deal with these
issues, as they arise, even if you have no authority or approval from client
to correct them..
Good Luck !!
Charly
"RayAll" wrote:
>
> yes,right
> yes,right.because in personal_info the key is Internal_ID (which is coming
> from Client) and Education_level (which is another field) that make the ro
ws
> unique.I think the second field is the key.
> yes but with different education_level.
>
> Thanks for following this up.
>
>|||Thanks for your help.
"CBretana" <cbretana@.areteIndNOSPAM.com> wrote in message
news:D2DBA4FE-90AA-48A7-8B1C-E73367A61610@.microsoft.com...
> So Personal Infp also has an education_Level as part of the key as well'
> That adds another twist to the puzzle... Bottom line, you really,
> REALLY
> need to read a book or article or something about database design, and
> database normalization... REGARDLESS Of the level of control you might
> have
> over the database, or opportunity to redesign it properly.
> The current design schema of your database is incredibly bad, and
> uncorrectted, it will produce a nightmare of coding problems, data
> inconsistency issues and maintenance headaches... The more you know about
> why
> and how it is messed up, the better you will be prepared to deal with
> these
> issues, as they arise, even if you have no authority or approval from
> client
> to correct them..
> Good Luck !!
> Charly
> "RayAll" wrote:
>
Sunday, February 19, 2012
How to get identity field value after recordset update
This is what I have:
rsRec.AddNew
rsRec("RequisitionID") = intReqNum
rsRec("CreatedBy") = cint(session("empno"))
rsRec("DateCreated") = Now
rsRec.Update
intItemId = rsRec("ReqChildID")
rsRec.Close
Forgive me if this has already been posted, but I couldn't find it.
[edit to add:]
rsRec is an ADODB.Recordset in case that wasn't clear.Look at @.@.IDENTITY and SCOPE_IDENTITY in BOL.|||1 intItemId set identity for replication
2 use keyset recordset type|||I appreciate the quick replies.
I am using @.@.Identity and it works well enough for my purposes.
[edit] I found the BOL. Never even looked at it before. Thanks for pointing it out
Thanks again all.|||Look at SCOPE_IDENTITY... @.@.IDENTITY is global to all transactions on the table, where SCOPE_IDENTITY is limited to the scope of a single transaction. You could potentially get the ID for the wrong transaction with @.@.IDENTITY.|||Look at SCOPE_IDENTITY... @.@.IDENTITY is global to all transactions on the table, where SCOPE_IDENTITY is limited to the scope of a single transaction. You could potentially get the ID for the wrong transaction with @.@.IDENTITY.
Agree. But it's good to know what differs those cases. Let the user choose what he needs. Give him fishing rod, not fish ;) .|||Due to time constraints I went with @.@.Identity. The database hits aren't very common so I will assume a certain small probability that there will be an error from time to time.
That being said, I would prefer Scope_Identity for 100% accuracy. I am continuing to work with SCOPE_IDENTITY when I can to try to make it work for me. As of this morning I got it to supply the correct ID using enterprise manager to test. I'll eventually get it to work in my code.
Thank you guys for helping me solve this problem.|||@.@.identity may acquire a value of anything else only when the target table contains a trigger that performs an insert into another table with identity field. if this is the case then scope_identity() needs to be used.
on another thought, you should put dml statements into a stored procedure and call it from your front end.|||I inherited this app. I would love to convert it to using stored procedures. I just need to get this section done so I can have a completed app, and a happy boss. Then I can convert as I go to make it all easier to work with.
Grrrr... I can't seem to get SCOPE_IDENTITY() to happen on the page.
I have:
set cn = Server.CreateObject("ADODB.Connection")
set rsRec = Server.CreateObject("ADODB.Recordset")
set rsIdent = Server.CreateObject("ADODB.Recordset")
cn.Open dbConnection
rsRec.Open sSQL,cn, 3 ,3
rsRec.AddNew
rsRec("ReqID") = intReqNum
rsRec("CreatedBy") = cint(session("empno"))
rsRec("DateCreated") = Now
rsRec.Update
rsRec.Close
sSQL = "SELECT SCOPE_IDENTITY() as Ident"
rsIdent.Open sSQL,cn, 3 ,3
intItemId = rsIdent("Ident")
rsIdent.Close
I have no idea why this doesn't work. I thought as long as I keep the connection(cn) open then this would work. Guess I'm wrong? Do I need to use the same recordset?|||sSQL="insert tbl (...) values (...) select ident=scope_identity()"
set rsRec=cn.execute(sSQL)|||I have simplified the statements that are actually in the code. Although that suggestion would likely make it work(as it works when I test it in the Query Analyzer), there are quite a few conditions that would affect the SQL statement and at this point I don't have the time to switch it to that style.
Its' done for the time being. I pushed it out for beta.
I'm only sorry I couldn't get it all to work fast enough, but that's what updates are for.
Thanks again for the help and pointing me in the right direction.
How to get ID into field upon insert (SCOPE_IDENTITY() ?)
ID - primary key and identity field (seed 1 increment 1)
GroupID - int
Upon INSERT I want groupID to be the value of ID
The only way I can figure out how to do this (being inexperienced with sql) is to INSERT with GroupID = 0 and then do a SELECT @.iGroupID=SCOPE_IDENTITY() and then UPDATE the record. But even inside a transaction this seems error prone and not the right way. Can anyone tell me the correct way to do this. Thank you in advance.You can try using a trigger.
|||I hope you are using SQL Server 2000 ... If that being the case we can use UDFs to accomblish this task ... A typical code snippet for the same looks like below:
CREATE TABLE [dbo].[Table1] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[GroupID] [int] NOT NULL ,
[AnotherColumn] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]CREATE TRIGGER [InsertTrigger] ON [dbo].[Table1]
AFTER INSERT
AS
declare theCursor cursor for SELECT ID FROM inserted
open theCursor
declare @.ThisID int
select @.ThisID = -1
while 1 = 1
begin
fetch next from theCursor into @.ThisID
if @.@.fetch_status <> 0
break
Update Table1
Set GroupID = @.ThisID
WHERE ID=@.ThisID
end
close theCursor
deallocate theCursor
CREATE FUNCTION dbo.GetIdentity() RETURNS INT AS
BEGIN
RETURN (IDENT_CURRENT('vin_test'))
END
CREATE TABLE vin_test
(
colAINT IDENTITY(1,1) NOT NULL,
colBINT DEFAULT dbo.GetIdentity(),
colCVARCHAR(10)
)
INSERT INTO vin_test (colC) VALUES ('Test')
SELECT * FROM vin_test|||Yes the ISP is server 2000 and my MSDE seems to support functions but prompts me to select from Inline, Table-values, Scalar-valued, can you please tell me which to select. Also I have about 20 tables I need to do this with. Do I need to write a function for each table?
THANKS!|||Yes, we need to create one for each table. I am sure it is better than creating 10 triggers ... :)
Select the scalar-valued function ...|||My final question:
Is the UDF better/safer/more stable/reliable then what I am doing in the stored procedure where inside a transaction I insert, get the scope_identity and then update the just inserted record. I understand my (hack/kludge?) method may take more server processing but I besides that I am wondering if it is any less reliable then the UDF method. (last question :) again, thanks.|||I can say it with certain that UDFs are quite stable ... There is no second thoughts on that statement. We have used this in our production code and have tested the same with concurrent users ... Works like a gem ... :) ...
Hmm ... the second part of the question has a couple of interesting points to backup:
1. Keep the transaction short. Which means if you have a big routine to do the same it is quite not advisible.
2. CPU cycles are not cheaper and so is memory. If you were to use SPs in such a fashion then we are using both ... :) ... And I dont recommend the same strongly ...
I know this is a delicate topic to answer and can raise a couple of eye-brows who are reading this ... But these are my views on the same. I am open to hear from others if they think otherwise ...|||stored procedures return only integers...UDF can return other datatypes like float...etc
other than that i guess both are similar...in terms of security/performance...etc|||Hmm ... Stored Procedures can also return more than one value using the OUTPUT parameter types ... And I feel that we can do things in UDF that are quite not possible with Stored Procedures ... Read my article on UDF at :http://www.extremeexperts.com/sql/articles/UDFFunctions.aspx ...
And for the present problem description ... I feel UDF is a cleaner and neater way rather than the conventional UDF approach ...
How to get generated identity value?
How can I retrieve generated identity value after insert a row into table in case I can identify inserted row?
(the INSERT statement is dynamic constructed and queried from data access layer, not in stored procedure)
Thanks,In the same batch, you can use @.@.identity (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_globals_50u1.asp) or scope_identity() (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_sa-ses_6n8p.asp). Once you allow the batch to end, it gets a lot trickier to get the identity value back.
-PatP