Showing posts with label inserted. Show all posts
Showing posts with label inserted. Show all posts

Friday, March 30, 2012

Inserting 1 row and getting a message that two rows were inserted.

Why does this code tell me that I inserted 2 rows when I really only inserted one? I am using SQL server 2005 Express. I can open up the table and there is only one record in it.

Dim InsertSQL As String = "INSERT INTO dbCG_Disposition ( BouleID, UserName, CG_PFLocation ) VALUES ( @.BouleID, @.UserName, @.CG_PFLocation )"
Dim StatusAs Label = lblStatusDim ConnectionStringAs String = WebConfigurationManager.ConnectionStrings("HTALNBulk").ConnectionStringDim conAs New SqlConnection(ConnectionString)Dim cmdAs New SqlCommand(InsertSQL, con) cmd.Parameters.AddWithValue("BouleID", BouleID) cmd.Parameters.AddWithValue("UserName", UserID) cmd.Parameters.AddWithValue("CG_PFLocation", CG_PFLocation)Dim addedAs Integer = 0Try con.Open() added = cmd.ExecuteNonQuery() Status.Text &= added.ToString() &" records inserted into CG Process Flow Inventory, Located in Boule_Storage."Catch exAs Exception Status.Text &="Error adding to inventory. " Status.Text &= ex.Message.ToString()Finally con.Close()End Try

Anyone have any ideas? Thanks

Change

Status.Text &=

To

Status.Text =

When you put &=, every time when you fire event, the text will be appended

(After I posted it, I realized probably it was able to solve your issue. Sorry for that).

|||

Yeah, somehow, added is getting set to 2 at the

added = cmd.ExecuteNonQuery()
step. I have a trigger set on this table to increase other rows with the same BouleID by one but that shouldn't
affect the ADO object should it?
 
There is this in the MSDN:

Although theExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data.

ForUPDATE, INSERT, and DELETE statements, the return value is the numberof rows affected by the command. When a trigger exists on a table beinginserted or updated, the return value includes the number of rowsaffected by both the insert or update operation and the number of rowsaffected by the trigger or triggers. For all other types of statements,the return value is -1. If a rollback occurs, the return value is also-1.

The problem is that these are new inserts into the table so the trigger is not affecting any other rows because they don't exist yet.
|||

Quite possibly. Do you have a SET NOCOUNT ON in your triggers?

|||

No, I dont'. I only have

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

set.

|||

In your trigger, right after the "AS", add "SET NOCOUNT ON". Then any queries the trigger does won't be seen. For example:

CREATE TRIGGER ...

AS

SET NOCOUNT ON

...

inserted/deleted tables

Does the data in the rows in the inserted and deleted tables always correspond? For instance, row 1 in inserted corresponds with row 1 in deleted.
Thanks,

OK, if you

-Insert n rows you have n rows in the inserted.
-Delete n rows you have n rows in the deleted table.
-Update n rows you have n rows in the inserted and n rows in the deleted table.

So for an update the rowcount is always corresponding.

HTH, Jens Suessmeyer

|||

Well, what I was really wanting to know is if I could assume that the data in row [1] (the new data to be inserted) of the inserted table corresponds with the data in row [1] (the data that was deleted) in the deleted table.

Example:

Update people

Set person_id = (select person_id from inserted)

Where people.person_id = (select person_id from deleted)

This type of update statement will only work if there is a single row being updated. I wanted to step through the inserted and deleted tables one row at a time for multiple row updates, but I did not know if it was safe to say that the data in inserted row # corresponded with the data in deleted row #.

|||

> Update people

>

> Set person_id = (select person_id from inserted)

>

> Where people.person_id = (select person_id from deleted)

What table is this trigger attached to? People, or another table? Are you

just trying to undo the update to people, or replicate the update to another

table? In what scenario?

> This type of update statement will only work if there is a single row

> being updated.

Absolutely correct, and a very common tripping point for hundreds of people

before you.

> I wanted to step through the inserted and deleted tables

> one row at a time for multiple row updates

No, no, no. You are going about this all wrong. Think about it in SETS.

If you give some proper DDL and specs (see http://www.aspfaq.com/5006) we

can help you do this in one statement and abandon this idea of iterating

through every row and trying to match some hypothetical "row number"...

|||

> Does the data in the rows in the inserted and deleted tables always

> correspond? For instance, row 1 in inserted corresponds with row 1 in

> deleted.

There is no "row 1"... a table, by definition, is an unordered set of rows.

Typically you identify a row by some unique value, like a primary key, not

whether it came first or last or somewhere in between.

|||

Hello to everyone.

here i want to know some more details regarding inserted/deleted tables.

consider the scenario that more than 100 users are inserting/updating rows of same or othere tables of a database and tiggers of after update upon each insert and/or update is been fired.

what will be the response of the SQL 2005 server to these operations as i am moving the updated data to the audit tables from the delted table. by using the following trigger.

CREATE TRIGGER [TrigAUTblA]
ON [TblA]
AFTER UPDATE AS
BEGIN
INSERT INTO [TblAHistory]
(
[guidA],
[Description]
)
SELECT deleted.guidA,
deleted.Description
FROM deleted

Also what issues can emerge using this scenario

|||

It is possible to update the unique key for multiple rows in a table. In that case, there is nothing to correlate the rows in "inserted" to the rows in "deleted" other than the order in which they are returned by a select statement.

So the question is a valid one, I think: If a table contains one unique key, and multiple rows in that table are updated such that the value of that key changes, can we count on the rows in the "inserted" and "deleted" tables being returned in the same order so that they can be matched up one to one?

Thanks,

Ron

inserted/deleted tables

Does the data in the rows in the inserted and deleted tables always correspond? For instance, row 1 in inserted corresponds with row 1 in deleted.
Thanks,

OK, if you

-Insert n rows you have n rows in the inserted.
-Delete n rows you have n rows in the deleted table.
-Update n rows you have n rows in the inserted and n rows in the deleted table.

So for an update the rowcount is always corresponding.

HTH, Jens Suessmeyer

|||

Well, what I was really wanting to know is if I could assume that the data in row [1] (the new data to be inserted) of the inserted table corresponds with the data in row [1] (the data that was deleted) in the deleted table.

Example:

Update people

Set person_id = (select person_id from inserted)

Where people.person_id = (select person_id from deleted)

This type of update statement will only work if there is a single row being updated. I wanted to step through the inserted and deleted tables one row at a time for multiple row updates, but I did not know if it was safe to say that the data in inserted row # corresponded with the data in deleted row #.

|||

> Update people

>

> Set person_id = (select person_id from inserted)

>

> Where people.person_id = (select person_id from deleted)

What table is this trigger attached to? People, or another table? Are you

just trying to undo the update to people, or replicate the update to another

table? In what scenario?

> This type of update statement will only work if there is a single row

> being updated.

Absolutely correct, and a very common tripping point for hundreds of people

before you.

> I wanted to step through the inserted and deleted tables

> one row at a time for multiple row updates

No, no, no. You are going about this all wrong. Think about it in SETS.

If you give some proper DDL and specs (see http://www.aspfaq.com/5006) we

can help you do this in one statement and abandon this idea of iterating

through every row and trying to match some hypothetical "row number"...

|||

> Does the data in the rows in the inserted and deleted tables always

> correspond? For instance, row 1 in inserted corresponds with row 1 in

> deleted.

There is no "row 1"... a table, by definition, is an unordered set of rows.

Typically you identify a row by some unique value, like a primary key, not

whether it came first or last or somewhere in between.

|||

Hello to everyone.

here i want to know some more details regarding inserted/deleted tables.

consider the scenario that more than 100 users are inserting/updating rows of same or othere tables of a database and tiggers of after update upon each insert and/or update is been fired.

what will be the response of the SQL 2005 server to these operations as i am moving the updated data to the audit tables from the delted table. by using the following trigger.

CREATE TRIGGER [TrigAUTblA]
ON [TblA]
AFTER UPDATE AS
BEGIN
INSERT INTO [TblAHistory]
(
[guidA],
[Description]
)
SELECT deleted.guidA,
deleted.Description
FROM deleted

Also what issues can emerge using this scenario

|||

It is possible to update the unique key for multiple rows in a table. In that case, there is nothing to correlate the rows in "inserted" to the rows in "deleted" other than the order in which they are returned by a select statement.

So the question is a valid one, I think: If a table contains one unique key, and multiple rows in that table are updated such that the value of that key changes, can we count on the rows in the "inserted" and "deleted" tables being returned in the same order so that they can be matched up one to one?

Thanks,

Ron

Inserted/deleted table.

Hi,

I am currently working on a MS SQL server 2000.

I would like to access the data inserted or deleted within a trigger. however the built-in tables -- inserted and deleted -- are not accessible. anyone knows why? And is there any other way to do this?

Thankspost your t-sql code that you used to access the inserted/deleted tablessql

inserted value on text field gets truncated after 255 chars

Hello,
I have a SP on SQL Server 2005 (Express Ed.) which performs an INSERT
statement over a table. In the table I have two 'text' fields with the
same properties, with just one difference: one field allows nulls, the
other one does not.
Well, one field actually accepts only the first 255 chars (the nullable
field), while the other field has no problems.
The "Length" property is set to 16 for both fields, as I said all the
properties but one (null/not null) are exactly the same, and also the
context is the same (same database, same table).
Many thanks for your help!
GiovanniHow does your SP look?
It sounds like you truncate it somewhere there. Maybe the parameter is
a varchar or something like that?|||How are you validating that only 255 characters are there? Are you using
SELECT DATALENGTH(col_name) FROM table? Or are you counting the number of
characters in the result set?
"gm1974" <gmascia@.gmail.com> wrote in message
news:1138737544.776002.219580@.f14g2000cwb.googlegroups.com...
> Hello,
> I have a SP on SQL Server 2005 (Express Ed.) which performs an INSERT
> statement over a table. In the table I have two 'text' fields with the
> same properties, with just one difference: one field allows nulls, the
> other one does not.
> Well, one field actually accepts only the first 255 chars (the nullable
> field), while the other field has no problems.
> The "Length" property is set to 16 for both fields, as I said all the
> properties but one (null/not null) are exactly the same, and also the
> context is the same (same database, same table).
> Many thanks for your help!
> Giovanni
>|||gm1974 wrote:
> Hello,
> I have a SP on SQL Server 2005 (Express Ed.) which performs an INSERT
> statement over a table. In the table I have two 'text' fields with the
> same properties, with just one difference: one field allows nulls, the
> other one does not.
> Well, one field actually accepts only the first 255 chars (the
> nullable field), while the other field has no problems.
> The "Length" property is set to 16 for both fields, as I said all the
> properties but one (null/not null) are exactly the same, and also the
> context is the same (same database, same table).
>
Are you testing it in QA? If so, you should modify the "maximum characters
per column" setting in the QA options dialog.
--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.|||Oh, I must be really tired. I definitely forgot to change parameter
type in the SP, it was still set at VarChar(255), so the value was
truncated!
Better to get some sleep, many thanks for your help.|||Thanks for your help, it may be useful in the future.
Giovanni

inserted the image in a column-how can i view the image

hi,
i have inserted the image present in mydocuments using alter command
create table aa(a int, d image)
insert into aa values (1,'F:\prudhvi\baba 002.jpg')
when i do
select * from aa
i am getting the result in the column d as
0x463A5C707275646876695C70727564687669203030322E6A 7067
how i can i view the image?
pls clarify my doubt
satish
Hi,
Sql is used for storing data... and image data is stored as varibale length
binary data...
image datatype...
Variable-length binary data from 0 through 231-1 (2,147,483,647) bytes.
Thats why you got that value...
For seeing it... just follow the below link... it uses ASP.NET and the "LOAD
FILE FROM DATABASE" property of text.
http://support.microsoft.com/default...b;en-us;326502
Thanks,
Sree
[Please specify the version of Sql Server as we can save one thread and time
asking back if its 2000 or 2005]
"satish" wrote:

> hi,
> i have inserted the image present in mydocuments using alter command
> create table aa(a int, d image)
> insert into aa values (1,'F:\prudhvi\baba 002.jpg')
> when i do
> select * from aa
> i am getting the result in the column d as
> 0x463A5C707275646876695C70727564687669203030322E6A 7067
>
> how i can i view the image?
> pls clarify my doubt
> satish
>

inserted the image in a column-how can i view the image

hi,
i have inserted the image present in mydocuments using alter command
create table aa(a int, d image)
insert into aa values (1,'F:\prudhvi\baba 002.jpg')
when i do
select * from aa
i am getting the result in the column d as
0x463A5C707275646876695C70727564687669203030322E6A7067
how i can i view the image?
pls clarify my doubt
satishHi,
Sql is used for storing data... and image data is stored as varibale length
binary data...
image datatype...
Variable-length binary data from 0 through 231-1 (2,147,483,647) bytes.
Thats why you got that value...
For seeing it... just follow the below link... it uses ASP.NET and the "LOAD
FILE FROM DATABASE" property of text.
http://support.microsoft.com/default.aspx?scid=kb;en-us;326502
Thanks,
Sree
[Please specify the version of Sql Server as we can save one thread and time
asking back if its 2000 or 2005]
"satish" wrote:
> hi,
> i have inserted the image present in mydocuments using alter command
> create table aa(a int, d image)
> insert into aa values (1,'F:\prudhvi\baba 002.jpg')
> when i do
> select * from aa
> i am getting the result in the column d as
> 0x463A5C707275646876695C70727564687669203030322E6A7067
>
> how i can i view the image?
> pls clarify my doubt
> satish
>

inserted the image in a column-how can i view the image

hi,
i have inserted the image present in mydocuments using alter command

create table aa(a int, d image)
insert into aa values (1,'F:\prudhvi\baba 002.jpg')

when i do
select * from aa
i am getting the result in the column d as
0x463A5C707275646876695C70727564687669203030322E6A 7067

how i can i view the image?

pls clarify my doubt

satishUse WRITETEXT/READTEXT instead of INSERT/SELECT to store / retrieve
There is quite a detailed explanation in Books Online

--
Jack Vamvas
___________________________________
Receive free SQL tips - www.ciquery.com/sqlserver.htm

"satish" <satishkumar.gourabathina@.gmail.com> wrote in message
news:1141732028.000941.183610@.e56g2000cwe.googlegr oups.com...
> hi,
> i have inserted the image present in mydocuments using alter command
> create table aa(a int, d image)
> insert into aa values (1,'F:\prudhvi\baba 002.jpg')
>
> when i do
> select * from aa
> i am getting the result in the column d as
> 0x463A5C707275646876695C70727564687669203030322E6A 7067
>
> how i can i view the image?
>
> pls clarify my doubt
>
> satish|||satish (satishkumar.gourabathina@.gmail.com) writes:
> i have inserted the image present in mydocuments using alter command
> create table aa(a int, d image)
> insert into aa values (1,'F:\prudhvi\baba 002.jpg')
> when i do
> select * from aa
> i am getting the result in the column d as
> 0x463A5C707275646876695C70727564687669203030322E6A 7067
>
> how i can i view the image?

You have not inserted the the image into the table. You have inserted the
disk location of the image into the table. Run

SELECT convert(varchar(80), d) FROM aa

to see.

There is no way to insert data into a column directly from a file. The
normal way of loading image is write a program that reads the file,
and the passes the binary stream through a parameterised INSERT statement
in a client API. You can also convert the contents to a hexstring and
build an INSERT statement from that.

Conversly, to display the image you also need an application. If you
have stored an image in a table, a SELECT on that table in Query Analyzer
or Mgmt Studio will only display a long hex string.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

inserted the image in a column-how can i view the image

hi,
i have inserted the image present in mydocuments using alter command
create table aa(a int, d image)
insert into aa values (1,'F:\prudhvi\baba 002.jpg')
when i do
select * from aa
i am getting the result in the column d as
0x463A5C707275646876695C7072756468766920
3030322E6A7067
how i can i view the image?
pls clarify my doubt
satishHi,
Sql is used for storing data... and image data is stored as varibale length
binary data...
image datatype...
Variable-length binary data from 0 through 231-1 (2,147,483,647) bytes.
Thats why you got that value...
For seeing it... just follow the below link... it uses ASP.NET and the "LOAD
FILE FROM DATABASE" property of text.
http://support.microsoft.com/defaul...kb;en-us;326502
Thanks,
Sree
[Please specify the version of Sql Server as we can save one thread and
time
asking back if its 2000 or 2005]
"satish" wrote:

> hi,
> i have inserted the image present in mydocuments using alter command
> create table aa(a int, d image)
> insert into aa values (1,'F:\prudhvi\baba 002.jpg')
> when i do
> select * from aa
> i am getting the result in the column d as
> 0x463A5C707275646876695C7072756468766920
3030322E6A7067
>
> how i can i view the image?
> pls clarify my doubt
> satish
>sql

inserted text take the wrong alignment

i try to insert the following string in the database

the red car (driver)

this string save like this

)the red car (driver

i have a problem when inserting string contains special character at the end of the string.

we have arabic and english string like this

???? ????? (R) radial ????

and it appear in reverse like this

???? (R) radial ???? ?????

You need to check the application that is inserting the data specifically the API commands being used. This is not a SQL Server problem per se. The database engine will store the values as passed from the client and doesn't manipulate it on the server. Also, where are you checking the display of the values? It is possible that the tool is doing something based on your language / regional settings. So this could just be a display issue also. Start with verifying the data in the back end tables directly, then your client code and then whatever UI you are using.|||

hello Umachandar,

me and Batool posted this one together

I do import the data into the database through a certain script, but I thought it was an sql problem, because the data were in the correct alignment before inserting, I see them reversed in the tables directly, actually to test this issue I tried to enter data directly into the database so in the cell I press ctrl + Alt + shift to reverse the alignment inside the cell in table, and when I start submitting my data it is reversed.

how could this be a display problem when it's correct in all other applications on my machine

thank you

|||

I believe I've seen funny behavior in Management Studio when you try to display mixed right-left and left-right scripts. (I doubt this is unique to MS.) Can you inspect the binary contents of the strings and see whether it contains what you expect?

Cheers,

|||

You should verify the data first without involving any UI elements into the picture. The reason I say that it could be a display issue is that the tool might be doing something different when reading and displaying the data. This happens for float data type values today. The accuracy of the digits are different from ISQLW and in some cases two values that differ in say the 17th decimal digit will look the same. But this doesn't mean that the values are the same.

So you could write a script or program that does the insert, reads the data back and verifies it using SQL only. This will eliminate the UI from the picture. Additionally, tracing the calls to the server from the UI / tool via Profiler will also help. You can find out if the provider/driver is translating the string based on code page settings. There are just too many variables involved in this. Is it possible to do the following?

1. Post a simple DDL, insert statements and SELECT which shows the behavior (note that you may have to use the appropriate collation and Unicode data type to avoid any character translation)

2. If #1 doesn't work for you, is it possible to post some steps using say a particular UI (like ISQLW or SSMS). Please be clear on how you are inputting the data (open table, script/open table combination) and so on. Schema and data type of the column(s) are important here also. You talk about entering something in a cell - where is this? What UI are you talking about?

Lastly, the configuration of the OS (language/regional settings) may also be a factor and version of SQL Server. So please post those also.

Inserted Table when Inserting

Hi,

Now thanks to you good folks on here, I have recently found out that when inserting data into table, there is a system table which can be queried with triggers - specifically called "Inserted".

What I am wondering is what are the limitations of what I can do with the data in this table?
I know I can query it from within the trigger, but can I update data specifically in this table before it is inserted?
(ie IF field1 FROM inserted = 'blah' UPDATE inserted SET field2 = 'something')

If so is there anything that I need to look out for? Concerns? Etc?

Thanks in advance for your help

Cheersyou can use the data for comparisons or you can join the query argument in the trigger to the inserted and or the deleted tables

I have never updated them directly so i cant speak to that but i can suggest that anything that you might want to change in these virtual tables (Inserted\Deleted) could just as easily be changed in the triggered or evaluated table directly from the trigger code.

remember these tables contain data to give you a before and after look at the transaction that the trigger is a part of
(a trigger is implicitly part of the X-act that calls it)
so they dont technically exist when you are not in a X-act|||It is a very bad idea to try to modify either INSERTED or DELETED directly, they are implemented in "curious" ways. While you might be able to update them, it is still a very bad idea to do it.

-PatP|||Ahh haaa so if I understand correctly - what you are basically saying is that the information contained in this table, is ALREADY inserted into the table.
So if the file I was inserting had a PK field = 1234, and I wanted to update something in this file once it was inserted I could say something to the effect of:

update table1
set field1 = blah
from table1
where table1.field2 = inserted.field2

Rather than:

update inserted
set field1 = blah
from inserted

Hmm hopefully I have made a bit of sense here....

Thanks.|||Originally posted by Pat Phelan
It is a very bad idea to try to modify either INSERTED or DELETED directly, they are implemented in "curious" ways. While you might be able to update them, it is still a very bad idea to do it.

-PatP

The logical tables INSERTED and DELETED cannot be updated.|||E3xtc

yes that is the case
basically when you perform an insert on a table that has a trigger on it (for insert)
1 the row is inserted to the table
2 the row is also added into the "inserted" table
(which is only available to the xact that calls it)
3 the trigger actions are executed
4 commit or rollback

for deleted the same actions occur except the row to be deleted is added to the deleted table.

an update (in some cases) is a insert and a delete so there is no actual "updated" table
on an update the row as it existed before the update is added to the "deleted" table and the row with the updated column is added to the "inserted" table.

while the table exists(during trigger execution) you can query it just as you would any table.|||Originally posted by E3xtc
Ahh haaa so if I understand correctly - what you are basically saying is that the information contained in this table, is ALREADY inserted into the table. Yep, that you did understand that correctly!

The rows are modified first, placed in a pair of "non-corporeal" tables named INSERTED and DELETED. These tables can be freely modified in an INSTEAD OF trigger if the database compatibility level is set to 80. In the first releases of sp1 and sp3, and in several PSS hot fixes you could update the INSERTED and DELETED tables in any kind of trigger, with any database compatibility level. It is still a bad idea!

In general, it is considered "good form" to use a JOIN back to the primary (host) table to change the values of columns. This becomes much more important in the 64 bit version of SQL 2000, and will be even more so in Yukon.

-PatP|||brilliant!! Thanks all for your help - it is crystal clear now.

Much appreciated!

INSERTED table performance

I have a table with one UPDATE trigger. When I execute a one row update
command
to the table, Graphical Query Plan reports very slow select from INSERTED
table (900ms).
However, if I check the same command using Profiler, everything goes quickly
(duration 0 ms). Why is that? Which one should I trust, profiler or query
plan?I trust Profiler more than the Graphical Query Plan. I have seen some quite
strange costs and percentages in the Graphical Query Plan, specially when
objects are involved that don't exist at the beginning of the query, like
the inserted and deleted tables, temporary tables and table variables
--
Jacco Schalkwijk
SQL Server MVP
"Pexi" <pekkadotheimonen@.plenwaredotnospamdotcom> wrote in message
news:emPWAZ4rDHA.2444@.TK2MSFTNGP12.phx.gbl...
> I have a table with one UPDATE trigger. When I execute a one row update
> command
> to the table, Graphical Query Plan reports very slow select from INSERTED
> table (900ms).
> However, if I check the same command using Profiler, everything goes
quickly
> (duration 0 ms). Why is that? Which one should I trust, profiler or query
> plan?
>|||Pexi,
Something that surprise me when I first found out. Inserted and deleted do
not exist, but are virtual tables that are populated each time you query
them by scanning the transaction log to extract the before and after images.
This is why the suggestion is to fill temp tables #inserted and #deleted if
you need to make repeated use of these tables.
Regarding the difference in the timings, the best way to measure is to
create a test. Do a loop calling your UPDATE repeatedly and logging the
milliseconds in a table.
SET @.BeginTime = GetDate()
EXEC YourTestStatement
INSERT INTO TrackingTable Values(@.BeginTime, GetDate())
Afterward you can analyze the results (and publish an article).
Russell Fields
http://www.sqlpass.org/
2004 PASS Community Summit - Orlando
- The largest user-event dedicated to SQL Server!
"Pexi" <pekkadotheimonen@.plenwaredotnospamdotcom> wrote in message
news:emPWAZ4rDHA.2444@.TK2MSFTNGP12.phx.gbl...
> I have a table with one UPDATE trigger. When I execute a one row update
> command
> to the table, Graphical Query Plan reports very slow select from INSERTED
> table (900ms).
> However, if I check the same command using Profiler, everything goes
quickly
> (duration 0 ms). Why is that? Which one should I trust, profiler or query
> plan?
>|||Thanks for the replies! You kind of confirm my thinking:
never trust the query plan - it just tells fairy tales sometimes :)
pexi
"Pexi" <pekkadotheimonen@.plenwaredotnospamdotcom> wrote in message
news:emPWAZ4rDHA.2444@.TK2MSFTNGP12.phx.gbl...
> I have a table with one UPDATE trigger. When I execute a one row update
> command
> to the table, Graphical Query Plan reports very slow select from INSERTED
> table (900ms).
> However, if I check the same command using Profiler, everything goes
quickly
> (duration 0 ms). Why is that? Which one should I trust, profiler or query
> plan?
>

INSERTED table and triggers

Hi. I was dealing with triggers when a doubt came in mind.

While I can understand that the DELETED and UPDATED tables can contain more rows that have been affected by the DELETE or the UPDATE statment, the INSERTED table that I read in a "FOR INSERT" trigger has just 1 row or can have more rows?

Thanks.

many rows. Number of rows depended on how many rows get deleted / updated / inserted|||Image the query

INSERT INTO SomeTable
SELECT SomeCOlumn From ManyRowTable

That will bring up more than one row. bew also aware that the trigger is fired upon DML statement not per row, this means that a query like

INSERT INTO SomeTable
SELECT SomeColumn From SomeTable2 Where 1 = 0

also brings the trigger to fire.

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de

INSERTED table

I have a qn regarding the INSERTED table.

Whenever a row is inserted into the table i understand that the INSERTED table also gets that particular row. But how long does that particular row stay thr? Till another new row is inserted into the table? which means that rows get overwritten whenever a row is inserted?

Hope everyone understands what i am trying to say. Would be kind of you to reply.thanks!

GayathriPlease provide an example of the sql.|||SELECT JobNumber
from inserted
where ServiceType = 'On-site' and ServiceStatus = 'NEW' and DateModified=(SELECT MAX(DateModified) from inserted)

when i execute this statement alone i will only get one job number but when i put this into a trigger and channel the output into a cursor to copy it into a variable it selects some other job number as well...This is the whole code

DECLARE job_number_cursor CURSOR FOR
SELECT JobNumber
from inserted
where ServiceType = 'On-site' and ServiceStatus = 'NEW' and DateModified=(SELECT MAX(DateModified) from inserted)
OPEN job_number_cursor
FETCH NEXT FROM job_number_cursor INTO
@.job_number

CLOSE job_number_cursor
DEALLOCATE job_number_cursor

I was hoping to get just one output since i thought the INSERTED table only contains the last inserted row.|||I understand what you are asking...

Basically you are saying,...

When a table has a trigger on it the trigger has access to a table called inserted (assuming it is an insert trigger). How long does the inserted table with the insert record exist...

In all honesty, I'm not sure, but I would say it would exist until the insert and the associated trigger (if there is one) has been completed...

I'll look up some resources and see what I can find.|||Um,... question,... when you use your cursor are you doing an update or insert into the table with the trigger on it??|||I am inserting|||okie,... so lets think about that for a sec...

you are in the middle of an insert, your trigger fires which opens a cursor which does an insert (loop to start and insert a new record into the inserted table)

your cursor is still open when you do your second insert and it references the same inserted table... which now has the new record in it...

does that make sense??|||Check out your bol:

The inserted table stores copies of the affected rows during INSERT and UPDATE statements. During an insert or update transaction, new rows are added simultaneously to both the inserted table and the trigger table. The rows in the inserted table are copies of the new rows in the trigger table.|||and I assume they get cleaned out once the insert is complete... including trigger execution...|||rnealejr ,I understand that INSERTED table stores copies of the rows inserted into the actual table...

So does this mean that everytime an insert or update statement is executed a new inserted table is formed?|||I think the table remains but the rows are removed after the action is completed.

The reason I think this is because according to the BOL you can reference the deleted table when doing an insert and the inserted table when doing a delete but there are no rows contained in the tables...

"When you set trigger conditions, use the inserted and deleted tables appropriately for the action that fired the trigger. Although referencing the deleted table while testing an INSERT, or the inserted table while testing a DELETE does not cause any errors, these trigger test tables do not contain any rows in these cases."|||You can have more than 1 record in the inserted table and the table is only accessible to the trigger - so the table exists as long as the trigger runs for a particular sql statement.|||So does this mean that everytime an insert or update statement is executed a new inserted table is formed?

These tables are created/stored in memory. From what I remember, I believe the scope of these virtual tables are for the life of the trigger. It would not make sense that ss would keep a table in memory any longer than needed.|||It's highly possible that they continue to exist after their usefulness has gone, after all we are talking a microsoft product and they have done stranger things in the past.

Also the amount of memory you are talking about is minimal so the effect of keeping the table alive in memory is unlikely to cause any real problems.

In fact, it is likely that the over head involved in creating the tables each time if more detrimental then kepeing them in memory especially when you consider that you are likely to do multiple updates/inserts/deletes on any given table at a time rather then constant swap around tables ...|||The inserted and deleted tables exist only within the scope of the trigger execution. Updates use both the inserted and deleted tables because they effectively insert new modified copies of the records and then delete the old ones.

gayamantra, the inserted table does not exist as a distinct and persistent object. Keep in mind that it has the same record format as whatever datatable was the subject of the operation.

New virtual tables of inserted and deleted records must be created (in memory only) for each operation, otherwise multiple users accessing the datatable would end up with their inserted/deleted records intermingling.

I would guess that there is little additional overhead in creating these virtual tables on the fly, because they may be incidental to the database server's operations anyway.|||"New virtual tables of inserted and deleted records must be created (in memory only) for each operation, otherwise multiple users accessing the datatable would end up with their inserted/deleted records intermingling."

Not necessarily, the tables could be created with a user context eg. they are specific to the user at the time... I don't really know though... lets be honest, there are quite a few methods that MS could be using... but for the nature of this discussion the inserted and deleted table exist for the duration of the insert or delete. :Dsql

inserted table

Is it ever possible for the inserted table to have more than one row in a
for update trigger? One of our devs recently put a cursor in his for update
trigger to loop over rows in the inserted table. However, from what I
understand, inserted should never have more than one row in it. I just
wanted to verify this before I removed it as I am working on optimizing it.
Brent Black
Onvia.com
Technical Lead/Database AdministratorThe inserted table can indeed have > 1 row in it and you code should take
this into account. Likely, you don't need a cursor either.
Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Brent Black" <bblack@.onvia.com> wrote in message
news:uhVRS4K9DHA.3404@.TK2MSFTNGP09.phx.gbl...
Is it ever possible for the inserted table to have more than one row in a
for update trigger? One of our devs recently put a cursor in his for update
trigger to loop over rows in the inserted table. However, from what I
understand, inserted should never have more than one row in it. I just
wanted to verify this before I removed it as I am working on optimizing it.
Brent Black
Onvia.com
Technical Lead/Database Administrator|||Don't use a cursor in a trigger, typically people do something like this:
update table set column = value where prinmarykey = (select primary key from
inserted)
If you will have multiple updates or inserts you would want to change it to
this
update table set column = value where prinmarykey IN (select primary key
from inserted)
HTH
--
Ray Higdon MCSE, MCDBA, CCNA
--
"Brent Black" <bblack@.onvia.com> wrote in message
news:uhVRS4K9DHA.3404@.TK2MSFTNGP09.phx.gbl...
> Is it ever possible for the inserted table to have more than one row in a
> for update trigger? One of our devs recently put a cursor in his for
update
> trigger to loop over rows in the inserted table. However, from what I
> understand, inserted should never have more than one row in it. I just
> wanted to verify this before I removed it as I am working on optimizing
it.
> Brent Black
> Onvia.com
> Technical Lead/Database Administrator
>|||I've been able to do that in every case except where the ID value from the
cursor is being passed into a udf that returns a table.. For example:
insert into sometable (column1, column2)
select distinct @.CursorValue, pgr.ID
from someUDF(@.CursorValue) as pgr
I tried changing this to:
insert into sometable(column1, column2)
select distinct i.ID, pgr.ID
from someUDF(i.ID) as pgr,
inserted i
but that didn't work because it expects a single deterministic value to be
passed into the UDL.. It appears that was why the original dev chose to use
a cursor in the trigger to handle this in the first place. Any ideas on how
to do this without the cursor?
Thanks!
Brent Black
Onvia.com
Technical Lead/Database Administrator
"Ray Higdon" <sqlhigdon@.nospam.yahoo.com> wrote in message
news:OYCx3KL9DHA.2604@.TK2MSFTNGP10.phx.gbl...
> Don't use a cursor in a trigger, typically people do something like this:
> update table set column = value where prinmarykey = (select primary key
from
> inserted)
> If you will have multiple updates or inserts you would want to change it
to
> this
> update table set column = value where prinmarykey IN (select primary key
> from inserted)
> HTH
> --
> Ray Higdon MCSE, MCDBA, CCNA
> --
> "Brent Black" <bblack@.onvia.com> wrote in message
> news:uhVRS4K9DHA.3404@.TK2MSFTNGP09.phx.gbl...
a
> update
> it.
>|||What's the UDF look like?
Ray Higdon MCSE, MCDBA, CCNA
--
"Brent Black" <bblack@.onvia.com> wrote in message
news:ucGCsKN9DHA.1936@.TK2MSFTNGP12.phx.gbl...
> I've been able to do that in every case except where the ID value from the
> cursor is being passed into a udf that returns a table.. For example:
> insert into sometable (column1, column2)
> select distinct @.CursorValue, pgr.ID
> from someUDF(@.CursorValue) as pgr
> I tried changing this to:
> insert into sometable(column1, column2)
> select distinct i.ID, pgr.ID
> from someUDF(i.ID) as pgr,
> inserted i
> but that didn't work because it expects a single deterministic value to
be
> passed into the UDL.. It appears that was why the original dev chose to
use
> a cursor in the trigger to handle this in the first place. Any ideas on
how
> to do this without the cursor?
> Thanks!
> Brent Black
> Onvia.com
> Technical Lead/Database Administrator
> "Ray Higdon" <sqlhigdon@.nospam.yahoo.com> wrote in message
> news:OYCx3KL9DHA.2604@.TK2MSFTNGP10.phx.gbl...
this:
> from
> to
in
> a
just
optimizing
>|||Brent,
I wouldn't be surprised if in this case the UDF is something like
create function someUDF(
@.v somedatatype
) returns table ...
WHERE someColumn = @.v
...
If that's the case, then the trigger could probably be written by
joining the inserted
table with whatever the current UDF applies its WHERE clause to, or with
not much more work than that.
In other words, as Ray said, what does the UDF (and the trigger) look like?
SK
Brent Black wrote:

>I've been able to do that in every case except where the ID value from the
>cursor is being passed into a udf that returns a table.. For example:
>insert into sometable (column1, column2)
> select distinct @.CursorValue, pgr.ID
> from someUDF(@.CursorValue) as pgr
>I tried changing this to:
>insert into sometable(column1, column2)
> select distinct i.ID, pgr.ID
> from someUDF(i.ID) as pgr,
> inserted i
> but that didn't work because it expects a single deterministic value to be
>passed into the UDL.. It appears that was why the original dev chose to us
e
>a cursor in the trigger to handle this in the first place. Any ideas on ho
w
>to do this without the cursor?
>Thanks!
>Brent Black
>Onvia.com
>Technical Lead/Database Administrator
>"Ray Higdon" <sqlhigdon@.nospam.yahoo.com> wrote in message
>news:OYCx3KL9DHA.2604@.TK2MSFTNGP10.phx.gbl...
>
>from
>
>to
>
>a
>
>
>|||Hi Brent,
Thank you for using the newsgroup.
Here is an example for your reference, you could run in your Query Analyzer:
use pubs
go
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[authorsx]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[authorsx]
GO
CREATE TABLE [dbo].[authorsx] (
[au_id] [id] NOT NULL ,
[au_lname] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[au_fname] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[phone] [char] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[city] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[state] [char] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[zip] [char] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[contract] [bit] NOT NULL ,
[test_column] varchar(2)
) ON [PRIMARY]
GO
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[author_fun]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[author_fun]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
create function author_fun(@.state varchar(30))
returns table
as
return(select * from authors where @.state=authors.state
)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
truncate table authorsx
insert into authorsx select *,1 from author_fun('CA')
select * from authorsx
go
drop table authorsx
So, I agree with Ray that if your the value returned by the UDF is match
the column you want to insert to or not.
Thanks.
Best regards
Baisong Wei
Microsoft Online Support
----
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
Please reply to newsgroups only. Thanks.|||Hi Brent,
I am reviewing you post and since I have not heard from you for some time,
I wonder whether you have solved you problem or you still have any
questions about that. For any questions, please feel free to post new
message here and I am glad to help.
Best regards
Baisong Wei
Microsoft Online Support
----
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
Please reply to newsgroups only. Thanks.

inserted table

Is it ever possible for the inserted table to have more than one row in a
for update trigger? One of our devs recently put a cursor in his for update
trigger to loop over rows in the inserted table. However, from what I
understand, inserted should never have more than one row in it. I just
wanted to verify this before I removed it as I am working on optimizing it.
Brent Black
Onvia.com
Technical Lead/Database AdministratorThis is a multi-part message in MIME format.
--=_NextPart_000_01FB_01C3F484.E84A26E0
Content-Type: text/plain;
charset="Windows-1252"
Content-Transfer-Encoding: 7bit
The inserted table can indeed have > 1 row in it and you code should take
this into account. Likely, you don't need a cursor either.
--
Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Brent Black" <bblack@.onvia.com> wrote in message
news:uhVRS4K9DHA.3404@.TK2MSFTNGP09.phx.gbl...
Is it ever possible for the inserted table to have more than one row in a
for update trigger? One of our devs recently put a cursor in his for update
trigger to loop over rows in the inserted table. However, from what I
understand, inserted should never have more than one row in it. I just
wanted to verify this before I removed it as I am working on optimizing it.
Brent Black
Onvia.com
Technical Lead/Database Administrator
--=_NextPart_000_01FB_01C3F484.E84A26E0
Content-Type: text/html;
charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

The inserted table can indeed have => 1 row in it and you code should take this into account. Likely, you don't =need a cursor either.
-- Tom
---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql
"Brent Black" wrote in =message news:uhVRS4K9DHA.3404=@.TK2MSFTNGP09.phx.gbl...Is it ever possible for the inserted table to have more than one row in =afor update trigger? One of our devs recently put a cursor in his for updatetrigger to loop over rows in the inserted table. =However, from what Iunderstand, inserted should never have more than one row in =it. I justwanted to verify this before I removed it as I am working on optimizing it.Brent BlackOnvia.comTechnical =Lead/Database Administrator

--=_NextPart_000_01FB_01C3F484.E84A26E0--|||Don't use a cursor in a trigger, typically people do something like this:
update table set column = value where prinmarykey = (select primary key from
inserted)
If you will have multiple updates or inserts you would want to change it to
this
update table set column = value where prinmarykey IN (select primary key
from inserted)
HTH
--
Ray Higdon MCSE, MCDBA, CCNA
--
"Brent Black" <bblack@.onvia.com> wrote in message
news:uhVRS4K9DHA.3404@.TK2MSFTNGP09.phx.gbl...
> Is it ever possible for the inserted table to have more than one row in a
> for update trigger? One of our devs recently put a cursor in his for
update
> trigger to loop over rows in the inserted table. However, from what I
> understand, inserted should never have more than one row in it. I just
> wanted to verify this before I removed it as I am working on optimizing
it.
> Brent Black
> Onvia.com
> Technical Lead/Database Administrator
>|||I've been able to do that in every case except where the ID value from the
cursor is being passed into a udf that returns a table.. For example:
insert into sometable (column1, column2)
select distinct @.CursorValue, pgr.ID
from someUDF(@.CursorValue) as pgr
I tried changing this to:
insert into sometable(column1, column2)
select distinct i.ID, pgr.ID
from someUDF(i.ID) as pgr,
inserted i
but that didn't work because it expects a single deterministic value to be
passed into the UDL.. It appears that was why the original dev chose to use
a cursor in the trigger to handle this in the first place. Any ideas on how
to do this without the cursor?
Thanks!
Brent Black
Onvia.com
Technical Lead/Database Administrator
"Ray Higdon" <sqlhigdon@.nospam.yahoo.com> wrote in message
news:OYCx3KL9DHA.2604@.TK2MSFTNGP10.phx.gbl...
> Don't use a cursor in a trigger, typically people do something like this:
> update table set column = value where prinmarykey = (select primary key
from
> inserted)
> If you will have multiple updates or inserts you would want to change it
to
> this
> update table set column = value where prinmarykey IN (select primary key
> from inserted)
> HTH
> --
> Ray Higdon MCSE, MCDBA, CCNA
> --
> "Brent Black" <bblack@.onvia.com> wrote in message
> news:uhVRS4K9DHA.3404@.TK2MSFTNGP09.phx.gbl...
> > Is it ever possible for the inserted table to have more than one row in
a
> > for update trigger? One of our devs recently put a cursor in his for
> update
> > trigger to loop over rows in the inserted table. However, from what I
> > understand, inserted should never have more than one row in it. I just
> > wanted to verify this before I removed it as I am working on optimizing
> it.
> >
> > Brent Black
> > Onvia.com
> > Technical Lead/Database Administrator
> >
> >
>|||What's the UDF look like?
--
Ray Higdon MCSE, MCDBA, CCNA
--
"Brent Black" <bblack@.onvia.com> wrote in message
news:ucGCsKN9DHA.1936@.TK2MSFTNGP12.phx.gbl...
> I've been able to do that in every case except where the ID value from the
> cursor is being passed into a udf that returns a table.. For example:
> insert into sometable (column1, column2)
> select distinct @.CursorValue, pgr.ID
> from someUDF(@.CursorValue) as pgr
> I tried changing this to:
> insert into sometable(column1, column2)
> select distinct i.ID, pgr.ID
> from someUDF(i.ID) as pgr,
> inserted i
> but that didn't work because it expects a single deterministic value to
be
> passed into the UDL.. It appears that was why the original dev chose to
use
> a cursor in the trigger to handle this in the first place. Any ideas on
how
> to do this without the cursor?
> Thanks!
> Brent Black
> Onvia.com
> Technical Lead/Database Administrator
> "Ray Higdon" <sqlhigdon@.nospam.yahoo.com> wrote in message
> news:OYCx3KL9DHA.2604@.TK2MSFTNGP10.phx.gbl...
> > Don't use a cursor in a trigger, typically people do something like
this:
> >
> > update table set column = value where prinmarykey = (select primary key
> from
> > inserted)
> >
> > If you will have multiple updates or inserts you would want to change it
> to
> > this
> >
> > update table set column = value where prinmarykey IN (select primary key
> > from inserted)
> >
> > HTH
> > --
> > Ray Higdon MCSE, MCDBA, CCNA
> > --
> > "Brent Black" <bblack@.onvia.com> wrote in message
> > news:uhVRS4K9DHA.3404@.TK2MSFTNGP09.phx.gbl...
> > > Is it ever possible for the inserted table to have more than one row
in
> a
> > > for update trigger? One of our devs recently put a cursor in his for
> > update
> > > trigger to loop over rows in the inserted table. However, from what I
> > > understand, inserted should never have more than one row in it. I
just
> > > wanted to verify this before I removed it as I am working on
optimizing
> > it.
> > >
> > > Brent Black
> > > Onvia.com
> > > Technical Lead/Database Administrator
> > >
> > >
> >
> >
>|||Brent,
I wouldn't be surprised if in this case the UDF is something like
create function someUDF(
@.v somedatatype
) returns table ...
WHERE someColumn = @.v
...
If that's the case, then the trigger could probably be written by
joining the inserted
table with whatever the current UDF applies its WHERE clause to, or with
not much more work than that.
In other words, as Ray said, what does the UDF (and the trigger) look like?
SK
Brent Black wrote:
>I've been able to do that in every case except where the ID value from the
>cursor is being passed into a udf that returns a table.. For example:
>insert into sometable (column1, column2)
> select distinct @.CursorValue, pgr.ID
> from someUDF(@.CursorValue) as pgr
>I tried changing this to:
>insert into sometable(column1, column2)
> select distinct i.ID, pgr.ID
> from someUDF(i.ID) as pgr,
> inserted i
> but that didn't work because it expects a single deterministic value to be
>passed into the UDL.. It appears that was why the original dev chose to use
>a cursor in the trigger to handle this in the first place. Any ideas on how
>to do this without the cursor?
>Thanks!
>Brent Black
>Onvia.com
>Technical Lead/Database Administrator
>"Ray Higdon" <sqlhigdon@.nospam.yahoo.com> wrote in message
>news:OYCx3KL9DHA.2604@.TK2MSFTNGP10.phx.gbl...
>
>>Don't use a cursor in a trigger, typically people do something like this:
>>update table set column = value where prinmarykey = (select primary key
>>
>from
>
>>inserted)
>>If you will have multiple updates or inserts you would want to change it
>>
>to
>
>>this
>>update table set column = value where prinmarykey IN (select primary key
>>from inserted)
>>HTH
>>--
>>Ray Higdon MCSE, MCDBA, CCNA
>>--
>>"Brent Black" <bblack@.onvia.com> wrote in message
>>news:uhVRS4K9DHA.3404@.TK2MSFTNGP09.phx.gbl...
>>
>>Is it ever possible for the inserted table to have more than one row in
>>
>a
>
>>for update trigger? One of our devs recently put a cursor in his for
>>
>>update
>>
>>trigger to loop over rows in the inserted table. However, from what I
>>understand, inserted should never have more than one row in it. I just
>>wanted to verify this before I removed it as I am working on optimizing
>>
>>it.
>>
>>Brent Black
>>Onvia.com
>>Technical Lead/Database Administrator
>>
>>
>>
>
>|||Hi Brent,
Thank you for using the newsgroup.
Here is an example for your reference, you could run in your Query Analyzer:
use pubs
go
if exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[authorsx]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[authorsx]
GO
CREATE TABLE [dbo].[authorsx] (
[au_id] [id] NOT NULL ,
[au_lname] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[au_fname] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[phone] [char] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[city] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[state] [char] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[zip] [char] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[contract] [bit] NOT NULL ,
[test_column] varchar(2)
) ON [PRIMARY]
GO
if exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[author_fun]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[author_fun]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
create function author_fun(@.state varchar(30))
returns table
as
return(select * from authors where @.state=authors.state
)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
truncate table authorsx
insert into authorsx select *,1 from author_fun('CA')
select * from authorsx
go
drop table authorsx
So, I agree with Ray that if your the value returned by the UDF is match
the column you want to insert to or not.
Thanks.
Best regards
Baisong Wei
Microsoft Online Support
----
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
Please reply to newsgroups only. Thanks.|||Hi Brent,
I am reviewing you post and since I have not heard from you for some time,
I wonder whether you have solved you problem or you still have any
questions about that. For any questions, please feel free to post new
message here and I am glad to help.
Best regards
Baisong Wei
Microsoft Online Support
----
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
Please reply to newsgroups only. Thanks.

Inserted Rows count from SSIS not like table Rows Count

Hi all

i using lookup error output to insert rows into table

Rows count rows has been inserted on the table 59,123,019 mill

table rows count 6,878,110 mill ............................

any ideas

So from the error output you are getting 59 123 019 rows? How are you counting this?
What are you using to insert the rows?|||Mapping from values i get and columns on distination table|||How are you counting the rows inserted?|||

I figuer out the Reasone my lookup error output configure to ignore the error and the error was "can't insert duplicated key" i change the error output to insert duplicated rows in flat file but i don't test it yet , i will hint with updates , hope that's resolve the problem

wish me luck

Phil

I Count rows from distination table "Select Count "

|||

Hosam Abdel Wahab wrote:

Phil

I Count rows from distination table "Select Count "

I mean, how are you counting the rows inserted from within SSIS?

But, yes, it sounds like you are on the correct path to figuring out your problem.

Inserted Rows

Does anyone have any SP or script that can help me easily
determine the activity within my tables? Specifically, I
am looking for any kind of SPs, scripts, or tools that
can help me easily determine how heavily hit my various
tables are. For example is table A with 1,000,000 rows
in it not the heavily used while table B with 5,000 rows
in it is constantly being inserted to, deleted from, and
updated. I am trying to track down my heavy hitter
tables to do some P&T on them or move them to their own
files, etc.Z,
You can use SQL Profiler to track activity against a database. One data
column it can report is the ObjectName being referenced. Examine the
discussion in the BOL on SQL Profiler and SQL Trace.
Ideally, you would run the trace and spool its results to a file. Afterward
you can load the file into a table and do some queries to aggregate the
activity you are experiencing.
Running a trace will take some CPU from your server, but if you are
judicious in the events and data columns it should not be oppressive to the
server unless you are running at very high CPU levels already.
Russell Fields
http://www.sqlpass.org/
2004 PASS Community Summit - Orlando
- The largest user-event dedicated to SQL Server!
"Z" <anonymous@.discussions.microsoft.com> wrote in message
news:07a601c3af8f$d7d328f0$a001280a@.phx.gbl...
> Does anyone have any SP or script that can help me easily
> determine the activity within my tables? Specifically, I
> am looking for any kind of SPs, scripts, or tools that
> can help me easily determine how heavily hit my various
> tables are. For example is table A with 1,000,000 rows
> in it not the heavily used while table B with 5,000 rows
> in it is constantly being inserted to, deleted from, and
> updated. I am trying to track down my heavy hitter
> tables to do some P&T on them or move them to their own
> files, etc.
>

Inserted row deletes after trigger

I'm hoping someone has seen this before because I have no idea what could be causing it.

I have an SQL 2005 database with multiple tables and several triggers on the various tables all set to run after insert and update.

My program inserts a record into the "items" via a SP that returns the index of the newly added row. The program then inserts a row into another table that is related to items. When the row is inserted into the second table it gets an error that it cannot insert the record because of a foreign key restraint. Checking the items table shows the record that was just inserted in there is now deleted.

The items record is only deleted when I have my trigger on that table enabled. Here is the text of the trigger:

GO
SETANSI_NULLSON
GO
SETQUOTED_IDENTIFIERON
GO

ALTERTRIGGER [dbo].[TestTrigger]
ON [dbo].[items]
AFTERINSERT

AS
BEGIN

SETNOCOUNTON;

INSERTINTO tblHistory(table_name, record_id, is_insert)
VALUES('items', 123, 1)

END

tblHistory's field types are (varchar(50), BigInt, bit).

As you can see there is nothing in the trigger to cause the items record to be deleted, so I have no idea what it could be? Anyone ever see this before?

Thanks in advance!

Hey,

I don't know that the row is deleted, but that the row doesn't get actually inserted for some reason. What do the two insertions look like? In SQL or ADO.NET code? Could it be that the first item doesn't get inserted, then returns a number that doesn't match an entry in that table, and that is why you get an error for the second insert?

|||

No, the first item is inserted and the returned value is exactly what it should be. When we test it without the trigger enabled and it all works, the new primary key value is the next value after the one that disapeared (i.e. if the record that was deleted was 5 the next one that works is 6).

|||

Are you using @.@.identity?

|||

If one of the follow on triggers fails, for whatever reason, the insert statement will be rolled back.

I suggest commenting out the triggers one by one (from last run to first run) until you figure out which one is the problem.

(Or learn to use the debugger in sql server.)

|||

David is correct in that the trigger code is considered part of the insert transaction.

If the trigger fails, then the entire "transaction" is rolled back, including the insert. If tblHistory has a foreign key constraint, and the trigger fails because of it, then you will get exactly what you are describing. The record is inserted partially (uncommitted), the trigger is fired, an error is encountered, then the insert is rolled back and the error from the trigger is sent to the client.

|||

It couldn't have been the trigger failing, b/c there are no constraints on the history table and while yo uare correct the error would have been returned as if it was coming from the insert statement I said above "When the row is inserted into the second table it gets an error that it cannot insert the record because of a foreign key restraint." The error was not about hte history table.

Motley you actually had the answer. What was happening is the stored procedure ran and inserted the row into items, the trigger ran on that and inserted the row into web updates, the stored procedure then returned the @.@.Identity, but since that returns the last identity of any insert to the database it was returning the identity of the history table, not the items table. When the second insert was run it was trying to insert the wrong identity and failed the foreign key restraint, resulting in the entire transaction to fail and rollback, giving the appearance the items record had been deleted.

Thanks for your help!

|||

Use scope_identity(), not identity! scope_identity was created to avoid just this problem!

sql

Inserted records missing in sql table yet tables primary key field has been incremented.

I have a sql sever 2005 express table with an automatically incremented primary key field. I use a Detailsview to insert new records and on the Detailsview itemInserted event, i send out automated notification emails.

I then received two automated emails(indicating two records have been inserted) but looking at the database, the records are not there. Whats confusing me is that even the tables primary key field had been incremented by two, an indication that indeed the two records should actually be in table. Recovering these records is not abig deal because i can re-enter them but iam wondering what the possible cause is. How come the id field was even incremented and the records are not there yet iam 100% sure no one deleted them. Its only me who can delete a record.

And then how come i insert new records now and they are all there in the database but now with two id numbers for those missing records skipped. Its not crucial data but for my learning, i feel i deserve understanding why it happened because next time, it might be costly.

Hi Nick,

Your problem seems interesting. Would you please put some related code here. So that we can analyze what exactly going on there.

|||

The code below indicates when the automated email is send and after that is the markup of my page.

ProtectedSub DetailsView1_ItemInserted(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.DetailsViewInsertedEventArgs)

'I have code to send automated emails here.

EndIf

Catch exAs Exception

'iam not catching nor doing any thing here. (possibly i should have done some thing here)

Finally

Response.Redirect("AfterInserting.aspx")

EndTry

And the markup is below

<asp:ContentID="Content1"ContentPlaceHolderID="ContentPlaceHolder1"Runat="Server">

<table>

<tr>

<tdstyle="width: 100px; height: 21px; text-align: left;"valign="top">

<asp:LabelID="Label8"runat="server"Width="126px"></asp:Label>

<asp:LabelID="Label20"runat="server"Width="128px"ForeColor="#0000FF"></asp:Label></td>

<tdstyle="width: 100px; height: 21px; text-align: left;"valign="top">

<asp:DetailsViewID="DetailsView1"runat="server"AutoGenerateRows="False"DataKeyNames="Incident_id"

DataSourceID="SqlDataSource1"DefaultMode="Insert"Height="50px"Width="497px"Font-Size="Smaller"OnItemInserted="DetailsView1_ItemInserted"BackColor="LightGoldenrodYellow"BorderColor="Tan"BorderWidth="1px"CellPadding="2"ForeColor="Black"OnItemInserting="DetailsView1_ItemInserting">

<Fields>

<asp:TemplateFieldHeaderText="Incident_id"InsertVisible="False"SortExpression="Incident_id">

<EditItemTemplate>

<asp:LabelID="Label1"runat="server"Text='<%# Eval("Incident_id") %>'></asp:Label>

</EditItemTemplate>

<ItemTemplate>

<asp:LabelID="Label20"runat="server"Text='<%# Bind("Incident_id") %>'ToolTip="This is the Incident Number"></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Person Raising Report"SortExpression="Incident_Reported_By">

<EditItemTemplate>

<asp:TextBoxID="TextBox7"runat="server"Text='<%# Bind("Incident_Reported_By") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:TextBoxID="TextBox2"runat="server"Text='<%# Bind("Incident_Reported_By") %>'ToolTip="Type the name of the person raising the report here (Your Name)"></asp:TextBox>

<asp:RequiredFieldValidatorID="RequiredFieldValidator1"runat="server"ControlToValidate="TextBox2"

ErrorMessage='You have not provided your name ......You must enter your name in the Person raising report field in order to report this incident .'

SetFocusOnError="True"ValidationGroup="email"EnableTheming="False">*</asp:RequiredFieldValidator>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label7"runat="server"Text='<%# Bind("Incident_Reported_By") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Person Raising Report's Employee#"SortExpression="Emp_No">

<EditItemTemplate>

<asp:TextBoxID="TextBox2"runat="server"Text='<%# Bind("Emp_No") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:DropDownListID="DropDownList1"runat="server"DataSourceID="SqlDataSource20"

DataTextField="EmpNumber"DataValueField="EmpNumber"SelectedValue='<%# Bind("Emp_No") %>'

Width="156px"ToolTip="Select Your Employee Number here. If you have no number check other options at bottom of the list and select one that suits you">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSource20"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT [EmpNumber] FROM [EmpNumbers] ORDER BY [EmpNumber]"></asp:SqlDataSource>

<asp:RequiredFieldValidatorID="RequiredFieldValidator2"runat="server"ControlToValidate="DropDownList1"

ErrorMessage="You must select your Employee Number. Other options are : Trainee, Contractor, Casual, Canteen staff and Security personnel. "

InitialValue=".."ValidationGroup="email">.</asp:RequiredFieldValidator>

<asp:TextBoxID="TextBox24"runat="server"Text='<%# Eval("Emp_No") %>'Visible="False"></asp:TextBox>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label2"runat="server"Text='<%# Bind("Emp_No") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Personnel Directly Involved"SortExpression="Personnel_Directly_Involved">

<EditItemTemplate>

<asp:TextBoxID="TextBox10"runat="server"Text='<%# Bind("Personnel_Directly_Involved") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:TextBoxID="TextBox4"runat="server"Text='<%# Bind("Personnel_Directly_Involved") %>'ToolTip="Type the name of the person directly involved in the Incident here"></asp:TextBox>

<asp:RequiredFieldValidatorID="RequiredFieldValidator4"runat="server"ControlToValidate="TextBox4"

ErrorMessage="Error in Personnel directly Involved Field....This field can not left blank"SetFocusOnError="True"

ValidationGroup="email">*</asp:RequiredFieldValidator>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label10"runat="server"Text='<%# Bind("Personnel_Directly_Involved") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Witness 1">

<InsertItemTemplate>

<asp:TextBoxID="TextBox21"runat="server"ToolTip="Type the name of the witness here. You can not leave this field blank"></asp:TextBox>

<asp:RequiredFieldValidatorID="RequiredFieldValidator8"runat="server"ControlToValidate="TextBox21"

EnableTheming="True"ErrorMessage="You must atleast specify one witness to the Incident. Please type the witness name."

SetFocusOnError="True"ValidationGroup="email">.</asp:RequiredFieldValidator>

</InsertItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Witness 2">

<InsertItemTemplate>

<asp:TextBoxID="TextBox22"runat="server"Text='<%# Bind("Witness_2") %>'ToolTip="Type the name of the second witness here if any. (Optional)"></asp:TextBox>

</InsertItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Witness 3">

<InsertItemTemplate>

<asp:TextBoxID="TextBox23"runat="server"Text='<%# Bind("witness_3") %>'ToolTip="Type the name of the third witness here if any (Optional)"></asp:TextBox>

</InsertItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Date Incident Occured "SortExpression="Incident_Date">

<EditItemTemplate>

<asp:TextBoxID="TextBox1"runat="server"Text='<%# Bind("Incident_Date") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<cc1:GMDatePickerID="GMDatePicker1"runat="server"AutoPosition="True"CalendarOffsetX="-200px"CalendarOffsetY="25px"CalendarTheme="Green"CalendarWidth="250px"CallbackEventReference=""Culture="English (United States)"DateString='<%# bind("Incident_Date") %>'EnableDropShadow="True"MaxDate="2020-12-31"MinDate=""NextMonthText=">"NoneButtonText="None"ShowNoneButton="False"ShowTodayButton="True"TextBoxWidth="150"ZIndex="1"InitialText="select date"ToolTip="Click the icon on the right to select the date on which the incident occurred">

<CalendarTodayDayStyleBackColor="#C0FFC0"/>

</cc1:GMDatePicker>

<asp:RequiredFieldValidatorID="RequiredFieldValidator6"runat="server"ControlToValidate="GMDatePicker1"

ErrorMessage="You must select the date on which this Incident Occurred. Click the icon next to the incident occurred date field to show a calendar and then click the desired date from the calendar."

SetFocusOnError="True"ValidationGroup="email"InitialValue="select date">.</asp:RequiredFieldValidator>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label1"runat="server"Text='<%# Bind("Incident_Date") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Date Incident Is Reported "SortExpression="Date_Reported">

<EditItemTemplate>

<asp:TextBoxID="TextBox9"runat="server"></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:TextBoxID="Textbox3"runat="server"Text='<%# Bind("Date_Reported") %>'ReadOnly="True"Font-Size="9pt"ForeColor="#6666FF"ToolTip="Do not type anything here. This field is automated to always display and save the current date"></asp:TextBox>

<asp:RequiredFieldValidatorID="RequiredFieldValidator3"runat="server"ControlToValidate="TextBox3"

ErrorMessage="Error in Incident Reported Date....This field can not be left blank. "

SetFocusOnError="True"ValidationGroup="email">*</asp:RequiredFieldValidator>

<asp:CompareValidatorID="CompareValidator2"runat="server"ControlToValidate="TextBox3"

ErrorMessage='Error in Incident Reported Date Field. Re-enter date in month/day/year format '

Operator="DataTypeCheck"SetFocusOnError="True"Type="Date"ValidationGroup="email">*</asp:CompareValidator>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label9"runat="server"Text='<%# Bind("Date_Reported") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Time Incident Occurred"SortExpression="TimeCoomencedshift">

<EditItemTemplate>

<asp:TextBoxID="TextBox16"runat="server"Text='<%# Bind("TimeCoomencedshift") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:TextBoxID="TextBox9"runat="server"Text='<%# Bind("time_incident_occurred") %>'Width="67px"Height="21px"ToolTip="Type the time at which the incident occurred here in 24 hour format."></asp:TextBox>

<asp:ListBoxID="ListBox1"runat="server"Height="24px"Width="55px"ToolTip="Use the up and down arrows to specify AM or PM">

<asp:ListItem>PM</asp:ListItem>

<asp:ListItem>AM</asp:ListItem>

</asp:ListBox>

<asp:RequiredFieldValidatorID="RequiredFieldValidator7"runat="server"ControlToValidate="TextBox9"

ErrorMessage="You must enter the time at which the Incident occurred"SetFocusOnError="True"

ValidationGroup="email"Height="10px">.</asp:RequiredFieldValidator>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label16"runat="server"Text='<%# Bind("TimeCoomencedshift") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="ReminderDate"SortExpression="ReminderDate">

<EditItemTemplate>

<asp:TextBoxID="TextBox8"runat="server"Text='<%# Bind("ReminderDate") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:TextBoxID="TextBox6"runat="server"Text='<%# Bind("ReminderDate") %>'Font-Size="9pt"ForeColor="#6666FF"ReadOnly="True"ToolTip="Do not type any thing here. This field is automated to always add 3 days to the current date "></asp:TextBox>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label8"runat="server"Text='<%# Bind("ReminderDate") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Department">

<InsertItemTemplate>

<asp:DropDownListID="DropDownList5"runat="server"DataSourceID="DEPTDataSource1"

DataTextField="name"DataValueField="name"SelectedValue='<%# Bind("Dept") %>'

Width="155px"ToolTip="Click the arrow ponting down to select a department of the person involved from this list ">

</asp:DropDownList><asp:SqlDataSourceID="DEPTDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT [name] FROM [Deptments] ORDER BY [name]"></asp:SqlDataSource>

</InsertItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Incident Location"SortExpression="Incident_Location">

<EditItemTemplate>

<asp:TextBoxID="TextBox3"runat="server"Text='<%# Bind("Incident_Location") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:DropDownListID="DropDownList2"runat="server"DataSourceID="SqlDataSource3"

DataTextField="Area_Name"DataValueField="Area_Name"SelectedValue='<%# Bind("Incident_Location") %>'

Width="155px"ToolTip="Select the location where the incident occurred from this list">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSource3"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT [Area_Name] FROM [Incident_Areas] ORDER BY [Area_Name]"></asp:SqlDataSource>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label3"runat="server"Text='<%# Bind("Incident_Location") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Incident Category"SortExpression="Incident_Category">

<EditItemTemplate>

<asp:TextBoxID="TextBox4"runat="server"Text='<%# Bind("Incident_Category") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:DropDownListID="DropDownList3"runat="server"DataSourceID="SqlDataSource5"

DataTextField="Category_Name"DataValueField="Category_Name"SelectedValue='<%# Bind("Incident_Category") %>'

Width="155px"ToolTip="Select the category of the incident from this list. Please take special note of injuries ">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSource5"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT [Category_Name] FROM [Incident_Category] ORDER BY [Category_Name]">

</asp:SqlDataSource>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label4"runat="server"Text='<%# Bind("Incident_Category") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Incident Severity"SortExpression="Incident_Severity">

<EditItemTemplate>

<asp:TextBoxID="TextBox5"runat="server"Text='<%# Bind("Incident_Severity") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:DropDownListID="DropDownList4"runat="server"DataSourceID="SqlDataSource7"

DataTextField="Incident_Severity"DataValueField="Incident_Severity"SelectedValue='<%# Bind("Incident_Severity") %>'

Width="157px"ToolTip="Select the incident severity from this list">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSource7"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT [Incident_Severity] FROM [Incident_Severity] ORDER BY [Incident_Severity]">

</asp:SqlDataSource>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label5"runat="server"Text='<%# Bind("Incident_Severity") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Incident classification"SortExpression="Incident_classification"Visible="False">

<EditItemTemplate>

<asp:TextBoxID="TextBox12"runat="server"Text='<%# Bind("Incident_classification") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:DropDownListID="DropDownList7"runat="server"DataSourceID="SqlDataSource16"

DataTextField="classification"DataValueField="classification"SelectedValue='<%# Bind("Incident_classification") %>'

Width="157px">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSource16"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT [classification] FROM [Incident_Classification]"></asp:SqlDataSource>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label12"runat="server"Text='<%# Bind("Incident_classification") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText=" Incident timing"SortExpression="TimingOfIncident"Visible="False">

<EditItemTemplate>

<asp:TextBoxID="TextBox19"runat="server"Text='<%# Bind("TimingOfIncident") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:DropDownListID="DropDownList8"runat="server"DataSourceID="SqlDataSource26"

DataTextField="timing"DataValueField="timing"SelectedValue='<%# Bind("TimingOfIncident") %>'

Width="155px">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSource26"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT [timing] FROM [roster_timing_OfIncident]"></asp:SqlDataSource>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label19"runat="server"Text='<%# Bind("TimingOfIncident") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Shift Details"SortExpression="ShiftDetails"Visible="False">

<EditItemTemplate>

<asp:TextBoxID="TextBox18"runat="server"Text='<%# Bind("ShiftDetails") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:DropDownListID="DropDownList9"runat="server"DataSourceID="SqlDataSource27"

DataTextField="shiftdetails"DataValueField="shiftdetails"SelectedValue='<%# Bind("ShiftDetails") %>'

Width="158px">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSource27"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT [shiftdetails] FROM [ShiftDetails]"></asp:SqlDataSource>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label18"runat="server"Text='<%# Bind("ShiftDetails") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Equipment Involved"SortExpression="EquipmentInvolved">

<EditItemTemplate>

<asp:TextBoxID="TextBox13"runat="server"Text='<%# Bind("EquipmentInvolved") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:DropDownListID="DropDownList6"runat="server"DataSourceID="SqlDataSource28"

DataTextField="Cause"DataValueField="Cause"SelectedValue='<%# Bind("EqiupmentInvolved") %>'

Width="156px"ToolTip="Select the equipment involved in incident. If the equipment involved does not exist in the list, please notify safety to have the equipment added to the list.">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSource28"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT [Cause] FROM [WhatCausedInjury] ORDER BY [Cause]"></asp:SqlDataSource>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label13"runat="server"Text='<%# Bind("EquipmentInvolved") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="N0. of days into Roster Cycle"SortExpression="Time Incident Occurred"Visible="False">

<EditItemTemplate>

<asp:TextBoxID="TextBox17"runat="server"Text='<%# Bind("NumberOfDaysintoRosterCycle") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:TextBoxID="TextBox10"runat="server"Text='<%# Bind("NumberOfDaysintoRosterCycle") %>'></asp:TextBox>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label17"runat="server"Text='<%# Bind("NumberOfDaysintoRosterCycle") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Hours into shift"SortExpression="Hoursintoshift"Visible="False">

<EditItemTemplate>

<asp:TextBoxID="TextBox15"runat="server"Text='<%# Bind("Hoursintoshift") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:TextBoxID="TextBox8"runat="server"Text='<%# Bind("Hoursintoshift") %>'></asp:TextBox>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label15"runat="server"Text='<%# Bind("Hoursintoshift") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Time To Finish shift"SortExpression="TimeToFinishshift"Visible="False">

<EditItemTemplate>

<asp:TextBoxID="TextBox14"runat="server"Text='<%# Bind("TimeToFinishshift") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:TextBoxID="TextBox7"runat="server"Text='<%# Bind("TimeToFinishshift") %>'></asp:TextBox>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label14"runat="server"Text='<%# Bind("TimeToFinishshift") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Incident Brief Description"SortExpression="Incident_Description">

<EditItemTemplate>

<asp:TextBoxID="TextBox11"runat="server"Text='<%# Bind("Incident_Description") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:TextBoxID="TextBox5"runat="server"Height="45px"Text='<%# Bind("Incident_Description") %>'

TextMode="MultiLine"Width="199px"ToolTip="Briefly describe the incident here. You can type upto a maximum of 4000 characters"></asp:TextBox>

<asp:RequiredFieldValidatorID="RequiredFieldValidator5"runat="server"ControlToValidate="TextBox5"

ErrorMessage="Error in Incident Description Field....You must briefly describe the nature of the Incident"SetFocusOnError="True"

ValidationGroup="email">*</asp:RequiredFieldValidator>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label11"runat="server"Text='<%# Bind("Incident_Description") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Immediate Action"SortExpression="Immediate_Action">

<EditItemTemplate>

<asp:TextBoxID="TextBox6"runat="server"Text='<%# Bind("Immediate_Action") %>'></asp:TextBox>

</EditItemTemplate>

<InsertItemTemplate>

<asp:TextBoxID="TextBox20"runat="server"Text='<%# Bind("Immediate_Action") %>'

TextMode="MultiLine"Height="41px"Width="201px"ToolTip="Type the immediate action taken when the incident occurred here"></asp:TextBox>

<asp:RequiredFieldValidatorID="RequiredFieldValidator9"runat="server"ControlToValidate="TextBox20"

ErrorMessage="No Immediate Action Entered: Please first enter the Immediate Action taken when the Incident Occurred"

SetFocusOnError="True"ValidationGroup="email">.</asp:RequiredFieldValidator>

</InsertItemTemplate>

<ItemTemplate>

<asp:LabelID="Label6"runat="server"Text='<%# Bind("Immediate_Action") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Foward To Your Head Of Department">

<InsertItemTemplate>

<asp:DropDownListID="DropDownList10"runat="server"DataSourceID="SqlDataSource50"

DataTextField="Names"DataValueField="Names"SelectedValue='<%# Bind("Foward_to") %>'

Width="154px"ToolTip="Select the head of department you want to foward the incident to from here">

</asp:DropDownList><asp:SqlDataSourceID="SqlDataSource50"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT [Names] FROM [H.O.D's] ORDER BY [Names]"></asp:SqlDataSource>

<asp:RequiredFieldValidatorID="RequiredFieldValidator10"runat="server"ControlToValidate="DropDownList10"

ErrorMessage="You have not selected the Head Of Department. Please select your head of department and then report agian."SetFocusOnError="True"ValidationGroup="email">.</asp:RequiredFieldValidator>

</InsertItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldShowHeader="False">

<InsertItemTemplate>

<asp:ButtonID="Button1"runat="server"CausesValidation="True"CommandName="Insert"

Text="Report Incident/Hazard"ValidationGroup="email"/>

<asp:ButtonID="Button2"runat="server"PostBackUrl="~/StartPage.aspx"Text="<< Exit"/>

</InsertItemTemplate>

<ItemStyleHorizontalAlign="Center"/>

<ItemTemplate>

<asp:ButtonID="Button1"runat="server"CausesValidation="False"CommandName="New"

Text="New"/>

</ItemTemplate>

</asp:TemplateField>

</Fields>

<FieldHeaderStyleHorizontalAlign="Right"/>

<InsertRowStyleHorizontalAlign="Left"/>

<FooterStyleBackColor="Tan"/>

<EditRowStyleBackColor="DarkSlateBlue"ForeColor="GhostWhite"/>

<PagerStyleBackColor="PaleGoldenrod"ForeColor="DarkSlateBlue"HorizontalAlign="Center"/>

<HeaderStyleBackColor="Tan"Font-Bold="True"/>

<AlternatingRowStyleBackColor="PaleGoldenrod"/>

</asp:DetailsView>

<asp:SqlDataSourceID="SqlDataSource1"runat="server"

ConnectionString="<%$ ConnectionStrings:ConnectionString %>"DeleteCommand="DELETE FROM [Report_Incident] WHERE [Incident_id] = @.original_Incident_id"

InsertCommand="INSERT INTO Report_Incident(Incident_Reported_By, Incident_Date, Date_Reported, ReminderDate, Personnel_Directly_Involved, Incident_Location, Incident_Category, Incident_Severity, Immediate_Action, Incident_Description, Incident_Assigned_To, EqiupmentInvolved, Emp_No, Foward_to, Dept, witness_1, witness_2, witness_3, time_incident_occurred) VALUES (@.Incident_Reported_By,@.Incident_Date,@.Date_Reported,@.ReminderDate, @.Personnel_Directly_Involved,@.Incident_Location,@.Incident_Category,@.Incident_Severity, @.Immediate_Action,@.Incident_Description,@.Incident_Assigned_To,@.EqiupmentInvolved, @.Emp_No,@.Foward_to,@.Dept,@.witness_1,@.witness_2,@.witness_3,@.time_incident_occurred) "

OldValuesParameterFormatString="original_{0}"SelectCommand="SELECT Incident_id, Incident_Reported_By, Incident_Date, Date_Reported, Personnel_Directly_Involved, Incident_Location, Incident_Category, Incident_Severity, Immediate_Action, Incident_Description, Incident_Assigned_To, Incident_classification, EqiupmentInvolved,Emp_No, ReminderDate,Foward_to, Dept, witness_1, witness_2, witness_3, time_incident_occurred FROM Report_Incident"EnableCaching="True">

<DeleteParameters>

<asp:ParameterName="original_Incident_id"Type="Int32"/>

</DeleteParameters>

<InsertParameters>

<asp:ParameterName="Incident_Reported_By"Type="String"/>

<asp:ParameterName="Emp_No"/>

<asp:ParameterName="Incident_Date"Type="DateTime"/>

<asp:ParameterName="Date_Reported"Type="DateTime"/>

<asp:ParameterName="ReminderDate"/>

<asp:ParameterName="Personnel_Directly_Involved"Type="String"/>

<asp:ParameterName="Incident_Location"Type="String"/>

<asp:ParameterName="Incident_Category"Type="String"/>

<asp:ParameterName="Incident_Severity"Type="String"/>

<asp:ParameterName="Immediate_Action"Type="String"/>

<asp:ParameterName="Incident_Description"Type="String"/>

<asp:ParameterName="Incident_Assigned_To"Type="String"/>

<asp:ParameterName="EqiupmentInvolved"/>

<asp:ParameterName="Foward_to"/>

<asp:ParameterName="Dept"/>

<asp:ParameterName="witness_1"/>

<asp:ParameterName="witness_2"/>

<asp:ParameterName="witness_3"/>

<asp:ParameterName="time_incident_occurred"/>

</InsertParameters>

</asp:SqlDataSource>

<asp:ValidationSummaryID="ValidationSummary1"runat="server"ShowMessageBox="True"

ShowSummary="False"ValidationGroup="email"Font-Strikeout="True"Height="1px"Width="179px"/>

</td>

<tdstyle="height: 21px; width: 3px;"valign="top">

<br/>

<br/>

<br/>

<br/>

<br/>

<br/>

<br/>

<br/>

<br/>

<asp:ButtonID="Button3"runat="server"Text="Get Help ?"Width="101px"Font-Bold="False"OnClientClick='window.open("Help/onreporting.aspx")'/><br/>

<br/>

<asp:ButtonID="Button1"runat="server"PostBackUrl="~/StartPage.aspx"Text="<< Back"

Width="97px"/><br/>

</td>

</tr>

</table>

</asp:Content>

|||

Identity column data is not guaranteed to be consecutive.

If the inserts were done in the context of a transaction, and the transaction is rolled back, then that is exactly what you will see. They were there at one point, but since the transaction was rolled back they are no longer there, and the identity seed is incremented.

|||

Motley:

Identity column data is not guaranteed to be consecutive.

If the inserts were done in the context of a transaction, and the transaction is rolled back, then that is exactly what you will see. They were there at one point, but since the transaction was rolled back they are no longer there, and the identity seed is incremented.

Thanks.|||

I got the problem. There was a field in the table with varchar(7) datatype and if some one tried to insert a record and typed more than 7 characters in the textbox that insertes into this table column, the identity field would be incremented but nothing would actually be saved in the database. In my own opinion, i would say microsoft should have designed it in a way that if nothing is inserted due to such a problem, then let nothing be done on database as well. Incrementing the identity field even when no record has been inserted makes it harder to troubleshoot.