Showing posts with label procedure. Show all posts
Showing posts with label procedure. Show all posts

Monday, March 26, 2012

Multiple inserts into one table using a stored procedure

Hi,

I am trying to create a stored procedure which will allow multiple inserts to happen on one table.

I cant find any information on this.

Please can someone help?.

Thanks

JagK

Hi JagK,

You would call multiple times to stored procedure.

Good Coding!

Javier Luna
http://guydotnetxmlwebservices.blogspot.com/

sql

Multiple Inserts in the Same Stored Procedure

Hey,
I have a project that I have been working on and I need to insert a
record into multiple tables and I if any one of the inserts fails I
need to rollback all of the previous inserts that were done. To
illustrate, I have ten tables that need to have a record inserted into
them and if it errors out on table six, then I want to rollback the
previous five inserts. I'd appreciate any advice I can get. Thanks.bradley.d.walker@.gmail.com wrote:
> Hey,
> I have a project that I have been working on and I need to insert a
> record into multiple tables and I if any one of the inserts fails I
> need to rollback all of the previous inserts that were done. To
> illustrate, I have ten tables that need to have a record inserted into
> them and if it errors out on table six, then I want to rollback the
> previous five inserts. I'd appreciate any advice I can get. Thanks.
>
BEGIN TRANSACTION
INSERT Table1 .....
IF @.@.ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN
END
INSERT Table2 .....
IF @.@.ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN
END
INSERT Table3 .....
IF @.@.ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN
END
INSERT Table4 .....
IF @.@.ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN
END
...
...
...
...
...
...
COMMIT TRANSACTION|||With SQL 2000 -SQL 2005 is a bit 'simplier' in manifestation - but the idea
is the same.
BEGIN TRANSACTION
INSERT INTO into table1 (ColList) VALUES (ValList)
IF @.ERROR <> 0
BEGIN
ROLLBACK
RETURN
END
INSERT INTO into table2 (ColList) VALUES (ValList)
IF @.ERROR <> 0
BEGIN
ROLLBACK
RETURN
END
{etc.}
COMMIT TRANSACTION
RETURN
There are variations to the idea, using GOTO to the end of the sproc and ROL
LBACK from there.
--
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another certification Exam
<bradley.d.walker@.gmail.com> wrote in message news:1151077294.100001.43410@.g10g2000cwb.goog
legroups.com...
> Hey,
>
> I have a project that I have been working on and I need to insert a
> record into multiple tables and I if any one of the inserts fails I
> need to rollback all of the previous inserts that were done. To
> illustrate, I have ten tables that need to have a record inserted into
> them and if it errors out on table six, then I want to rollback the
> previous five inserts. I'd appreciate any advice I can get. Thanks.
>|||To add to the other responses, consider adding SET XACT_ABORT ON to the
beginning of your proc. This will ensure a transaction rollback occurs in
the case of a client-initiated attention event (e.g. query timeout or
cancel).
Hope this helps.
Dan Guzman
SQL Server MVP
<bradley.d.walker@.gmail.com> wrote in message
news:1151077294.100001.43410@.g10g2000cwb.googlegroups.com...
> Hey,
> I have a project that I have been working on and I need to insert a
> record into multiple tables and I if any one of the inserts fails I
> need to rollback all of the previous inserts that were done. To
> illustrate, I have ten tables that need to have a record inserted into
> them and if it errors out on table six, then I want to rollback the
> previous five inserts. I'd appreciate any advice I can get. Thanks.
>|||>> I have a project that I have been working on and I need to insert a record [si
c] into multiple tables and I if any one of the inserts fails Ineed to rollb
ack all of the previous inserts that were done. <<
Easy enough; set up a series of INSERT INTO's in a single transaction,
trap each insertion's error and do a ROLLBACK and return if you have a
failure. Do not commit until the end of the whole thing.
The scope of transactions in T-SQL is independent of the block
structure of the language. Think of a "transaction guy" with a bucket
of data looking at a house. The house pumps data into his bucket. He
does not care what is happening inside; he is waiting to see a COMMIT
or ROLLBACK flag come out of the window of the house. At that point,
he either throws the data out or throws it in the database.
But a better question why do you want to store the same data in
multiple tables? The major reason we moved from files to RDBMS was to
get rid of redundancy -- the mantra is "one fact, one time, one way,
one place!" and not "Let's make ten copies and try to keep them all the
same!" Instead of making ten copies of a mag tape with the same data,
we use VIEWs, CTE, and derived tables in SQL.
You did know that a row is not a record in your posting or understand
transactions, makes me wonder if your schema is messed up because you
are mimicing files.|||Dan Guzman (guzmanda@.nospam-online.sbcglobal.net) writes:
> To add to the other responses, consider adding SET XACT_ABORT ON to the
> beginning of your proc. This will ensure a transaction rollback occurs in
> the case of a client-initiated attention event (e.g. query timeout or
> cancel).
Very interesting! I did not know about this. This can be a quick fix
for applications that suffers from unhandled query timeouts.
Why did you not tell me this before? :-)
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|||> Very interesting! I did not know about this. This can be a quick fix
> for applications that suffers from unhandled query timeouts.
We did exactly that recently for one of our ADO middle-tier database
application with persistent db connections. All transactions were done in
stored procedure code (no nested procs) and the application performed no
explicit transaction handling and no special database exception handling.
Database errors were logged but the app moved on, oblivious to the
ramifications.
Everything was fine until a nightly job was accidentally run during the day
and that caused blocking and subsequent command timeouts. Because the app
performed no connection cleanup after the exception, a transaction that was
in progress remained open after the timeout. All subsequent work done on a
problem connection was done in the context the open transaction and was
never committed!
In addition to adding XACT_ABORT ON quick fix, I asked the developers to
close and re-open persistent connections following any type of database
exception.

> Why did you not tell me this before? :-)
I got the idea to try XACT_ABORT ON after perusing your error handling
articles. Somehow, I got it in my mind that this technique was covered
there ;-)
Hope this helps.
Dan Guzman
SQL Server MVP
"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns97ED135AF6FCYazorman@.127.0.0.1...
> Dan Guzman (guzmanda@.nospam-online.sbcglobal.net) writes:
> Very interesting! I did not know about this. This can be a quick fix
> for applications that suffers from unhandled query timeouts.
> Why did you not tell me this before? :-)
>
> --
> 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|||Dan Guzman (guzmanda@.nospam-online.sbcglobal.net) writes:
> Everything was fine until a nightly job was accidentally run during the
> day and that caused blocking and subsequent command timeouts. Because
> the app performed no connection cleanup after the exception, a
> transaction that was in progress remained open after the timeout. All
> subsequent work done on a problem connection was done in the context the
> open transaction and was never committed!
A really fine mess! Yes, we have experienced this in our application as
well, although that's many years behind us now. I wonder how much the
default timeout of 30 seconds have cost enterprises over the worldin
money and misery.

> In addition to adding XACT_ABORT ON quick fix, I asked the developers to
> close and re-open persistent connections following any type of database
> exception.
While better than nothing, it's not optimal, unless you already have
turned off connection pooling. Of course, if you close and reconnect
directly, and get back the same physical connection directly, everything
will be cleaned up on the spot. But if the pool gives you a different
connection, it could take 60 seconds before the rollback occurs, when
the API actually closes the connection.

> I got the idea to try XACT_ABORT ON after perusing your error handling
> articles. Somehow, I got it in my mind that this technique was covered
> there ;-)
In that case, I don't know that I write in my articles myself. But I
will have to add it!
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

Multiple Inserts

Hello I am trying to optimize a Stored Procedure and am having no luck
It comes from using a Cursor Inserting a record then using that records
ID to insert another record. Here is the code
OPEN _cursor
FETCH NEXT FROM _cursor
INTO @.Program, @.Year, @.JobID, @.EmpID
WHILE @.@.FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM _cursor
INTO @.Program, @.Year, @.JobID, @.EmpID
SET @.msg = 'Job# : ' + CAST(@.JobID as nvarchar(20)) + ' Has no
Installation Rate for the Following Combination. '
SET @.msg = @.msg + 'Program : ' + @.Program + ', Year : ' + @.Year
SELECT @.isNEW = WFTID FROM tblWorkFlowTasks
WHERE ARID = @.AREA AND WFTTID=@.TT AND ID = @.JobID
-- Only Insert New Records
if(isnull(@.isNEW, 0) = 0)
BEGIN
INSERT INTO tblWorkFlowTasks(ARID, ID, StatusID, Description, WFTTID)
VALUES (@.AREA, @.JobID, @.STOpen, @.msg, @.TT)
SET @.WFTID = @.@.IDENTITY
-- Assign To User
INSERT INTO tblWorkFlowTaskAssignees (WFTID, UserID) VALUES
(@.WFTID,@.EmpID)
END
END
CLOSE _cursor
DEALLOCATE _cursor
I was wondering I could use an insert statement inside of an insert
statement
or specify SP VAlues from a SELECT Statement?What exactly is the business requirement here? Inserting master and detail
rows in one step?
BTW: that piece of code is actually made up from examples of not bad, but
*terrible* practices.
ML|||Any Help would be nice thanks.
Yes I know there are bad practices there. Hence trying to optimize it
takes
Over 3 minutes to run but if run each separately by hand it takes 20
secs.
I am trying to Insert a Master Records based on a Query/Temp Table.
And then Insert a Detail record for the Inserted Records. All In one
step with out cursors
Evil little devils.
Thanks Again|||How about using an Insert trigger to populate your second table. That way
you could remove the inefficient cursor. If this sounds like a viable optio
n
for you I'll supply some example code if required.
--
Adam J Warne, MCDBA
"EzraB" wrote:

> Hello I am trying to optimize a Stored Procedure and am having no luck
> It comes from using a Cursor Inserting a record then using that records
> ID to insert another record. Here is the code
>
> OPEN _cursor
> FETCH NEXT FROM _cursor
> INTO @.Program, @.Year, @.JobID, @.EmpID
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> FETCH NEXT FROM _cursor
> INTO @.Program, @.Year, @.JobID, @.EmpID
>
> SET @.msg = 'Job# : ' + CAST(@.JobID as nvarchar(20)) + ' Has no
> Installation Rate for the Following Combination. '
> SET @.msg = @.msg + 'Program : ' + @.Program + ', Year : ' + @.Year
>
> SELECT @.isNEW = WFTID FROM tblWorkFlowTasks
> WHERE ARID = @.AREA AND WFTTID=@.TT AND ID = @.JobID
> -- Only Insert New Records
> if(isnull(@.isNEW, 0) = 0)
> BEGIN
> INSERT INTO tblWorkFlowTasks(ARID, ID, StatusID, Description, WFTTID)
> VALUES (@.AREA, @.JobID, @.STOpen, @.msg, @.TT)
> SET @.WFTID = @.@.IDENTITY
>
> -- Assign To User
> INSERT INTO tblWorkFlowTaskAssignees (WFTID, UserID) VALUES
> (@.WFTID,@.EmpID)
> END
> END
> CLOSE _cursor
> DEALLOCATE _cursor
> I was wondering I could use an insert statement inside of an insert
> statement
> or specify SP VAlues from a SELECT Statement?
>|||Hi EzraB
You can avoid using the cursor to increase the performance.
You can re-write whole thing as:
INSERT INTO tblWorkFlowTasks(ARID, ID, StatusID, Description, WFTTID)
SELECT @.AREA, @.JobID, @.STOpen, 'Job# : ' + CAST(@.JobID as nvarchar(20)) + '
Has no Installation Rate for the Following Combination. ' + 'Program : ' +
@.Program + ', Year : ' + @.Year, @.TT
FROM <condition in cursor>
where isnull(@.isNEW, 0) = 0
INSERT INTO tblWorkFlowTaskAssignees (WFTID, UserID)
SELECT @.IDENTITY, @.EmpID
FROM <condition in cursor>
where isnull(@.isNEW, 0) = 0
Please let me know if u have any questions
best Regards,
Chandra
http://chanduas.blogspot.com/
http://www.SQLResource.com/
---
"EzraB" wrote:

> Hello I am trying to optimize a Stored Procedure and am having no luck
> It comes from using a Cursor Inserting a record then using that records
> ID to insert another record. Here is the code
>
> OPEN _cursor
> FETCH NEXT FROM _cursor
> INTO @.Program, @.Year, @.JobID, @.EmpID
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> FETCH NEXT FROM _cursor
> INTO @.Program, @.Year, @.JobID, @.EmpID
>
> SET @.msg = 'Job# : ' + CAST(@.JobID as nvarchar(20)) + ' Has no
> Installation Rate for the Following Combination. '
> SET @.msg = @.msg + 'Program : ' + @.Program + ', Year : ' + @.Year
>
> SELECT @.isNEW = WFTID FROM tblWorkFlowTasks
> WHERE ARID = @.AREA AND WFTTID=@.TT AND ID = @.JobID
> -- Only Insert New Records
> if(isnull(@.isNEW, 0) = 0)
> BEGIN
> INSERT INTO tblWorkFlowTasks(ARID, ID, StatusID, Description, WFTTID)
> VALUES (@.AREA, @.JobID, @.STOpen, @.msg, @.TT)
> SET @.WFTID = @.@.IDENTITY
>
> -- Assign To User
> INSERT INTO tblWorkFlowTaskAssignees (WFTID, UserID) VALUES
> (@.WFTID,@.EmpID)
> END
> END
> CLOSE _cursor
> DEALLOCATE _cursor
> I was wondering I could use an insert statement inside of an insert
> statement
> or specify SP VAlues from a SELECT Statement?
>|||Adam -
I know how to do cursors, But if I took that route how would I get the
UserID Values without requerying the Database? Thanks I'll keep it in
mind.
I do not claim to be the best sql Programmer. I can do what need to be
done. But I would like to now the best ways to do things so feel free
to pick apart my code. Thanks once agian|||Chandra-
Will that put the inserted ID from the Tasks Table into the Assignees
Table?
I doesn't look like it would but I'll Give it a try.
Thanks for all the help so far people. First time in groups never
expected responses this fast.|||That's the way to go!
Insert the master row, then in an appropriate way (of which "set @.master_id
= @.@.identity" is the worst) get the master key (be it primary key or any
other kandidate key), then use that key when inserting detail rows.
To improve data integrity you can wrap it all up into a transaction, too.
We could provide more help, but you'll have to provide more data. Post your
DDL, DML and sample data and we can come up with a solution.
ML|||No problem Ezra, I've copied some code in below. Just paste this in a test
db and run the code in. Then execute the proc to see it work. You can stil
l
use @.@.identity within a trigger.
--CODE START
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[TRG_INS_TEST]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
drop trigger [dbo].[TRG_INS_TEST]
GO
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[InsertMasterAndChild]') and OBJECTPROPERTY(id,
N'IsProcedure') = 1)
drop procedure [dbo].[InsertMasterAndChild]
GO
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[TableChild]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TableChild]
GO
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[TableMaster]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TableMaster]
GO
CREATE TABLE [dbo].[TableChild] (
[id] [int] NOT NULL ,
[col2] [varchar] (50) COLLATE Latin1_General_CI_AS NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TableMaster] (
[col1] [int] IDENTITY (1, 1) NOT NULL ,
[col2] [varchar] (50) COLLATE Latin1_General_CI_AS NULL
) ON [PRIMARY]
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE InsertMasterAndChild AS
insert into TableMaster (col2)
values ('a')
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE TRIGGER TRG_INS_TEST ON [dbo].[TableMaster]
FOR INSERT
AS
INSERT INTO TableChild
values(@.@.IDENTITY,'Anything you want')
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
--CODE END
--
Adam J Warne, MCDBA
"EzraB" wrote:

> Adam -
> I know how to do cursors, But if I took that route how would I get the
> UserID Values without requerying the Database? Thanks I'll keep it in
> mind.
> I do not claim to be the best sql Programmer. I can do what need to be
> done. But I would like to now the best ways to do things so feel free
> to pick apart my code. Thanks once agian
>|||Chandra - ML -
THanks for your help so far. But When I execute the Above Code In the
Assignees/Detials
I just get the Same ID for All the Records. So I'm going to give you a
really striped down version okay. here we go.
FROMTABLE
PKID [int]
Field1 [int]
FIeld2 [int]
MASTERTABLE
PKID [int]
Field1 [int] -- This should match Field1 from FROMTABLE
DETAILTABLE
PKID [int]
ParentID [int] -- This should match the PKID Field from MASTERTABLE
Field2 [int] -- This should match Field2 from FROMTABLE
I wish to insert all records from FROMTABLE INTO MASTERTABLE
ONLY Field Field1
THEN CREATE A DETAILS FOR THE MASTERTABLE in DETAILTABLE
With Field2 FROM FROMTABLE and PKID from MASTERTABLE.
The reason this is not in one table is so I can insert other details at
a later time.
Did I make that a bit easier to understand? Thanks.
I'm really starting to dig this groups.

Multiple Insertions

Hi everyone,

I just need a bit of advice as to where to start tackling a problem, if
thats possible - thanks very much.

I need a single stored procedure to make several inserts into my msde
database. There will be two arguments to the stored proc. The first
is a title argument which needs to be inserted into the first table
after which the autonumbered primary key is captured with @.@.identity.

The second argument is a delimited list of foreign keys which need to
be inserted into the second table along with the new key from the first
statement. This table is a link table with two columns - both foreign
keys - ie its the link table in a many to many relationship.

My problems is that as far as I know I can't use arrays in sql server
cause it doesn't support them. And this has come about because I don't
know how many rows need to be inserted into the link table. But there
will always be at least one.

I know I need to do this in a loop, but how do I split up the the
second argument so that I can?

Thanks,

MarkOn 27 Jun 2005 08:22:10 -0700, Mark wrote:

>Hi everyone,
>I just need a bit of advice as to where to start tackling a problem, if
>thats possible - thanks very much.
>I need a single stored procedure to make several inserts into my msde
>database. There will be two arguments to the stored proc. The first
>is a title argument which needs to be inserted into the first table
>after which the autonumbered primary key is captured with @.@.identity.
>The second argument is a delimited list of foreign keys which need to
>be inserted into the second table along with the new key from the first
>statement. This table is a link table with two columns - both foreign
>keys - ie its the link table in a many to many relationship.
>My problems is that as far as I know I can't use arrays in sql server
>cause it doesn't support them. And this has come about because I don't
>know how many rows need to be inserted into the link table. But there
>will always be at least one.
>I know I need to do this in a loop, but how do I split up the the
>second argument so that I can?
>Thanks,
>Mark

Hi Mark,

Check out this site for a wealth of possible solutions:

http://www.sommarskog.se/arrays-in-sql.html

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||>> I just need a bit of advice as to where to start tackling a problem, if that is possible - thanks very much. <<

You need to go back to foundations. You missed the major points of
RDBMS and are trying to write a 1950's file system in SQL.

1) Autonumbering is totally non-relational and cannot be a key by
definition. This is foundations, not fancy stuff. A key is a subset
of attributes that makes a row unique within a table; it has to do with
the data model and not the current state of the hardware on which the
data is stored.

2) An INSERT INTO statement works on one and only one base table.

3) There are only scalar value parameters; there are no lists, arrays,
etc. There are a bunch of kludges where you write a parser in T-SQL,
if you do not care about maintaining or porting your code.

4) There is no such term as "link table" -- link is a term from
navigational databases and assembly language. It is a many-to-many
relationship.

5) We do not like to write procedural code, so you should avoid loops.

6) You do not insert keys into a table; you insert rows. WHOLE rows.
You probably have more (non-key) columns in the second table to fill
in.

7) Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications. It is very hard to debug code when you do not let us
see it.

Your code should look something like this, assuming a vanilla invoice
schema:

BEGIN
INSERT INTO Invoices (invoice_nbr, ..)
VALUES (@.new_invoice_nbr, .. );

INSERT INTO InvoiceDetails (invoice_nbr, sku..)
SELECT @.new_invoice_nbr, sku..
FROM WorkingTable;
END;

Invoice_nbr should have a CHECK() constraint to validate it, of course.|||This is the version of split array return table from sommarskog. I use this
to pass in arrays of keys (space separated). It's more efficient than
populating a temporary table with keys programmatically every time you need
to join (as Celko seems to suggest). Although in general Celko is correct
from a purest point of view, I do believe that a small function like this
allowing you to pass and split arrays in a stored procedure has more utility
than it does downsides. For example, my client needs to periodically check
a set of rows to see if they have been changed. These records are in no
particular order (whichever rows the user happens to be viewing). Instead
of writing each one to a working table one by one and then executing an SP
to check their timestamps, I pass in an array of keys, split it and join
with the split table to return the update state.

However, in your example, perhaps a working table would be a better idea. I
would only advise using array splitting algorithms server-side if they are
just autonumber unique keys, rather than whole rows of information. It's
just a quickish method for fetching arbitrary rows from your tables.

CREATE FUNCTION dbo.func_Split_Array_Return_Table (@.list NTEXT)
RETURNS @.Table TABLE ( listpos INT IDENTITY(1, 1) NOT NULL, number INT NOT
NULL) AS

BEGIN
DECLARE @.pos INT, @.textpos INT, @.chunklen SMALLINT, @.str NVARCHAR(4000),
@.tmpstr NVARCHAR(4000), @.leftover NVARCHAR(4000)

SET @.textpos = 1
SET @.leftover = ''

WHILE @.textpos <= datalength(@.list) / 2
BEGIN

SET @.chunklen = 4000 - datalength(@.leftover) / 2
SET @.tmpstr = ltrim(@.leftover + substring(@.list, @.textpos,
@.chunklen))
SET @.textpos = @.textpos + @.chunklen
SET @.pos = charindex(' ', @.tmpstr)

WHILE @.pos > 0
BEGIN

SET @.str = substring(@.tmpstr, 1, @.pos - 1)

INSERT @.Table (number)
VALUES
(convert(int, @.str))

SET @.tmpstr = ltrim(substring(@.tmpstr, @.pos + 1, len(@.tmpstr)))
SET @.pos = charindex(' ', @.tmpstr)

END

SET @.leftover = @.tmpstr
END

IF ltrim(rtrim(@.leftover)) <> ''
INSERT @.Table (number)
VALUES
(convert(int, @.leftover))

RETURN

END

"Mark" <mjmather@.gmail.com> wrote in message
news:1119885730.339475.84280@.g47g2000cwa.googlegro ups.com...
> Hi everyone,
> I just need a bit of advice as to where to start tackling a problem, if
> thats possible - thanks very much.
> I need a single stored procedure to make several inserts into my msde
> database. There will be two arguments to the stored proc. The first
> is a title argument which needs to be inserted into the first table
> after which the autonumbered primary key is captured with @.@.identity.
> The second argument is a delimited list of foreign keys which need to
> be inserted into the second table along with the new key from the first
> statement. This table is a link table with two columns - both foreign
> keys - ie its the link table in a many to many relationship.
> My problems is that as far as I know I can't use arrays in sql server
> cause it doesn't support them. And this has come about because I don't
> know how many rows need to be inserted into the link table. But there
> will always be at least one.
> I know I need to do this in a loop, but how do I split up the the
> second argument so that I can?
> Thanks,
> Marksql

Friday, March 23, 2012

Multiple Filtering on the same field using a Stored Procedure

Hello,

I am looking at writing a SP without much success which enables multiple filtering on one field. Something like below:

Input field: Product Description

So if the user enters: "Large Drill" OR "Drill Large" the same resultset will be returned.

SELECT * FROM products WHERE products.prod_desc contains both "Large" AND "Drill"

I guess there'll need to be a nested Select and loop to parse the space separated input field.

Any pointers would be appreciated.

Thank you

Lee

hi dear,

I answer the same question on MSDN forum....you can reach this via this link

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1448983&SiteID=1

Thank You

Best Regards,

Muhammad Akhtar Shiekh

|||

Thank you very much Muhammad

Problem solved.

Wednesday, March 21, 2012

Multiple Files

I have a job with a single step that executes a stored procedure that performs the following steps:

1. Checks for the existance of a file A in a folder A

2. If it exists,

a. executes the cmdshell to run a DTS package to drop a table, recreate it and load the data in the file A to table X

b. runs other stored procedures that use the data in table X to create other tables Y and Z

c. executes the cndshell to remove and rename the file A from Folder A into Folder B

What I'd like to do is use this same stored procedure if possible, but create a job or another store procedure that would loop thru and process multiple files in Folder A instead of just one.

Any suggestions would be greatly appreciated

My post in this thread should point you in a workable direction.

Multiple file import SQLExpress

Hi everyone one,
I'm very new to SQLExpress and I'm having difficulty with a procedure I
found on the net
to import multiple files into a table:
http://www.databasejournal.com/feat...cle.php/3325701
The method I'm using is method one.
I've done everything as outlined, however when running the procedure within
SQLexpress I receive the error message
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ','.
I'm presuming it has something to do with the Fieldterminator remark, the
double quote and comma specified in the bulk insert statement:
set @.Query ='BULK INSERT '+ @.Tablename + ' FROM "'+ @.Filepath+@.Filename+'"
WITH
( FIELDTERMINATOR = "," , ROWTERMINATOR = "\n")'
I've tried running the bulk insert with single quotes and it runs fine..with
double quotes not so good I get the same error so thats why I think its a
syntax error...but when I replace single quotes in the procedure, the
procedure doesn't compile...i.e.
set @.Query ='BULK INSERT '+ @.Tablename + ' FROM "'+ @.Filepath+@.Filename+'"
WITH
( FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n')'
....I'm at a loss as to how to fix it!
Could someone help please, thanks so much.Try using single quotes instead of double quotes to delimit literals so that
you aren't sensitive to your QUOTED_IDENTIFIER setting. When you need a
quote within a literal, specify 2 single quotes:
set @.Query ='BULK INSERT '+ @.Tablename + ' FROM '''+ @.Filepath+@.Filename+'''
WITH
( FIELDTERMINATOR = '','' , ROWTERMINATOR = ''\n'')'
Happy Holidays
Dan Guzman
SQL Server MVP
"Dale" <dale@.nospam.com> wrote in message
news:es09z0vDGHA.472@.TK2MSFTNGP12.phx.gbl...
> Hi everyone one,
> I'm very new to SQLExpress and I'm having difficulty with a procedure I
> found on the net
> to import multiple files into a table:
> http://www.databasejournal.com/feat...cle.php/3325701
> The method I'm using is method one.
> I've done everything as outlined, however when running the procedure
> within SQLexpress I receive the error message
> Msg 102, Level 15, State 1, Line 2
> Incorrect syntax near ','.
> I'm presuming it has something to do with the Fieldterminator remark, the
> double quote and comma specified in the bulk insert statement:
> set @.Query ='BULK INSERT '+ @.Tablename + ' FROM "'+ @.Filepath+@.Filename+'"
> WITH
> ( FIELDTERMINATOR = "," , ROWTERMINATOR = "\n")'
> I've tried running the bulk insert with single quotes and it runs
> fine..with double quotes not so good I get the same error so thats why I
> think its a syntax error...but when I replace single quotes in the
> procedure, the procedure doesn't compile...i.e.
> set @.Query ='BULK INSERT '+ @.Tablename + ' FROM "'+ @.Filepath+@.Filename+'"
> WITH
> ( FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n')'
> ....I'm at a loss as to how to fix it!
> Could someone help please, thanks so much.
>
>|||Thanks Dan, that worked, now on to my "real" data...
the fields are separated by a comma but enclosed in a double quote i.e.
"12345","67899"
How do I get the field terminator set correctly? I just know you're going
to
tell me to remove the double quotes...(sigh)...theres a ton of files...
Thanks again
"Dan Guzman" <guzmanda@.nospam-online.sbcglobal.net> wrote in message
news:OX$4aOwDGHA.344@.TK2MSFTNGP11.phx.gbl...
> Try using single quotes instead of double quotes to delimit literals so
> that you aren't sensitive to your QUOTED_IDENTIFIER setting. When you
> need a quote within a literal, specify 2 single quotes:
> set @.Query ='BULK INSERT '+ @.Tablename + ' FROM '''+
> @.Filepath+@.Filename+'''
> WITH
> ( FIELDTERMINATOR = '','' , ROWTERMINATOR = ''\n'')'
> --
> Happy Holidays
> Dan Guzman
> SQL Server MVP
> "Dale" <dale@.nospam.com> wrote in message
> news:es09z0vDGHA.472@.TK2MSFTNGP12.phx.gbl...
>|||You need to create a format file when you have a more complicated file
format. Sample SQL 2000 format file:
8.0
3
1 SQLCHAR 0 1 "\"" 0 quote ""
2 SQLCHAR 0 10 "\",\"" 1 Col1 ""
3 SQLCHAR 0 10 "\"\r\n" 2 Col2 ""
Specify the format file using FORMATFILE in your BULK INSERT statement
instead of FIELDTERMINATOR and ROWTERMINATOR:
set @.Query ='BULK INSERT '+ @.Tablename + ' FROM '''+
@.Filepath+@.Filename+'''
WITH
( FORMATFILE = ''' + @.FormatFilename + ''')'
See the Books Online for format file details.
Happy Holidays
Dan Guzman
SQL Server MVP
"Dale" <dale@.nospam.com> wrote in message
news:OtBJ2LxDGHA.3064@.TK2MSFTNGP10.phx.gbl...
> Thanks Dan, that worked, now on to my "real" data...
> the fields are separated by a comma but enclosed in a double quote i.e.
> "12345","67899"
> How do I get the field terminator set correctly? I just know you're going
> to
> tell me to remove the double quotes...(sigh)...theres a ton of files...
> Thanks again
> "Dan Guzman" <guzmanda@.nospam-online.sbcglobal.net> wrote in message
> news:OX$4aOwDGHA.344@.TK2MSFTNGP11.phx.gbl...
>|||Thanks Dan...this certainly got complicated fast!! I'm guessing this format
file is likened to a specifications file in msaccess.
At any rate, when trying to run the bcp utility:
bcp adventureworks.humanresources.department format nul -T -n -f
importtest-f-n.txt
I receive an error, unable to open a connection...that remote access may not
be enabled? I've checked using the surface configuration tool and remote
looks to be enabled.
Secondly if I get this bcp utililty to work..can it be run against a "txt"
file (haven't been able to get this to work either)..it doesn't make sense
to me to run the utility against the table rec'ving the data if it isn't the
source of the import?...I can't see any other way to create this format file
other than manually?
"Dan Guzman" <guzmanda@.nospam-online.sbcglobal.net> wrote in message
news:eqAaAwxDGHA.3528@.TK2MSFTNGP12.phx.gbl...
> You need to create a format file when you have a more complicated file
> format. Sample SQL 2000 format file:
> 8.0
> 3
> 1 SQLCHAR 0 1 "\"" 0 quote ""
> 2 SQLCHAR 0 10 "\",\"" 1 Col1 ""
> 3 SQLCHAR 0 10 "\"\r\n" 2 Col2 ""
> Specify the format file using FORMATFILE in your BULK INSERT statement
> instead of FIELDTERMINATOR and ROWTERMINATOR:
> set @.Query ='BULK INSERT '+ @.Tablename + ' FROM '''+
> @.Filepath+@.Filename+'''
> WITH
> ( FORMATFILE = ''' + @.FormatFilename + ''')'
> See the Books Online for format file details.
> --
> Happy Holidays
> Dan Guzman
> SQL Server MVP
> "Dale" <dale@.nospam.com> wrote in message
> news:OtBJ2LxDGHA.3064@.TK2MSFTNGP10.phx.gbl...
>|||> bcp adventureworks.humanresources.department format nul -T -n -f
> importtest-f-n.txt
Since you haven't specified a server, BCP will connect to the default
instance on the local machine. Is that your intent?

> it doesn't make sense to me to run the utility against the table rec'ving
> the data if it isn't the source of the import?
A format file describes the format of your text file (source or target).
When you run BCP using the 'format' option, the table is neither a source
nor target; the table schema is used to facilitate creating a format file
with one field per column. Since you have specified '-n', the generated
format file will be appropriate only for native file format rather than the
comma-delimited/quoted field format you specified in your original post.

> I can't see any other way to create this format file other than manually?
Although BCP can't directly create a format file for a
comma-delimited/quoted field format, you can use BCP to create a default
character format file and then change the generated to match your actual
file. That way, you at least won't need to enter all the columns. For
example:
bcp adventureworks.humanresources.department format
nul -T -c -fimporttest-f-n.txt -SMyServer
Hope this helps.
Dan Guzman
SQL Server MVP
"Dale" <dale@.nospam.com> wrote in message
news:uMsEFo7DGHA.516@.TK2MSFTNGP15.phx.gbl...
> Thanks Dan...this certainly got complicated fast!! I'm guessing this
> format file is likened to a specifications file in msaccess.
> At any rate, when trying to run the bcp utility:
> bcp adventureworks.humanresources.department format nul -T -n -f
> importtest-f-n.txt
> I receive an error, unable to open a connection...that remote access may
> not be enabled? I've checked using the surface configuration tool and
> remote looks to be enabled.
> Secondly if I get this bcp utililty to work..can it be run against a "txt"
> file (haven't been able to get this to work either)..it doesn't make sense
> to me to run the utility against the table rec'ving the data if it isn't
> the source of the import?...I can't see any other way to create this
> format file other than manually?
> "Dan Guzman" <guzmanda@.nospam-online.sbcglobal.net> wrote in message
> news:eqAaAwxDGHA.3528@.TK2MSFTNGP12.phx.gbl...
>|||Thanks again Dan
I agree it would be easier to run the bcp utility w/correct syntax for the
purposes intended. However it seems...I cannot get it to run:
C:\>bcp adventureworks.humanresources.department format nul -T -n -f
importtest-
f-n.txt -<servername>
Warning: Packetsize size must be between 512 and 65535 -- defaulting to
4096.
SQLState = 08001, NativeError = 2
Error = [Microsoft][SQL Native Client]Named Pipes Provider: Could not open a
con
nection to SQL Server [2].
SQLState = HYT00, NativeError = 0
Error = [Microsoft][SQL Native Client]Login timeout expired
SQLState = 08001, NativeError = 2
Error = [Microsoft][SQL Native Client]An error has occurred while
establishing a
connection to the server. When connecting to SQL Server 2005, this failure
may
be caused by the fact that under the default settings SQL Server does not
allow
remote connections.
I have checked everything that a newbie can think of, it looks to me like
remote connections are enabled, connect via tcp/ip or named pipes, I've even
specified a port 3308 to connect on via firewall...
Ok as silly as it sounds, does bcp work with SQLexpress?...|||Hi Dale
You are missing -S<servername> is this a typo?
If you are using the default server then you can miss out specifying
completely
John
"Dale" <dale@.nospam.com> wrote in message
news:ejWme09DGHA.2956@.TK2MSFTNGP14.phx.gbl...
> Thanks again Dan
> I agree it would be easier to run the bcp utility w/correct syntax for the
> purposes intended. However it seems...I cannot get it to run:
> C:\>bcp adventureworks.humanresources.department format nul -T -n -f
> importtest-
> f-n.txt -<servername>
> Warning: Packetsize size must be between 512 and 65535 -- defaulting to
> 4096.
> SQLState = 08001, NativeError = 2
> Error = [Microsoft][SQL Native Client]Named Pipes Provider: Could not open
> a con
> nection to SQL Server [2].
> SQLState = HYT00, NativeError = 0
> Error = [Microsoft][SQL Native Client]Login timeout expired
> SQLState = 08001, NativeError = 2
> Error = [Microsoft][SQL Native Client]An error has occurred while
> establishing a
> connection to the server. When connecting to SQL Server 2005, this failure
> may
> be caused by the fact that under the default settings SQL Server does not
> allow
> remote connections.
> I have checked everything that a newbie can think of, it looks to me like
> remote connections are enabled, connect via tcp/ip or named pipes, I've
> even specified a port 3308 to connect on via firewall...
> Ok as silly as it sounds, does bcp work with SQLexpress?...
>|||In addition to John's response, the instance needs to be restarted after you
enable remote connections. You might try restarting the instance to make
sure the change isn't pending.

> I have checked everything that a newbie can think of, it looks to me like
> remote connections are enabled, connect via tcp/ip or named pipes, I've
> even specified a port 3308 to connect on via firewall...
> Ok as silly as it sounds, does bcp work with SQLexpress?...
Is this the default or named instance? How did you configure port 3308?
Note that for a named instance, you'll need to enable/start the SQL Browser
service in order to remotely connect by server\instance.
Hope this helps.
Dan Guzman
SQL Server MVP
"Dale" <dale@.nospam.com> wrote in message
news:ejWme09DGHA.2956@.TK2MSFTNGP14.phx.gbl...
> Thanks again Dan
> I agree it would be easier to run the bcp utility w/correct syntax for the
> purposes intended. However it seems...I cannot get it to run:
> C:\>bcp adventureworks.humanresources.department format nul -T -n -f
> importtest-
> f-n.txt -<servername>
> Warning: Packetsize size must be between 512 and 65535 -- defaulting to
> 4096.
> SQLState = 08001, NativeError = 2
> Error = [Microsoft][SQL Native Client]Named Pipes Provider: Could not open
> a con
> nection to SQL Server [2].
> SQLState = HYT00, NativeError = 0
> Error = [Microsoft][SQL Native Client]Login timeout expired
> SQLState = 08001, NativeError = 2
> Error = [Microsoft][SQL Native Client]An error has occurred while
> establishing a
> connection to the server. When connecting to SQL Server 2005, this failure
> may
> be caused by the fact that under the default settings SQL Server does not
> allow
> remote connections.
> I have checked everything that a newbie can think of, it looks to me like
> remote connections are enabled, connect via tcp/ip or named pipes, I've
> even specified a port 3308 to connect on via firewall...
> Ok as silly as it sounds, does bcp work with SQLexpress?...
>|||Xref: TK2MSFTNGP08.phx.gbl microsoft.public.sqlserver.programming:574887
Dale (dale@.nospam.com) writes:
> Thanks Dan...this certainly got complicated fast!! I'm guessing this
> format file is likened to a specifications file in msaccess. At any
> rate, when trying to run the bcp utility:
> bcp adventureworks.humanresources.department format nul -T -n -f
> importtest-f-n.txt
> I receive an error, unable to open a connection...that remote access may
> not be enabled? I've checked using the surface configuration tool and
> remote looks to be enabled
You probably need to add:
-S .\SQLEXPRESS
if you leave out the server name, BCP tries to connect to the default
instance. But by default SQL Express installs as a *named* instance with
the name SQLEXPRESS. (You can have several instances of SQL Server on
your machine, but only one can be the default instance.)
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

Multiple Dynamic Insert Statements in one stored procedure?

Hello, I'm having a little trouble, and need a little direction. I

have a stored procedure with a transaction that creates a contract for

a customer in a Contract table. After the contract record is created, I need

to create the contract items/products with their properties (price,

notes, etc), which belong in a linked table, so that they're created

all within the same transaction (the contract, and the products), so

that if either the contract or any of the items cannot be inserted into

their correct tables, it will rollback and undo the creation of the

contract. Now, I understand transactions and how they work, but my

trouble is that I'm not sure if I can use a dynamic insert

statement to create the contract items/products, within the same

transaction where the contract is created.

I'm new to sp_executesql, which seems to be the recommended method for dynamic sql in a stored proc, but if I understand it correctly, I'd have to call a stored proc for each item i wanted to insert something into the ContractItem table with a dynamic insert statement. Is there any way to have multiple dynamically created insert statements in one stored procedure? Help! I hope I explained my problem well enough. thanks in advance!

You can execute sp_executesql as many times as you like in a stored procedure. Simply begin a transaction at the start of the proc then either rollback or commit the transaction when appropriate.

Incidentally, is there a particular reason that you are choosing to use dynamic SQL over defining stored procedures that parameters can be passed into?

Chris

|||

Chris Howarth wrote:

You can execute sp_executesql as many times as you like in a stored procedure. Simply begin a transaction at the start of the proc then either rollback or commit the transaction when appropriate.

I understand this, I guess my problem really is this: the number of rows I will have to insert into the ContractItem table will vary each time this stored procedure to create a Contract and it's ContractItems is called. So how do I pass that (variable amount of) data into the stored prodedure to create the dynamic insert statements?

Chris Howarth wrote:

Incidentally, is there a particular reason that you are choosing to use dynamic SQL over defining stored procedures that parameters can be passed into?

Not really, I'm still sort of new to stored procedures though, if that is any kind of an excuse :) If this would be a better way to do it, then my plan should probably change slightly...

|||

How you choose to do this very much depends on your application's architecture.

If you have a web server or application server that is executing your stored procedures then it would probably make sense to create a single INSERT stored proc (designed to insert one row at a time) per table and then get your web/app server to execute the stored procedure once per row, passing in the parameters as required. Any iteration that needs to take place can then be performed by the web/app server.

You can start a transaction at the connection level, so as long as your web/app server uses the same connection to execute all stored procs that are part of the 'business transaction' then all of the changes will be rolled back should an error be raised.

Does this fit your scenario?

Chris

|||Chris,

This does fit my scenario... a transaction at the connection level sound just like what I need to get this to work properly. Now I just have to go dig up how to do that. Thank you so much for your help!

Multiple Detail Sections

I have created a report that is using a table with multiple groupings. My
main result set from a stored procedure populates the detail section of the
table. I have a secondary result set that I would like to populate based on a
value from the first result set. For example:
Detail 1 Customer 1
Detail 2 Order 1
Order 2
Order 3
Detail 2 is populated based on the customer id.
How can I accomplish this using the report authoring tool?
Any help would be appreciated.Assuming you are not trying to do a table with groupings, this can be
accomplished with nested "List" items (a list inside of a list) which allow
a free form layout. You just bind each list to the correct dataset for your
detail. See the Sample Reports for an example.
"Scott2624" <Scott2624@.discussions.microsoft.com> wrote in message
news:8411C050-B2FE-48B1-8E26-755220D4FD06@.microsoft.com...
>I have created a report that is using a table with multiple groupings. My
> main result set from a stored procedure populates the detail section of
> the
> table. I have a secondary result set that I would like to populate based
> on a
> value from the first result set. For example:
> Detail 1 Customer 1
> Detail 2 Order 1
> Order 2
> Order 3
> Detail 2 is populated based on the customer id.
> How can I accomplish this using the report authoring tool?
> Any help would be appreciated.
>

Monday, March 19, 2012

multiple deletes with a stored procedure

Just wondering if this is good form:

Alter Procedure "mySPName"
@.UniqueID int
AS
set nocount on
set xact_abort off

DELETE FROM tblNameOne
WHERE
(tblNameOne.UniqueID = @.UniqueID)

DELETE FROM tblNameTwo
WHERE
(tblNameTwo.UniqueID = @.UniqueID)

Is it a good idea to run multiple detele statements within one SP?
thanks,
lqOn 8 Apr 2004 12:30:55 -0700, Lauren Quantrell wrote:

>Just wondering if this is good form:

Looks fine to me, except I'd prefer set xact_abort on. But that's a
general comment, your situation mught demand this option to be off.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||Thanks,
I am having a situation were the SQL server experiences every now and
then excessive blocking errors, sometimes around the time of execution
of this type of stored procedure, sometimes around the time of an SP
where I'm running multiple INSERT queries with one SP. I'm trying to
identify where the problem may be.

I'm wondering if you could tell me what the use of GO or RETURN is and
if I need them in this sort of SP?
lq

Hugo Kornelis <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message news:<v1bb70td57mtifd8le40ot4kv9gp118as9@.4ax.com>...
> On 8 Apr 2004 12:30:55 -0700, Lauren Quantrell wrote:
> >Just wondering if this is good form:
> Looks fine to me, except I'd prefer set xact_abort on. But that's a
> general comment, your situation mught demand this option to be off.
> Best, Hugo|||On 9 Apr 2004 06:42:55 -0700, Lauren Quantrell wrote:

>Thanks,
>I am having a situation were the SQL server experiences every now and
>then excessive blocking errors, sometimes around the time of execution
>of this type of stored procedure, sometimes around the time of an SP
>where I'm running multiple INSERT queries with one SP. I'm trying to
>identify where the problem may be.

I don't know much about blocking. The only thing I know is that you
can use sp_who to identify which process all other processes are
waiting for. The only action I have ever taken in these situations was
to either kill the blocking process or tell the complaining users that
this process was too important to postpone until the evening.

If you find a procedure like this to be the cause of blocking, there
are probably ways to improve this. However, I don't know how to do
that. Maybe you should ask a new question, making sure that "blocking"
is in the subject line. Also, note that there are a lot of groups
devoted to SQL Server in the microsoft.public.sqlserver hierarchy. A
question about blocking could go in either .programming or .server.

>I'm wondering if you could tell me what the use of GO or RETURN is and
>if I need them in this sort of SP?

RETURN is used to exit immediately from a stored procedure or trigger.
Check Books Online for more detailed description and examples. Use it
if you detect a situation where the remaining statements in the
procedure should not be executed.

GO means "end of batch". It is intercepted by Query Analyzer (as well
as OSQL, ISQL and probably other tools as well) and prompts them to
send everything to the server. Therefor, you can't put GO inside a
procedure. Example:

Create procedure Testit
as
select * from sysobjects
go
select * from sysfiles
go

Execute this, and all rows in sysfiles will be listed. Next, execute
"sp_helptext Testit" and you'll see that only the select from
sysobjects made it into the procedure. The other select was sent as a
seperate batch and therefor executed immediately.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||If i am not wrong, i think the GO statment is used for Batch Termination.
Some of the SQL Statments don't allow some Commands to be executed along
with DDL. So the word GO can be used to tell the SQL Server that one batch
finished and the other batch is ready. The return statement can be used when
checking for error codes and returning an error code(from a procedure) to
the appropriate procedure/SQL.

"Lauren Quantrell" <laurenquantrell@.hotmail.com> wrote in message
news:47e5bd72.0404090542.db112d9@.posting.google.co m...
> Thanks,
> I am having a situation were the SQL server experiences every now and
> then excessive blocking errors, sometimes around the time of execution
> of this type of stored procedure, sometimes around the time of an SP
> where I'm running multiple INSERT queries with one SP. I'm trying to
> identify where the problem may be.
> I'm wondering if you could tell me what the use of GO or RETURN is and
> if I need them in this sort of SP?
> lq
>
> Hugo Kornelis <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:<v1bb70td57mtifd8le40ot4kv9gp118as9@.4ax.com>...
> > On 8 Apr 2004 12:30:55 -0700, Lauren Quantrell wrote:
> > >Just wondering if this is good form:
> > Looks fine to me, except I'd prefer set xact_abort on. But that's a
> > general comment, your situation mught demand this option to be off.
> > Best, Hugo|||Have you looked at triggers? We've got an idiot vendor (who should
be gone by the end of the year) who implemented their referential
integrity with triggers, rather than real foreign keys.
We make up for that with an excessive use of cursors and nolock
hints, but if you have the option of actually fixing the trigger,
it would be better.

Bill

Lauren Quantrell wrote:

> Thanks,
> I am having a situation were the SQL server experiences every now and
> then excessive blocking errors, sometimes around the time of execution
> of this type of stored procedure, sometimes around the time of an SP
> where I'm running multiple INSERT queries with one SP. I'm trying to
> identify where the problem may be.
> I'm wondering if you could tell me what the use of GO or RETURN is and
> if I need them in this sort of SP?
> lq
>
> Hugo Kornelis <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message news:<v1bb70td57mtifd8le40ot4kv9gp118as9@.4ax.com>...
>>On 8 Apr 2004 12:30:55 -0700, Lauren Quantrell wrote:
>>
>>
>>>Just wondering if this is good form:
>>
>>Looks fine to me, except I'd prefer set xact_abort on. But that's a
>>general comment, your situation mught demand this option to be off.
>>
>>Best, Hugo

multiple datatables passed to one report?

Is it possible to pass multiple datatables to one report (within one dataset)?

My stored procedure would have two or more select statements.

Only one resultset is supported.

You could add a parameter to the stored procedure (or write a wrapper). The parameter determines which resultset is returned. You would then define multiple datasets in the RS report and call the stored procedure with different parameter values.

-- Robert

|||

Thanks, I guess I need to research multiple datasets in the report. I imagine there is a custom assembly involved?

|||

Using multiple datasets in a report has nothing to do with custom assemblies.

Multiple datasets just means you need to have multiple data regions (list, table, matrix, chart) in the report to show the data.

-- Robert

Wednesday, March 7, 2012

Multiple columns and row values

Hi. I am trying to write a single stored procedure which would trace the
changes made by a user on a table. I would like this implemented on multiple
tables having the most efficient code possible. Is it possible to browse to
a
table and extract all its columns (column_name from information_schema) and
get the row value for these columns having only a record id. I was able to
get the column_name but unable to make a sql statement retrieving the values
of the column_name.
Any help is appreciated.Can you post more detail? What do you mean "columns having only a record
id"? If you post actual DDL, sample data, and sample output, that would be
best...
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
--
"[Alan Flores]" <AlanFlores@.discussions.microsoft.com> wrote in message
news:871EF4F4-B4A4-493D-BBC1-6787783C1BFF@.microsoft.com...
> Hi. I am trying to write a single stored procedure which would trace the
> changes made by a user on a table. I would like this implemented on
multiple
> tables having the most efficient code possible. Is it possible to browse
to a
> table and extract all its columns (column_name from information_schema)
and
> get the row value for these columns having only a record id. I was able to
> get the column_name but unable to make a sql statement retrieving the
values
> of the column_name.
> Any help is appreciated.
>|||OK. Sorry about that.. I have TABLE1 with COL1, COL2, COL3, COL4. COL1 is in
t
and the primary key. also I have TABLE2 with COL1, COL2, COL3, etc.. with
COL1 as primary key and an int. I want to write a stored procedure to extrac
t
a record from TABLE1 or TABLE2 (table_name being passed as parameter) with a
record id (COL1) and loops over the columns and its row values. So I can use
this stored procedure in these two tables or in any other table as long as
the primary key is int. better if the int (primary key) is eliminated as a
constraint as well..
so a query from information_schema would give me the column names (given the
table as a parameter) but how do i extract the row value of those columns if
i know the record primary key value (COL1).
Thanks.
"Adam Machanic" wrote:

> Can you post more detail? What do you mean "columns having only a record
> id"? If you post actual DDL, sample data, and sample output, that would b
e
> best...
> --
> Adam Machanic
> SQL Server MVP
> http://www.sqljunkies.com/weblog/amachanic
> --
>
> "[Alan Flores]" <AlanFlores@.discussions.microsoft.com> wrote in message
> news:871EF4F4-B4A4-493D-BBC1-6787783C1BFF@.microsoft.com...
> multiple
> to a
> and
> values
>
>|||"[Alan Flores]" <AlanFlores@.discussions.microsoft.com> wrote in message
news:D66A9835-AAAF-4811-8F6F-1473F095166A@.microsoft.com...
> OK. Sorry about that.. I have TABLE1 with COL1, COL2, COL3, COL4. COL1 is
int
> and the primary key. also I have TABLE2 with COL1, COL2, COL3, etc.. with
> COL1 as primary key and an int. I want to write a stored procedure to
extract
> a record from TABLE1 or TABLE2 (table_name being passed as parameter) with
a
> record id (COL1) and loops over the columns and its row values. So I can
use
> this stored procedure in these two tables or in any other table as long as
> the primary key is int. better if the int (primary key) is eliminated as a
> constraint as well..
Why do you want to do this? You're completely eliminating most of the
benefits of using stored procedures, and DBMSs in general -- keeping the
application out of the data management business! My advice to you is to
very carefully consider your motives for doing this -- I can guarantee that
you will not end up simplifying anything by tightly coupling your
application to your database (which is what this stored procedure will
accomplish). You can take that with however many grains of salt as you
choose, but you may want to search the archives of this group for lots of
threads about these kinds of techniques and the problems they invariably
cause.
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
--|||i know.. well. i have written a large application and i everything is almost
in place. I just need this user tracking history. who inserts what and who
updates which record.. and so on.. i can use triggers but that would mean
going to each one of the tables which is 100+. I want a single stored
procedure, called from a class that I can reuse on every page. So i need the
columns and the current values so i can record them in a table where it can
be retrieved in a report. but this has to go on a per column value.. and the
pages are a lot less that the tables..
"Adam Machanic" wrote:

> "[Alan Flores]" <AlanFlores@.discussions.microsoft.com> wrote in message
> news:D66A9835-AAAF-4811-8F6F-1473F095166A@.microsoft.com...
> int
> extract
> a
> use
>
> Why do you want to do this? You're completely eliminating most of the
> benefits of using stored procedures, and DBMSs in general -- keeping the
> application out of the data management business! My advice to you is to
> very carefully consider your motives for doing this -- I can guarantee tha
t
> you will not end up simplifying anything by tightly coupling your
> application to your database (which is what this stored procedure will
> accomplish). You can take that with however many grains of salt as you
> choose, but you may want to search the archives of this group for lots of
> threads about these kinds of techniques and the problems they invariably
> cause.
>
> --
> Adam Machanic
> SQL Server MVP
> http://www.sqljunkies.com/weblog/amachanic
> --
>
>