Showing posts with label insert. Show all posts
Showing posts with label insert. Show all posts

Monday, March 26, 2012

how to get the primary key from the field of the row ive just inserted

I need to insert a row of data and return the value of the primary key id of the row.
I thought that something like this would work


int Key = (int)command.ExecuteScalar();

where command is SqlCommand object.

It doesn't work, maybe I've misunderstood the usage of ExecuteScalar.ExecuteScalar() returns the first row/first column of the resulet set. This should work IF part of the command contains something like SELECT Scope_IDentity() or SELECT @.@.IDENTITY after the insert, and the table has an IDENTITY column.sql

Wednesday, March 21, 2012

How to get the client IP Address in T-SQL ?

Hi,

My problem is -
I have a trigger for auditing the changes(insert/update/delete) in the database table.That is done and is working fine. But I need to have the client's IP address from where the changes are done. That I need in T-SQL, that means, not in any web form but in the SQL/T-SQL.

As I have checked many forums, I got that there is extended stored procedure in master database named xp_cmdshell which has xplog70.dll and when we execute this stored procedure with 'ipconfig' we can get the IP Address. But I do not need that in master database. I need that in my database say myDB.

So how to proceed further. I don't know whether to create extended SP which contains DLL or is there any other option.

Pls help
Thanks in advanceHave you tried calling the stored procedure* from within your "myDB"? :)|||See this the stored procedure code and call,

create Procedure sp_get_ip_address (@.ip varchar(40) out)
as
begin
Declare @.ipLine varchar(200)
Declare @.pos int
set nocount on
set @.ip = NULL
Create table #temp (ipLine varchar(200))
Insert #temp exec master..xp_cmdshell 'ipconfig'
select @.ipLine = ipLine
from #temp
where upper (ipLine) like '%IP ADDRESS%'
if (isnull (@.ipLine,'***') != '***')
begin
set @.pos = CharIndex (':',@.ipLine,1);
set @.ip = rtrim(ltrim(substring (@.ipLine ,
@.pos + 1 ,
len (@.ipLine) - @.pos)))
end
drop table #temp
set nocount off
end
go

declare @.ip varchar(40)
exec sp_get_ip_address @.ip out
print @.ip

But this is in the master Database.If I do this same thing in my database say myDB it gives error that it do not have extended SP|||Try

Exec dbo.sp_get_ip_address @.ip out|||If we exec this stored procedure in the trigger, How to store the output in the table or in some variable. Since I have tried this way - Insert #temp exec master..xp_cmdshell 'ipconfig' which gives error saying that -' insert and execute statments cannot be nested'. And if I first create the table with a column and then write - select * into #temp from exec sp_get_my_ip_address @.ip out, it gives error as incorrect syntax near exec|||Let's just confirm the DBMS that we're using...
I'm guessing SQL Server 2000, but please correct me if I'm wrong.

I'll then move the thread to the appropriate topic.|||I am using SQL Server 2005|||This works in 2000 and 2005 and might be of some use to you - let me know how you get on.

DECLARE @.host varchar(255)
SET @.host = host_name()

CREATE TABLE #Results (
Results varchar(255)
)

DECLARE @.cmd varchar(260)
SET @.cmd = 'ping ' + @.host

INSERT INTO #Results
EXEC master..xp_cmdshell @.cmd

SELECT Replace(Left(Results, CharIndex(']', Results)), 'Pinging ', '') As [client]
, host_name() As [host_name()]
FROM #Results
WHERE Results LIKE 'Pinging%'

DROP TABLE #Results|||Now my problem is - if the client machine do not have host name assigned in that case how can we ping and get the IP ?|||You can't...
Back to your method it is then...

Try this

--DROP trigger and/or table if they exist
IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'TR' AND name = 'myTable_InsertUpdate') BEGIN
DROP TRIGGER myTable_InsertUpdate
END
IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' AND name = 'myTable') BEGIN
DROP TABLE myTable
END

--Create out table; note the audit fields
CREATE TABLE myTable (
id int PRIMARY KEY NOT NULL IDENTITY(1,1)
, field1 char(1)
, changed_by_ip char(15)
, changed_by_host char(15)
, datetime_changed datetime
)
GO

--Create trgger for update and insert
CREATE TRIGGER myTable_InsertUpdate
ON myTable
FOR insert, update
AS
DECLARE @.ipLine varchar(255)
DECLARE @.pos int
DECLARE @.ip char(15)

--temporary table creation
CREATE TABLE #ip (
ipLine varchar(255)
)

--Insert the return of ipconfig into the temp table
INSERT #ip EXEC master..xp_cmdshell 'ipconfig'

--find the line which contains the IP and assign it to a variable
SET @.ipLine = (
SELECT ipLine
FROM #ip
WHERE ipLine LIKE '%IP Address%'
)

--If the IP is known
IF Coalesce(@.ipLine, '***') <> '***' BEGIN
--Find the index of the colon from the END of the string
SET @.pos = CharIndex(':', Reverse(@.ipLine), 1) - 1
--Trim the IP off the end of the string
SET @.ip = Right(@.ipLine, @.pos)
--Remove any trailing or leading white space
SET @.ip = RTrim(LTrim(@.ip))
END

--Drop the temp table
DROP TABLE #ip

--Update the audit fields based on the value being updated
UPDATE myTable
SET changed_by_ip = @.ip
, datetime_changed = GetDate()
, changed_by_host = host_name()
WHERE id IN (SELECT id FROM inserted)
GO

--Insert some test values
INSERT INTO myTable (field1) VALUES ('a')
INSERT INTO myTable (field1) VALUES ('a')
--Display initial values
SELECT * FROM myTable

--Update one of the fields
UPDATE myTable
SET field1 = 'b'
WHERE id = 2
--Display changed values.
SELECT * FROM myTable

--Notice the change in datetime_changed where id = 2
GO

--And finally; clean up after ourselves
DROP TRIGGER myTable_InsertUpdate
DROP TABLE myTable

This works on my install of 2000 and 2005.|||Let me see if I understand what the original poster (neetu bhagtani) was looking for, because this line of reasoning doesn't sound correct to me.

You have at least a SQL 2005 server, and a web server in a data center. You have clients that connect to the web server using HTTP, but those clients do not log in to the SQL Server directly.

If I've described the configuration that you've currently got, then your SQL Server can only get the client machine's IP address from the web server, because the SQL Server only "sees" the web server via TCP/IP, it never deals directly with the client so the SQL Server won't know the IP address of the client.

-PatP|||See as I told you before I get an error at this line -

INSERT #ip EXEC master..xp_cmdshell 'ipconfig' (as per the code given by you)

Insert #temp exec master..xp_cmdshell 'ipconfig' (and as per the code written by me)

which gives error saying that -' insert and execute statments cannot be nested'.

Also, I would like to tell that I was working on testing environment means on local server but not on live server since it this works on testing server and only we can upload and test on live server. Live Server is SQL Server 2003

Now when I uploaded your pinging version of Stored Procedure I get an error telling that master DB owner is someone else and when I give '[dbo].master' for executing the xp_cmdshell it gives another error saying that server is not the sysservers list use 'sp_addlinkedserver' Stored Procedure to add the server in the sysservers list

Pls help|||Yes, as described below is very much true

If I've described the configuration that you've currently got, then your SQL Server can only get the client machine's IP address from the web server, because the SQL Server only "sees" the web server via TCP/IP, it never deals directly with the client so the SQL Server won't know the IP address of the client.|||So all users will appear to have the same IP... (which kinda ruins what you're trying to achieve, no?)|||Some users will access the application on web server from UK, some from US, and some from India. So all will connect to same web server on which the application resides but will have different IP addresses of their machines.|||You do realize that the IIS logs keep all of the information you are after. Right?|||You should be handling this at the application level and/or analyzing logs as MCrowley suggests. It is not physically possible to do at the database level per Pat's assertion.

Also, if you enabled the ability to fire xp_cmdshell under the privileges that your web app uses, I suggest you disable it right now.|||But how to exactly do that ? how to get it from IIS log ?|||Let's go back to the original requirement for a second. You need to get the webserver client's IP address, so you can put that into an audit trail for any updates. Is this about what you need?|||See I am inserting the data in my Audit table in the trigger while insert/update/delete and I have the log file created by IIS which has all IP Addresses. My problem is how to get the IP from log file and insert in the table since insert in the table is done in the trigger while insert/update/delete|||This sounds like it should be done by passing the variable from the client-side.
For example, if you're users are accessing the databse through a web front end then pick up the value from the client's workstation and pass it on submit of a query as one of the values.

Make sense?|||Why would this need to be done by a trigger? Why can't the webserver pass this information to you? Are there users accessing this data by methods other than the webserver?|||Hi there,

Does it have to be IP address? will hostname do? with a lookup table for IP address or something.

If you want the hostname then do this:

select hostname from sysprocesses
where spid = @.@.spid|||True, but in an IIS implementation both the web server's address and hostname ought to be constants. The original poster wants the IP address of the client, which is not available to the SQL Server.

-PatP

Monday, March 19, 2012

How to get statistics on DML statements per table

Can I get statistics on which type of DML statements (e.g. insert, delete, update) that are executed by users on a table without creating triggers? I want to be able to show the number of executed statements per statement type. I have tried the 2005 Profiler but it outputs the entire batch statement which makes it a bit more difficult to create statistics.

Rgds

Bob

There is no easy way to obtain this information. You could also take a look at 3rd party tools that can get this sort of information from the transaction logs.

Monday, March 12, 2012

How to get return value for the number of rows affected by update command

Hi,

i read from help files that "For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. " Anyone know how to get the return value from the query below?

Below is the normal way i did in vb.net, but how to check for the return value. Please help.

========
Public Sub CreateMySqlCommand(myExecuteQuery As String, myConnection As SqlConnection)
Dim myCommand As New SqlCommand(myExecuteQuery, myConnection)
myCommand.Connection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
End Sub 'CreateMySqlCommand
========

Thank you.you can add either of these statements to the SQL being called
[BOL} @.@.rowcount
[BOL] Rowcount_big

the difference is in the datatypes rowcount _big returns a bigint
and @.@.rowcount returns int

if you have over 2 billion rows user rowcount_big|||Hi Ruprect, thanks for your reply. My sql statement is a very simple insert query without using any parameters just like the one below:

sql = "INSERT INTO [Subscriber] ([SubID], [SubName], [SubEmail], [Status], [MailID], [SubscribeDate]) VALUES (SubID, SubName, SubEmail, 'Pending', MailID ,getDate())"

I'm unsure of how to include the " [BOL} @.@.rowcount ". Do you mean that i should add a parameter to return @.@.rowcount or there is other way to do it? I'm new to this, would you please give me an example.

Thanks for your time.|||@.@.Rowcount stored the number of records affected by the immediately prior statement. The value is lost as soon as another statement is executed, so you must either use it immediately or store it in a procedure variable:

declare @.RecordsAffected Int
.
.
.
.
.
Update/Select/Delete some records from somewhere...
set @.RecordsAffected = @.@.RowCount

Look up @.@.Rowcount in Books Online for more details.|||thanks BLIND MAN
i didnt getthis until late
[BOL] stands for Books Online it's the sql server help file
i was giving you the article title

and since blindman got it exactly i've no need to reiterate
good luck.|||see if there is something like mycommand.rowsaffected property.|||Thanks Blindman and Thanks Ruprect. I'll study BOL ;) for details of @.@.rowcount.|||You should also follow ms_sql_dba's suggestion to see if there is a method to return the value via VB.

It might be more appropriate if you are going to use the value in your VB code.|||Hi ms_sql_dba, there isn't any rowsaffected property, however there is this UpdatedRowSource and others ..

Thanks for your suggestion, although i'm unsure of their usage, i'll look into it and see if i can find something which stores the value of number of rows affected!|||Sure Blindman, i'll study both ways and see which one is more applicable for my situation. You have a great day.|||Hi Everyone,

I managed to find another solution to my question. Just simply assign the value like this line:-

rowsAffected = myCommand.ExecuteNonQuery()|||see, it was simple!|||Yea. Lesson learned! Cheers!!!

Friday, March 9, 2012

How to get rank?

I would like to write a query that gives me the values of a set of
observations, and their rank.

CREATE TABLE #Values(val int)
INSERT #Values SELECT 1
INSERT #Values SELECT 5
INSERT #Values SELECT 10

I would like to select this:

1 10 -- rank 1, value 10
2 5
3 1

I can put them into a temp table with an identity column, ordered by
the column I'm interested in, and then retrieve in order by the
identity column. I'm wondering if there's a way to do that with a
subquery.

Thanks,
JimRunning count is one way

CREATE TABLE #Values(val int)
INSERT #Values SELECT 1
INSERT #Values SELECT 5
INSERT #Values SELECT 10

select (select count(*) from #Values v where val <= v2.Val) as Rank,*
from #Values v2
order by 2

Denis the SQL Menace
http://sqlservercode.blogspot.com/

jim_geiss...@.countrywide.com wrote:
> I would like to write a query that gives me the values of a set of
> observations, and their rank.
> CREATE TABLE #Values(val int)
> INSERT #Values SELECT 1
> INSERT #Values SELECT 5
> INSERT #Values SELECT 10
> I would like to select this:
> 1 10 -- rank 1, value 10
> 2 5
> 3 1
> I can put them into a temp table with an identity column, ordered by
> the column I'm interested in, and then retrieve in order by the
> identity column. I'm wondering if there's a way to do that with a
> subquery.
> Thanks,
> Jim|||Jim,

if you are using SS 2005 , use row_number() or rank() OLAP function|||Where do you want to show data?
If you use front end application, do Ranking there

Madhivanan


jim_geissman@.countrywide.com wrote:

Quote:

Originally Posted by

> I would like to write a query that gives me the values of a set of
> observations, and their rank.
> CREATE TABLE #Values(val int)
> INSERT #Values SELECT 1
> INSERT #Values SELECT 5
> INSERT #Values SELECT 10
> I would like to select this:
> 1 10 -- rank 1, value 10
> 2 5
> 3 1
> I can put them into a temp table with an identity column, ordered by
> the column I'm interested in, and then retrieve in order by the
> identity column. I'm wondering if there's a way to do that with a
> subquery.
> Thanks,
> Jim

Wednesday, March 7, 2012

how to get more then one isentity

i have few tables and in one of them i need to insert

the PK of sometable1 as FK to sometable3 and

the PK of sometable2 as Fk to sometable3

i have this for while:

select ident_current("dbo.Images") as img

select ident_current("dbo.Articals")as art

insert into dbo.ArticalsImages(ImageID,ArticalCode)

values (img,art)

but it give me error :

The name "img" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.

why is it?

if there is other better way its greater|||

May be you can try this.

insert into dbo.ArticalsImages(ImageID,ArticalCode)

select ident_current("dbo.Images"), ident_current("dbo.Articals")

Or you can declare those variables (img and art) and assign value to the variables

select img=ident_current("dbo.Images")

and then insert the values.

|||

Roy:

Try this instead:


declare @.img integer
declare @.art integer

select ident_current('dbo.Images') as @.img
select ident_current('dbo.Articals')as @.art


insert into dbo.ArticalsImages(ImageID,ArticalCode)
values (@.img,@.art)

This may fix the syntax errors; however, I have a good deal of doubt about using the IDENT_CURRENT function. I would suggest looking up @.@.IDENTITY in books online. What I would normally suggest is that you track what is going on and use SCOPE _IDENTITY instead of IDENT_CURRENT. With IDENT_CURRENT it is possible for an insert by a completely different process to become the keys that you would be inserting into your target table. Can you describe a little more what you are doing before you go to insert the row into "ArticalsImages"?

how to get more then one isentity

i have few tables and in one of them i need to insert

the PK of sometable1 as FK to sometable3 and

the PK of sometable2 as Fk to sometable3

i have this for while:

select ident_current("dbo.Images") as img

select ident_current("dbo.Articals")as art

insert into dbo.ArticalsImages(ImageID,ArticalCode)

values (img,art)

but it give me error :

The name "img" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.

why is it?

if there is other better way its greater|||

May be you can try this.

insert into dbo.ArticalsImages(ImageID,ArticalCode)

select ident_current("dbo.Images"), ident_current("dbo.Articals")

Or you can declare those variables (img and art) and assign value to the variables

select img=ident_current("dbo.Images")

and then insert the values.

|||

Roy:

Try this instead:


declare @.img integer
declare @.art integer

select ident_current('dbo.Images') as @.img
select ident_current('dbo.Articals')as @.art


insert into dbo.ArticalsImages(ImageID,ArticalCode)
values (@.img,@.art)

This may fix the syntax errors; however, I have a good deal of doubt about using the IDENT_CURRENT function. I would suggest looking up @.@.IDENTITY in books online. What I would normally suggest is that you track what is going on and use SCOPE _IDENTITY instead of IDENT_CURRENT. With IDENT_CURRENT it is possible for an insert by a completely different process to become the keys that you would be inserting into your target table. Can you describe a little more what you are doing before you go to insert the row into "ArticalsImages"?

Friday, February 24, 2012

How to get identity from parent Table and insert it into the child table

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 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

Is this a one time process?
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

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 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

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:
> 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 I
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?
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 wht
I
> 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 ID into field upon insert (SCOPE_IDENTITY() ?)

I have two fields:

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.


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

|||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 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?

Hi,
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