Showing posts with label rows. Show all posts
Showing posts with label rows. Show all posts

Friday, March 30, 2012

INSERTING 20Mill Records into a Table with 100Mill Records..

Hi, Iam new to SQL Srvr 2005 with a Oracle Background..

I have three tables
Table 1 (100 Mill Rows)
Table 2 (20 Mill Rows)
Table 3 (10 Mill Rows)

INSERT INTO Table1
select Table2.* from Table 2
where exists (select 1 from Table3
where Table2.xyz = Table3.xyz
and Table2.abc = Table3.abc);

Whats the most efficient way to do this..
Iam already DISABL'ng the Indexes before the Insert on Table 1
Also -- Whats the SQLSRVR's equivalent to Rollback Segment?

I would suggest to use a join and be sure to have indexes in table2 and table3 by the columns used in the join.

- index on table2 by (xyz, abc)

- index on table3 by (xyz, abc)

The index could be also by (abc, xyz), but it will depend on the order of an existing constraint like primary key or foreign key, or in case there not a constraint, then the selectivity of those columns..

INSERT INTO Table1

select

Table2.*

from

Table 2 inner join Table3

on Table2.xyz = Table3.xyz and Table2.abc = Table3.abc

AMB

|||

Inserting 20 mil rows at one time will create a log of Transaction Log activity.

IF, and that is a big IF, this is a singular operation, and if there is no other activity in the database, you may wish to change the recovery model to 'SIMPLE' (after first making a backup.)

Then do the import in batches of 100k rows - this will greatly reduce the logging pressure and could make a radical difference in speed.

When finished, return the recovery model to the previous setting. AND then make a full backup.

|||

If you go with changing the Recovery Model to simple and back, you'll want to be sure to run a full back-up immediately after reverting back.

Switching to the Simple model breaks the log chain and a full back-up is required to establish a new chain.

|||

Thanks, Dale,

I should have explicitly mentioned that (assumptions, assumptions, etc.)

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

Wednesday, March 28, 2012

inserted and deleted tables

ok i know the rows being affected are put in these temporary tables, but
if i do an insert with 5 rows does inserted have 5 rows in it?
if htats the case how do you check field values for every row
I was using
if (select newfield from #inserted) = this
begin
update #inserted set newfield = that
end
but that isnt going to work if inserted contains all 5 rows, i thought
inserted only had the current row and it passed through the instead of
trigger 5 times once for each row. if thats not the case how do you do
something like
for each newfield in #inserted do
if newfield is this
set it to this.
for example
say i have an insert with three fields
category, categoryid, name
and the 3 rows in my insert are
('Standard', 1, 'Toys')
('NonStandard, null, 'Games')
('Misc', null, 'Puzzles')
and in my instead of trigger i want to fill the nulls with the proper
number so in my instead of trigger i say
if (field2 is null)
begin
set field2 = (select rightnumber from mastertable where name = field2)
end
but it has to do it for each rowChris M wrote:
> ok i know the rows being affected are put in these temporary tables,
> but if i do an insert with 5 rows does inserted have 5 rows in it?
> if htats the case how do you check field values for every row
> I was using
> if (select newfield from #inserted) = this
> begin
> update #inserted set newfield = that
> end
> but that isnt going to work if inserted contains all 5 rows, i thought
> inserted only had the current row and it passed through the instead of
> trigger 5 times once for each row. if thats not the case how do you
> do something like
> for each newfield in #inserted do
> if newfield is this
> set it to this.
> for example
> say i have an insert with three fields
> category, categoryid, name
> and the 3 rows in my insert are
> ('Standard', 1, 'Toys')
> ('NonStandard, null, 'Games')
> ('Misc', null, 'Puzzles')
> and in my instead of trigger i want to fill the nulls with the proper
> number so in my instead of trigger i say
> if (field2 is null)
> begin
> set field2 = (select rightnumber from mastertable where name = field2)
> end
> but it has to do it for each row
Yes. The inserted and deleted logical tables contain all affected rows.
No. You cannot modify data in the inserted and deleted tables, so I'm
not quite sure how your code was even executing. The tables do not have
a '#' prefix. The are plainly 'inserted' and 'deleted'.
How would you get the "right number" from mastertable is the second
column is NULL. What are you joining on?
Personally, I would just throw up a RAISERROR. I don't really understand
your test scenario. If you could join up with mastertable, then it seems
you should be using a FK to that table rather than repeating data
values.
Could you provide the DDL for the tables in question.
David Gugick
Imceda Software
www.imceda.com|||It will do it for each row in inserted, just write the expression on the
right of the set newfield =...
so that it will be a different value for each row of inserted...
update Table set newfield =
Case newfield
When 'this' Then 'That'
When 'TheOther' Then 'OtherThat'
End
But what is #Inserted? a Temporary Table?
What are you trying to update in this trigger?
"Chris M" wrote:

> ok i know the rows being affected are put in these temporary tables, but
> if i do an insert with 5 rows does inserted have 5 rows in it?
> if htats the case how do you check field values for every row
> I was using
> if (select newfield from #inserted) = this
> begin
> update #inserted set newfield = that
> end
> but that isnt going to work if inserted contains all 5 rows, i thought
> inserted only had the current row and it passed through the instead of
> trigger 5 times once for each row. if thats not the case how do you do
> something like
> for each newfield in #inserted do
> if newfield is this
> set it to this.
> for example
> say i have an insert with three fields
> category, categoryid, name
> and the 3 rows in my insert are
> ('Standard', 1, 'Toys')
> ('NonStandard, null, 'Games')
> ('Misc', null, 'Puzzles')
> and in my instead of trigger i want to fill the nulls with the proper
> number so in my instead of trigger i say
> if (field2 is null)
> begin
> set field2 = (select rightnumber from mastertable where name = field2)
> end
> but it has to do it for each row
>|||--BEGIN PGP SIGNED MESSAGE--
Hash: SHA1
Stop thinking procedure and start thinking sets. If there are 3 rows in
the inserted set and 2 have NULL in some column (as your example shows)
you can do an UPDATE like this:
UPDATE original_table
SET column_name = (select rightnumber
from mastertable m inner join inserted i
on m.<join cols> = i.<join cols> )
WHERE EXISTS (SELECT * FROM inserted
WHERE column_name IS NULL
AND inserted.ID = original_table.ID)
The "WHERE column_name IS NULL" in the UPDATE's WHERE clause subquery
will identify the rows in original_table that have the 'column_name' set
to the "rightnumber."
The <join cols> have to be a column, or columns, that uniquely identify
the rows in inserted that relate to rows in mastertable, so the
"rightnumber" can be retrieved. I would have to see the design of
mastertable and original_table to determine which columns those would
be. You could even do w/o the inserted set and just use something in
the mastertable that identifies which row in mastertable has the correct
data that is to be placed in the original_table. IOW, if you had a
Default value in mastertable that always goes in that column - data in
mastertable looks like this:
column_ rightnumber
-- --
Price 25
The SET subquery would look like this:
SET Price = (select rightnumber
from mastertable
where column_ = 'Price')
NB: By now you should realize that you can create a DEFAULT on the
column(s) in original_table instead of using a trigger like the above.
E.g.: CREATE TABLE T (col_1 int, col_a char(2) default ('zz'))
insert into t (col_1) values (2)
select * from t
col_1 col_a
-- --
2 zz
--
MGFoster:::mgf00 <at> earthlink <decimal-point> net
Oakland, CA (USA)
--BEGIN PGP SIGNATURE--
Version: PGP for Personal Privacy 5.0
Charset: noconv
iQA/ AwUBQmguqYechKqOuFEgEQJJSgCg8iAqLWvq7TwF
9BLQlhBbcY/uxx0AnRRi
DXmdayzhLIxU5WBk4wSL4x4R
=mDFy
--END PGP SIGNATURE--
Chris M wrote:
> ok i know the rows being affected are put in these temporary tables, but
> if i do an insert with 5 rows does inserted have 5 rows in it?
> if htats the case how do you check field values for every row
> I was using
> if (select newfield from #inserted) = this
> begin
> update #inserted set newfield = that
> end
> but that isnt going to work if inserted contains all 5 rows, i thought
> inserted only had the current row and it passed through the instead of
> trigger 5 times once for each row. if thats not the case how do you do
> something like
> for each newfield in #inserted do
> if newfield is this
> set it to this.
> for example
> say i have an insert with three fields
> category, categoryid, name
> and the 3 rows in my insert are
> ('Standard', 1, 'Toys')
> ('NonStandard, null, 'Games')
> ('Misc', null, 'Puzzles')
> and in my instead of trigger i want to fill the nulls with the proper
> number so in my instead of trigger i say
> if (field2 is null)
> begin
> set field2 = (select rightnumber from mastertable where name = field2)
> end
> but it has to do it for each row
>|||MGFoster wrote:
> --BEGIN PGP SIGNED MESSAGE--
> Hash: SHA1
> Stop thinking procedure and start thinking sets. If there are 3 rows in
> the inserted set and 2 have NULL in some column (as your example shows)
> you can do an UPDATE like this:
> UPDATE original_table
> SET column_name = (select rightnumber
> from mastertable m inner join inserted i
> on m.<join cols> = i.<join cols> )
> WHERE EXISTS (SELECT * FROM inserted
> WHERE column_name IS NULL
> AND inserted.ID = original_table.ID)
> The "WHERE column_name IS NULL" in the UPDATE's WHERE clause subquery
> will identify the rows in original_table that have the 'column_name' set
> to the "rightnumber."
> The <join cols> have to be a column, or columns, that uniquely identify
> the rows in inserted that relate to rows in mastertable, so the
> "rightnumber" can be retrieved. I would have to see the design of
> mastertable and original_table to determine which columns those would
> be. You could even do w/o the inserted set and just use something in
> the mastertable that identifies which row in mastertable has the correct
> data that is to be placed in the original_table. IOW, if you had a
> Default value in mastertable that always goes in that column - data in
> mastertable looks like this:
> column_ rightnumber
> -- --
> Price 25
> The SET subquery would look like this:
> SET Price = (select rightnumber
> from mastertable
> where column_ = 'Price')
> NB: By now you should realize that you can create a DEFAULT on the
> column(s) in original_table instead of using a trigger like the above.
> E.g.: CREATE TABLE T (col_1 int, col_a char(2) default ('zz'))
> insert into t (col_1) values (2)
> select * from t
> col_1 col_a
> -- --
> 2 zz
I can do that sometimes but if i want to set something like an id number
based on a column in another table that i cannot join on i can't do it
with a set
unless there is a command like
select * into #inserted from inserted
update #inserted
set keyfield = getNextValueFromTable()
insert into myTable select * from #inserted
but I cannot figure out how to get the getNextValueFromTable()
procedure since i cannot call stored procedures that way and UDF's
cannot access my table values
I am only doing this the way i'm doing it to maintain compatibility with
a program. If i was to design this myself I'd be doing it with
constraints, foreign keys, identities, etc|||Chris M wrote:
> MGFoster wrote:
>
< SNIP >
> I can do that sometimes[,] but if i want to set something like an id numbe
r
> based on a column in another table that i cannot join on i can't do it
> with a set
>
<SNIP >
--BEGIN PGP SIGNED MESSAGE--
Hash: SHA1
How can you know which "id number[...]in another table" to use if you
cannot join on it? That implies that there is "some other" way of
determining the relationship between one table and another; and, that
that relationship is defined outside the database. This goes against
RDB design principles.
If the "id number [is] based on a column in another table" that means
there is a relationship between the 2 tables. If there is a
relationship between the 2 tables you can join them.
So, what's going on there? ;-)
--
MGFoster:::mgf00 <at> earthlink <decimal-point> net
Oakland, CA (USA)
--BEGIN PGP SIGNATURE--
Version: PGP for Personal Privacy 5.0
Charset: noconv
iQA/ AwUBQmgyZYechKqOuFEgEQJd5QCfaDO4xXjYNt2S
oYbvwG9acyT4ncAAoPyO
BL03rAJrHegoe1ktC8L/pRBI
=8GJu
--END PGP SIGNATURE--|||What do you mean..
<snip> ...that i cannot join on ...</snip>
Why Not?
If the objective here is to insert some records into MyTable, then just do
that in the trigger
Insert MyTable
Select <Stuff>
From inserted
The <Stuff> above needs t oeb written as a set-based expression, (Set of
expressions), such that the values will be appropriate... But there's no way
for us to guess what that is until you tell us whjat you are trying to do
with getNextValueFromTable()...
again, if all you are tyrying to do is set the value based on the value in
the inserted table, then, as an example...
Insert MyTable
Select <OtherColumns>,
Case newField
When <ValueA> Then <outValueA>
When <ValueB> Then <outValueB>
When <ValueC> Then <outValueC>
When <ValueD> Then <outValueD>
Else <OutVAlueDefault> End
From inserted|||MGFoster wrote:
> Chris M wrote:
>
> < SNIP >
>
> <SNIP >
> --BEGIN PGP SIGNED MESSAGE--
> Hash: SHA1
> How can you know which "id number[...]in another table" to use if you
> cannot join on it? That implies that there is "some other" way of
> determining the relationship between one table and another; and, that
> that relationship is defined outside the database. This goes against
> RDB design principles.
> If the "id number [is] based on a column in another table" that means
> there is a relationship between the 2 tables. If there is a
> relationship between the 2 tables you can join them.
> So, what's going on there? ;-)
A table called generators
create table generators (
generator_name varchar(50),
generator_lastid integer
)
in my table say myTable if i want to get the next ID from generators i
have to
select generator_lastid from generators where generator_name =
'gen_id_mytable)
so i do not know how i can join on that, and I'm sure this does violate
some rule, but its meant to simulate the sequence/generator object of
oracle/interbase/firebird|||> if i do an insert with 5 rows does inserted have 5 rows in it?
Yes if the insert/update was done as a single statement.

> if htats the case how do you check field values for every row
> I was using
> if (select newfield from #inserted) = this
> begin
> update #inserted set newfield = that
> end
What is "this"? Is the idea to override the values being inserted/updated in
the
trigger? If that is the case, then you need an InsteadOf trigger not an Afte
r
trigger.

> but that isnt going to work if inserted contains all 5 rows, i thought
> inserted only had the current row and it passed through the instead of tri
gger
> 5 times once for each row. if thats not the case how do you do something like[/co
lor]
No. That is not the case. Each *statement* fires the trigger once (ignoring
cascades for the moment). Thus, imagine the statement:
Insert Table(F1...Fn)
Select F1...FN
From Table
That might insert 1000 records with that once statement. That statement will
fire the trigger once and populate the "inserted" table with 1000 records. I
f it
is an update, then you will get 1000 records in the "inserted" table and 100
0
records in the "deleted" table.
> for each newfield in #inserted do
> if newfield is this
> set it to this.
Can't do that with an After trigger. You need to do that with an InsteadOf
trigger.

> for example
> say i have an insert with three fields
> category, categoryid, name
> and the 3 rows in my insert are
> ('Standard', 1, 'Toys')
> ('NonStandard, null, 'Games')
> ('Misc', null, 'Puzzles')
> and in my instead of trigger i want to fill the nulls with the proper numb
er
> so in my instead of trigger i say
> if (field2 is null)
> begin
> set field2 = (select rightnumber from mastertable where name = field2)
> end
Create Table Stuff
(
Category VarChar(50) Not Null
, SomeNumber Int Null
, Description VarChar(50) Not Null
)
Create Table SomeOtherTable
(
SingleValue Int
)
Insert SomeOtherTable(SingleValue) Values(99)
Create Trigger trigStuff On dbo.Stuff
Instead Of Insert
As
Begin
Insert Stuff(Category, SomeNumber, Description)
Select Category
, (Select SingleValue From SomeOtherTable)
, Description
From inserted As I
End
Insert Stuff(Category, SomeNumber, Description) Values('Standard', 1, 'Toys'
)
Insert Stuff(Category, SomeNumber, Description) Values('NonStandard', Null,
'Games')
Insert Stuff(Category, SomeNumber, Description) Values('Misc', Null, 'Puzzle
s')
Select * From Stuff
HTH
Thomas|||Chris M wrote:
> MGFoster wrote:
>
>
> A table called generators
> create table generators (
> generator_name varchar(50),
> generator_lastid integer
> )
>
> in my table say myTable if i want to get the next ID from generators i
> have to
> select generator_lastid from generators where generator_name =
> 'gen_id_mytable)
> so i do not know how i can join on that, and I'm sure this does violate
> some rule, but its meant to simulate the sequence/generator object of
> oracle/interbase/firebird
--BEGIN PGP SIGNED MESSAGE--
Hash: SHA1
Ah... In that case you can just insert that value "generator_lastid"
into the NULL columns in the original table like this (this is in the
trigger):
UPDATE original_table
SET null_column = (SELECT generator_nextid FROM generators
WHERE generator_name = null_column_name)
WHERE id IN (SELECT id FROM inserted WHERE null_column IS NULL)
Substitute correct table/column names where appropriate.
Each row would get the same number. This won't work if you want
incrementing numbers in each row that had the NULL valued column. There
is no way to increment the nextid for the next call. A function can't
be used 'cuz ya can't run an UPDATE inside a function (to increment the
nextid). A procedure can't be used 'cuz ya can't use a procedure as a
recordsource, like ya can w/ a function.
Looks like (ugh!) a WHILE loop would have to be used to cycle thru all
the inserted rows that had NULL values in the column.
@.count = (select count(*) from inserted where column_name is null)
while @.count > 0 begin
-- do the update & generate new nextid
@.count = @.count - 1
end
Quite a problem.
--
MGFoster:::mgf00 <at> earthlink <decimal-point> net
Oakland, CA (USA)
--BEGIN PGP SIGNATURE--
Version: PGP for Personal Privacy 5.0
Charset: noconv
iQA/ AwUBQmhsb4echKqOuFEgEQL6JwCguTf9eD2kFh7F
fZDJAtnUhIKvKWwAniqR
xD1fe46JZ8B2jXX11NQRQmtJ
=xD8y
--END PGP SIGNATURE--

Insert/update/delete Transaction

Hi,

I have an unbound DataGridView and I have load it with a set of records from a Data base.

I modify existing rows, delete rows and add new rows to DataGridView control. I have to send a new modified dataset back to the data base.

Please any suggestions how to solve the problem?

Thanks in advance

George

Hi George,

I think you'll have more success posting your question on the Visual Studio forums - this is the T-SQL forum which is primarily used for back-end SQL questions, rather than user interface coding problems like DataGridViews.

Hope that helps :)

Menthos
|||Thanks :)sql

Friday, March 23, 2012

Insert using From

I am trying to insert rows into a table using
insert into table_name(columns)
from table_name
and I get Subquery returned more than 1 valueCould you post your sql-statement?|||If you are getting a "sub-query returned more than one variable" error message, there is probably a logic error in your query. If you post the query, I'd bet that one of us can help you fix it.

-PatP

Insert unique rows in temp table

i have temp table name "#TempResult" with column names Memberid,Month,Year. Consider this temp table alredy has some rows from previuos query. I have one more table name "Rebate" which also has columns MemberID,Month, Year and some more columns. Now i wanted to insert rows from "Rebate" Table into Temp Table where MemberID.Month and Year DOES NOT exist in Temp table.

MemberID + Month + Year should ne unique in Temp table

I don't think what you are doing is valid because a local temp table scope is very limited, but if it valid it will be covered in the link below by one of the best minds in T-SQL. Hope this helps.

http://www.awprofessional.com/articles/article.asp?p=25288&seqNum=4&rl=1

Insert two rows into two tables at the same time from a formview

I have a formview that uses a predefined dataset based on a cross table query. When the formview is in insert mode I need to insert the data into two seperate tables. Essentially I have tblPerson and tblAddress and my formview is capturing username, password, name, address line1, address line 2, etc. I presume I need to use a stored procedure to insert a row into tblPerson and then insert a row intp tblAddress. This is easy enough to do but the tables use RI and tblPerson has an imcremental primary key which needs to be innserted into a foreign key field in my address row. How do I do this? I'm using SQL Server.

If you're passing all of the information into your Stored Procedure, then can't you simply retrieve the last ID inserted via SCOPE_IDENTITY? This assumes your using an identity column within tblPerson.

|||

Thanks for your reply. I'm not familiar with this command because I'm from a MySQL background. So I essentially I use the following

INSERT INTO tblPerson (name, username, password) VALUES (@.name, @.username, @.password);

INSERT INTO tblAddress (FK_tblPerson, address1, address2) VALUES (scope_identity(),@.address1, @.address2);

|||

Yes, except that I'd declare a variable and place the results of SCOPE_IDENTITY into it. Then I'd use that variable for my next INSERT.

Insert Trigger on every row

Hi,
I want to insert some hundred rows into a table, an
instead of trigger should be executed for every insert.
up to now only the last insert executes the trigger.Steffen
I am not sure what are you trying to do?
Trigger executes a statement against the table .
Just a guess
INSERT INTO Table SELECT * FROM inserted
Note: Number of columns in target and destination tables should be matched.
"Steffen Steinert de Lima" <steffen_steinert_de_lima@.hotmail.com> wrote in
message news:059b01c3d368$9646fcc0$a101280a@.phx.gbl...
> Hi,
> I want to insert some hundred rows into a table, an
> instead of trigger should be executed for every insert.
> up to now only the last insert executes the trigger.|||Hi, here is the trigger
the insert is a normal insert like
select * into stoerung_2day from ...
when i insert the rows from ms-access via odbc the
trigger is executed for every inserted row, in sqlserver
it's only executed for the last row.
**************************************************
CREATE TRIGGER stoerung_more_day ON [dbo].
[stoerung_2day]
instead of INSERT, update
AS
declare @.cnt integer
declare @.id integer
declare @.day_beginn as datetime
declare @.day_ende as datetime
declare @.gueltig as datetime
select @.id = [id],
@.day_beginn = beginn,
@.day_ende = ende
from inserted
set @.cnt = day(@.day_beginn)
set @.gueltig = @.day_beginn
while @.cnt <= day(@.day_ende)
begin
insert into stoerung_2day values (@.id, @.day_beginn,
@.day_ende, @.gueltig)
set @.cnt = @.cnt +1
set @.gueltig = @.gueltig + 1
end
********************************************************
>--Original Message--
>Steffen
>I am not sure what are you trying to do?
>Trigger executes a statement against the table .
>Just a guess
>INSERT INTO Table SELECT * FROM inserted
>Note: Number of columns in target and destination tables
should be matched.
>
>"Steffen Steinert de Lima"
<steffen_steinert_de_lima@.hotmail.com> wrote in
>message news:059b01c3d368$9646fcc0$a101280a@.phx.gbl...
>> Hi,
>> I want to insert some hundred rows into a table, an
>> instead of trigger should be executed for every insert.
>> up to now only the last insert executes the trigger.
>
>.
>|||Steffen
Have you read what BOL says?
Trigger executes a statement against the table
In your case you have multi-insert so you have to cary out in inserted
table .
INSERT INTO Table SELECT * FROM inserted
What is goal of using these statements?
> set @.cnt = @.cnt +1
> set @.gueltig = @.gueltig + 1
"Steffen Steinert de Lima" <steffen_steinert_de_lima@.hotmail.com> wrote in
message news:021601c3d36e$653596e0$a001280a@.phx.gbl...
>
> Hi, here is the trigger
> the insert is a normal insert like
> select * into stoerung_2day from ...
> when i insert the rows from ms-access via odbc the
> trigger is executed for every inserted row, in sqlserver
> it's only executed for the last row.
> **************************************************
> CREATE TRIGGER stoerung_more_day ON [dbo].
> [stoerung_2day]
> instead of INSERT, update
> AS
> declare @.cnt integer
> declare @.id integer
> declare @.day_beginn as datetime
> declare @.day_ende as datetime
> declare @.gueltig as datetime
> select @.id = [id],
> @.day_beginn = beginn,
> @.day_ende = ende
> from inserted
> set @.cnt = day(@.day_beginn)
> set @.gueltig = @.day_beginn
> while @.cnt <= day(@.day_ende)
> begin
> insert into stoerung_2day values (@.id, @.day_beginn,
> @.day_ende, @.gueltig)
> set @.cnt = @.cnt +1
> set @.gueltig = @.gueltig + 1
> end
> ********************************************************
> >--Original Message--
> >Steffen
> >I am not sure what are you trying to do?
> >Trigger executes a statement against the table .
> >
> >Just a guess
> >INSERT INTO Table SELECT * FROM inserted
> >
> >Note: Number of columns in target and destination tables
> should be matched.
> >
> >
> >"Steffen Steinert de Lima"
> <steffen_steinert_de_lima@.hotmail.com> wrote in
> >message news:059b01c3d368$9646fcc0$a101280a@.phx.gbl...
> >> Hi,
> >>
> >> I want to insert some hundred rows into a table, an
> >> instead of trigger should be executed for every insert.
> >> up to now only the last insert executes the trigger.
> >
> >
> >.
> >|||>--Original Message--
>Steffen
>Have you read what BOL says?
where ?
>Trigger executes a statement against the table
>In your case you have multi-insert so you have to cary
out in inserted
>table .
>INSERT INTO Table SELECT * FROM inserted
>What is goal of using these statements?
>> set @.cnt = @.cnt +1
>> set @.gueltig = @.gueltig + 1
the sense of the whole trigger is to multiply the rows if
the from-date and the until-date in the record are not
the same. so i create a new record for every day of the
period.
example: id date_from date_until gueltig cnt
1 05-01-2004 07-01-2004
result: 1 05-01-2004 07-01-2004 05-01-2004 1
1 05-01-2004 07-01-2004 06-01-2004 2
1 05-01-2004 07-01-2004 07-01-2004 3
for inserting one record the trigger works well. perhaps
there's missing a commit after every insert ?
>"Steffen Steinert de Lima"
<steffen_steinert_de_lima@.hotmail.com> wrote in
>message news:021601c3d36e$653596e0$a001280a@.phx.gbl...
>>
>> Hi, here is the trigger
>> the insert is a normal insert like
>> select * into stoerung_2day from ...
>> when i insert the rows from ms-access via odbc the
>> trigger is executed for every inserted row, in
sqlserver
>> it's only executed for the last row.
>> **************************************************
>> CREATE TRIGGER stoerung_more_day ON [dbo].
>> [stoerung_2day]
>> instead of INSERT, update
>> AS
>> declare @.cnt integer
>> declare @.id integer
>> declare @.day_beginn as datetime
>> declare @.day_ende as datetime
>> declare @.gueltig as datetime
>> select @.id = [id],
>> @.day_beginn = beginn,
>> @.day_ende = ende
>> from inserted
>> set @.cnt = day(@.day_beginn)
>> set @.gueltig = @.day_beginn
>> while @.cnt <= day(@.day_ende)
>> begin
>> insert into stoerung_2day values (@.id, @.day_beginn,
>> @.day_ende, @.gueltig)
>> set @.cnt = @.cnt +1
>> set @.gueltig = @.gueltig + 1
>> end
********************************************************
>> >--Original Message--
>> >Steffen
>> >I am not sure what are you trying to do?
>> >Trigger executes a statement against the table .
>> >
>> >Just a guess
>> >INSERT INTO Table SELECT * FROM inserted
>> >
>> >Note: Number of columns in target and destination
tables
>> should be matched.
>> >
>> >
>> >"Steffen Steinert de Lima"
>> <steffen_steinert_de_lima@.hotmail.com> wrote in
>> >message news:059b01c3d368$9646fcc0$a101280a@.phx.gbl...
>> >> Hi,
>> >>
>> >> I want to insert some hundred rows into a table, an
>> >> instead of trigger should be executed for every
insert.
>> >> up to now only the last insert executes the trigger.
>> >
>> >
>> >.
>> >
>
>.
>|||Unlike Oracle, SQL-server does not have a trigger which
triggers once for every row. The trigger only 'fires' once for
the complete statement.
So you have to revert to solutions allready offered in the
other anwsers.
Have a nice 2004,
Ben Brugman
"Steffen Steinert de Lima" <steffen_steinert_de_lima@.hotmail.com> wrote in
message news:059b01c3d368$9646fcc0$a101280a@.phx.gbl...
> Hi,
> I want to insert some hundred rows into a table, an
> instead of trigger should be executed for every insert.
> up to now only the last insert executes the trigger.

Wednesday, March 21, 2012

Insert Trigger and Bulk Insert

I am using Bulk Insert to insert multiple rows into a table (Invoice_Lines_Temp). I need to update/insert rows in another table (Invoice_Lines) as these rows are inserted into Invoice_Lines_Temp. As I understand, the trigger is only fired once for the insert so only one row is affected in Invoice_Lines, and this is what I'm seeing.

How would someone modify this trigger to update/insert the Invoice_Line table for each record inserted into Invoice_Line_Temp?

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

go

-- =============================================

-- Author: <Author,,Name>

-- Create date: <Create Date,,>

-- Description: <Description,,>

-- =============================================

ALTER TRIGGER [dbo].[Invoice_Line_Temp_Insert]

on [dbo].[Invoice_Line_Temp]

for Insert

As

Declare @.Transaction_ID int,

@.Line_Number int,

@.Item_Desc varchar(32),

@.Invoice_Date datetime,

@.Group_Number int,

@.Item_Code varchar(8),

@.Quantity_Sold decimal,

@.Section_Number int,

@.LastUpdate datetime

Select @.Transaction_ID = inserted.Transaction_ID,

@.Line_Number = inserted.Line_Number,

@.Item_Desc = Inserted.Item_Desc,

@.Invoice_Date = inserted.Invoice_Date,

@.Group_Number = inserted.Group_Number,

@.Item_Code = inserted.Item_Code,

@.Quantity_Sold = inserted.Quantity_Sold,

@.Section_Number = inserted.Section_Number,

@.LastUpdate = inserted.LastUpdate

from inserted

IF Exists

(Select dbo.invoice_line.transaction_id, dbo.invoice_line.line_number

from dbo.invoice_line

where dbo.invoice_line.transaction_id = @.Transaction_id

and dbo.invoice_line.Line_Number = @.Line_Number)

Begin

update dbo.invoice_line

set Item_Desc = @.Item_Desc,

Invoice_Date = @.Invoice_Date,

Group_Number = @.Group_Number,

Item_Code = @.Item_Code,

Quantity_Sold = @.Quantity_Sold,

Section_Number = @.Section_Number,

LastUpdate = @.LastUpdate

where dbo.invoice_line.transaction_id = @.Transaction_id

and dbo.invoice_line.Line_Number = @.Line_Number

end

ELSE

Begin

INSERT INTO dbo.Invoice_Line

(InvoiceLineId,Transaction_ID,Line_Number,Item_Desc,Invoice_Date,

Group_Number,Item_Code,Quantity_Sold,Section_Number,LastUpdate)

VALUES

(newid(),@.Transaction_ID,@.Line_Number,@.Item_Desc,@.Invoice_Date,

@.Group_Number,@.Item_Code,@.Quantity_Sold,@.Section_Number,@.LastUpdate)

end

Try this:

Code Snippet

ALTER TRIGGER [dbo].[Invoice_Line_Temp_Insert]

on [dbo].[Invoice_Line_Temp]

for Insert

As

BEGIN

UPDATE il

SET Item_Desc = i.Item_Desc,

Invoice_Date = i.Invoice_Date,

Group_Number = i.Group_Number,

Item_Code = i.Item_Code,

Quantity_Sold = i.Quantity_Sold,

Section_Number = i.Section_Number,

LastUpdate = i.LastUpdate

FROM dbo.invoice_line il

INNER JOIN inserted

ON il.transaction_id = i.Transaction_id

AND il.Line_Number = i.Line_Number

INSERT INTO dbo.Invoice_Line

(InvoiceLineId,Transaction_ID,Line_Number,Item_Desc,Invoice_Date,

Group_Number,Item_Code,Quantity_Sold,Section_Number,LastUpdate)

SELECT newid(), i.Transaction_id, i.Line_number, i.Item_Desc, i.Invoice_Date,

i.GroupNumber, i.Item_Code, i.Quantity_Sold, i.Section_Number, i.LastUpdate

FROM inserted

WHERE NOT EXISTS

( SELECT * FROM dbo.Invoice_Line il

WHERE il.transaction_id = i.Transaction_id

AND il.Line_Number = i.Line_Number)

END

|||Worked great! More elegant as well. thanks...

Insert transaction batch size

I have insert statements that inserts 1.7 million rows from one server to
another. Half way through the insert, the connection gets lost. I am thinking
that because of the batch size the connection gets cut-off. How can I
implement a commit in T-SQL after say every 500 rows inserted ?
Thanks.
DXC,
You will have to manage this yourself in a stored procedure or sql batch.
Have you considered DTS - you can set the commit batch size there.
-- Bill
"DXC" <DXC@.discussions.microsoft.com> wrote in message
news:B8409B51-1A56-4CB5-946B-234102EDFA27@.microsoft.com...
>I have insert statements that inserts 1.7 million rows from one server to
> another. Half way through the insert, the connection gets lost. I am
> thinking
> that because of the batch size the connection gets cut-off. How can I
> implement a commit in T-SQL after say every 500 rows inserted ?
> Thanks.

Insert transaction batch size

I have insert statements that inserts 1.7 million rows from one server to
another. Half way through the insert, the connection gets lost. I am thinkin
g
that because of the batch size the connection gets cut-off. How can I
implement a commit in T-SQL after say every 500 rows inserted ?
Thanks.DXC,
You will have to manage this yourself in a stored procedure or sql batch.
Have you considered DTS - you can set the commit batch size there.
-- Bill
"DXC" <DXC@.discussions.microsoft.com> wrote in message
news:B8409B51-1A56-4CB5-946B-234102EDFA27@.microsoft.com...
>I have insert statements that inserts 1.7 million rows from one server to
> another. Half way through the insert, the connection gets lost. I am
> thinking
> that because of the batch size the connection gets cut-off. How can I
> implement a commit in T-SQL after say every 500 rows inserted ?
> Thanks.

Insert to a table

Can I do an insert from table A to table B only columns that are in A but not
in B and changing them before insert? I want the primary key of rows in A
that don't exist in B to be inserted in B, but I want to flag them in a
couple of other columns. I see that I can either use an Insert query with
select statement where all the columns are inserted as is or Insert...Values
where all are manual values. Is there a statement that can be a combination
of these two?
Thanks
You should be able to formulate an INSERT SELECT statement to do what you
want:
INSERT INTO TableB (col1, col2, col3, col4, ...)
SELECT colA, 'some value', 1234, colB, ...
FROM TableA
WHERE ...
David Portas
SQL Server MVP
|||On Mon, 13 Dec 2004 15:01:01 -0800, Niles wrote:

>Can I do an insert from table A to table B only columns that are in A but not
>in B and changing them before insert? I want the primary key of rows in A
>that don't exist in B to be inserted in B, but I want to flag them in a
>couple of other columns. I see that I can either use an Insert query with
>select statement where all the columns are inserted as is or Insert...Values
>where all are manual values. Is there a statement that can be a combination
>of these two?
>Thanks
Hi Niles,
You mean something like this?
INSERT INTO TableB (KeyColumn, OtherColumn, ThirdColumn)
SELECT KeyColumn, OtherColumn, 'Literal value'
FROM TableA AS a
WHERE NOT EXISTS
(SELECT *
FROM TableB AS b
WHERE b.KeyColumn = a.KeyColumn)
or alternatively:
INSERT INTO TableB (KeyColumn, OtherColumn, ThirdColumn)
SELECT a.KeyColumn, a.OtherColumn, 'Literal value'
FROM TableA AS a
LEFT OUTER JOIN TableB AS b
ON b.KeyColumn = a.KeyColumn
WHERE b.KeyColumn IS NULL
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)

Insert to a table

Can I do an insert from table A to table B only columns that are in A but not
in B and changing them before insert? I want the primary key of rows in A
that don't exist in B to be inserted in B, but I want to flag them in a
couple of other columns. I see that I can either use an Insert query with
select statement where all the columns are inserted as is or Insert...Values
where all are manual values. Is there a statement that can be a combination
of these two?
ThanksYou should be able to formulate an INSERT SELECT statement to do what you
want:
INSERT INTO TableB (col1, col2, col3, col4, ...)
SELECT colA, 'some value', 1234, colB, ...
FROM TableA
WHERE ...
--
David Portas
SQL Server MVP
--|||On Mon, 13 Dec 2004 15:01:01 -0800, Niles wrote:
>Can I do an insert from table A to table B only columns that are in A but not
>in B and changing them before insert? I want the primary key of rows in A
>that don't exist in B to be inserted in B, but I want to flag them in a
>couple of other columns. I see that I can either use an Insert query with
>select statement where all the columns are inserted as is or Insert...Values
>where all are manual values. Is there a statement that can be a combination
>of these two?
>Thanks
Hi Niles,
You mean something like this?
INSERT INTO TableB (KeyColumn, OtherColumn, ThirdColumn)
SELECT KeyColumn, OtherColumn, 'Literal value'
FROM TableA AS a
WHERE NOT EXISTS
(SELECT *
FROM TableB AS b
WHERE b.KeyColumn = a.KeyColumn)
or alternatively:
INSERT INTO TableB (KeyColumn, OtherColumn, ThirdColumn)
SELECT a.KeyColumn, a.OtherColumn, 'Literal value'
FROM TableA AS a
LEFT OUTER JOIN TableB AS b
ON b.KeyColumn = a.KeyColumn
WHERE b.KeyColumn IS NULL
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

Monday, March 19, 2012

Insert Table Lock - Various connections inserting into one table

I have three connections from oracle DBs which all insert into 1 SQL
Server 2000 table. About 1 million rows in all. The problem is only one
connection is inserting at one time... then the second... then
third.... The first connection obtains a table lock causing other
connections to wait until it completes...should'nt they run
simultaneously'...My DBA recently changed the from FULL to Simple
recovery model... does that has anything to do with how insert table
locks are being handled' If I was on simple recovery model....
would I be able to insert into one table from three different
connections or SQL statements?Hi Zomer
The recovery model should not affect the locking.
How are you determining that a table lock is being acquired?
Are the connections doing more than inserts? Are they starting an explicit
transaction? (Look for BEGIN TRAN)
What isolation level are you in? Have you enabled implicit transactions?
(Run DBCC USEROPTIONS on the connection)
Have you disallowed page and row locks (check indexproperty function)
HTH
Kalen Delaney, SQL Server MVP
www.solidqualitylearning.com
"zomer" <noneee@.gmail.com> wrote in message
news:1146586395.557732.192510@.u72g2000cwu.googlegroups.com...
>I have three connections from oracle DBs which all insert into 1 SQL
> Server 2000 table. About 1 million rows in all. The problem is only one
> connection is inserting at one time... then the second... then
> third.... The first connection obtains a table lock causing other
> connections to wait until it completes...should'nt they run
> simultaneously'...My DBA recently changed the from FULL to Simple
> recovery model... does that has anything to do with how insert table
> locks are being handled' If I was on simple recovery model....
> would I be able to insert into one table from three different
> connections or SQL statements?
>|||I run sp_lock to find out if a table lock was acquired or not. I am
doing it in DTS and I can see one connections getting data while others
are waiting for it to get done (due to table lock)
How do I check for Transaction isolation level? When I run DBCC
USEROPTIONS I dont see any informaton about transactions...
No I have not disallowed page and row locks...
A few days ago this DB was changed to simple from full recovery model
by DBA|||If DBCC USEROPTIONS doesn't mention transaction isolation, it means you
haven't changed it from the default, but you have to be running it from the
connection doing the insert.
Did you run sp_indexoption to verify that page and row locks are allowed?
Can you post the specific information from sp_lock that is showing the table
lock?
HTH
Kalen Delaney, SQL Server MVP
www.solidqualitylearning.com
"zomer" <noneee@.gmail.com> wrote in message
news:1146590297.747832.125830@.i39g2000cwa.googlegroups.com...
>I run sp_lock to find out if a table lock was acquired or not. I am
> doing it in DTS and I can see one connections getting data while others
> are waiting for it to get done (due to table lock)
> How do I check for Transaction isolation level? When I run DBCC
> USEROPTIONS I dont see any informaton about transactions...
> No I have not disallowed page and row locks...
> A few days ago this DB was changed to simple from full recovery model
> by DBA
>

insert statement script/stored proc.

I have a table that has 3 columns that I need to split up the data in
each column and insert into another table as rows.
As well for each record inserted the Status is set to "O".
I am thinking I stored procedure would be the way to go? But trying to
determine the best way to go about this.
Below is an example of the table structures.
I have 2 options, delete all the data from table2 and do a bunch of
inserts, or perform updates?
I am assuming the first would be better but having trouble with the sql
statement.
Any ideas?
table1
ID Name1 Name2 CITY
500 John Jeff TO
501 Sheila Rose TO
502 Barb Jen TO
503 Tom Jerry TO
504 Alan Scott TO
505 Steve John TO
506 Pat Cathy TO
table2
ID Name Status
500 John O
500 Jeff O
501 Sheila O
501 Rose O
502 Barb O
502 Jen O
503 Tom O
503 Jerry O
504 Alan O
504 Scott O
505 Steve O
505 John O
506 Pat O
506 Cathy O
One way is to use an UNION like:
SELECT id, name1 AS "Name" FROM tbl
UNION
SELECT id, name2 AS "Name" FROM tbl
Another option is to use a CASE expression like:
SELECT id, CASE seq WHEN 1 THEN name1 ELSE name 2 END
FROM tbl, ( SELECT 1 UNION SELECT 2 ) D ( seq )
Make sure you have a composite key on ( id, name ) to prevent potential
duplication of names.
Anith
|||<pisquem@.hotmail.com> wrote in message
news:1160507284.442954.181820@.i3g2000cwc.googlegro ups.com...
>I have a table that has 3 columns that I need to split up the data in
> each column and insert into another table as rows.
> As well for each record inserted the Status is set to "O".
> I am thinking I stored procedure would be the way to go? But trying to
> determine the best way to go about this.
> Below is an example of the table structures.
> I have 2 options, delete all the data from table2 and do a bunch of
> inserts, or perform updates?
> I am assuming the first would be better but having trouble with the sql
> statement.
> Any ideas?
>
> table1
> ID Name1 Name2 CITY
> 500 John Jeff TO
> 501 Sheila Rose TO
> 502 Barb Jen TO
> 503 Tom Jerry TO
> 504 Alan Scott TO
> 505 Steve John TO
> 506 Pat Cathy TO
>
> table2
> ID Name Status
> 500 John O
> 500 Jeff O
> 501 Sheila O
> 501 Rose O
> 502 Barb O
> 502 Jen O
> 503 Tom O
> 503 Jerry O
> 504 Alan O
> 504 Scott O
> 505 Steve O
> 505 John O
> 506 Pat O
> 506 Cathy O
>
I might not be following, but this should do what you wish.
INSERT table2 (ID, Name, Status)
SELECT ID, Name1, 'O'
FROM Table1
UNION ALL
SELECT ID, Name2, 'O'
FROM Table1
Rick Sawtell
|||Thanks for the posts.
Which is the most effective and efficient way?
Rick Sawtell wrote:
> <pisquem@.hotmail.com> wrote in message
> news:1160507284.442954.181820@.i3g2000cwc.googlegro ups.com...
> I might not be following, but this should do what you wish.
> INSERT table2 (ID, Name, Status)
> SELECT ID, Name1, 'O'
> FROM Table1
> UNION ALL
> SELECT ID, Name2, 'O'
> FROM Table1
>
> Rick Sawtell
|||Darn, I forgot to include something...
In the second table I need to have another column inserted with the
value of either 001 or 002 depending on if its Name1 being inserted or
Name2. So the table should be outputed as follows.
ID Name Code Status
500 John 001 O
500 Jeff 002 O
501 Sheila 001 O
501 Rose 002 O
Any ideas?
pisq...@.hotmail.com wrote:[vbcol=seagreen]
> Thanks for the posts.
> Which is the most effective and efficient way?
>
> Rick Sawtell wrote: