Execute Multiple SQL Statements In Stored Procedur

Feb 28, 2008

I am seeking a syntax example for executing multiple T-SQL statements in a single stored procedure. For example, I would like to insert a new client record and immediately insert an associated household record. I don't want to have to hit the database twice to accomplish this, and I prefer not to use a trigger.

View 1 Replies


ADVERTISEMENT

Execute Multiple SQL Statements In Stored Proc

Nov 1, 2005

Hi, I have a table containing SQl statements. I need to extract the statements and execute them through stored procedure(have any better ideas?)

Table Test

Id Description

1Insert into test(Id,Name) Values (1,'Ron')
2Update Test Set Name = 'Robert' where Id = 1
3Delete from Test where Id = 1


In my stored procedure, i want to execute the above statements in the order they were inserted into the table. Can Someone shed some light on how to execute multiple sql statements in a stored procedure. Thanks

Reo

View 2 Replies View Related

How To Execute Multiple Statements?

Sep 17, 2007

Is there a way to execute multiple SQL statements within SQL Server? I'm triyng to write a sql statement that will delete from three tables. I need at least two sql statements to delete from these three tables. Can this be done?

View 12 Replies View Related

Execute Multiple Statements At Once...

Oct 17, 2006

I am not even sure if this is possible but I want to be able to excute several statements (or SPs) at once from inside a SPs (or any other method).

What I am doing is a I am taking data from a single column, multiple rows and making it into one row (i.e. data1 + data2 + data3....) But I am doing this to a total of 2.1 million individual rows and the result will be about 204k rows.... what I have written is basically a nested loop and it works fine but very slow... slow as in it has been running for 24 hours now and it is about 60% done... I need this to finish in under 36 hours preferably...

If I could handle more than one set of data at once (there will be no duplicates) I could speed up the process by how ever many I feel like working with...

So is there a way to execute a statement (sp or function) and go to the next statement without waiting for the first to finish??



Thanks Big Time... I hope this is possible.

OH.... SQL 2000 SP4 on Windows 2003.

View 16 Replies View Related

Stored Procedur NOT NULL

Jan 3, 2008

In my page there is 5 textbox. User must write data in first three textbox . When the user do not write anything in 4 and 5. textbox, null value insert in db.ALTER PROCEDURE dbo.new_inquiry
 
(@ inquiryHeader varchar(250),
@ inquiry1 varchar(50),@ inquiry2 varchar(50),
@ inquiry3 varchar(50),@ inquiry4 varchar(50),
@ inquiry5 varchar(50),@ inquiryDate datetime
 
)
 
AS
SET NOCOUNT ON
DECLARE @ inquiryID int,
@Err int
 
BEGIN
BEGIN TRANSACTION
 INSERT INTO tbl inquiry
(
 inquiryHeader,
 inquiryDate,
 
)
VALUES
(
@inquiryHeader ,
@inquiryDate
 
 
)
SELECT @inqueryID = SCOPE_IDENTITY(),
@Err = @@ERROR
 
 IF ( @Err = 0 )
BEGININSERT INTO tblInqeryOption
(
inqueryID,
inqueryOption
 
 
)
VALUES
(
@inqueryID,
@inquery1
 
 
)SELECT @Err = @@Error
ENDIF ( @Err = 0 )
BEGININSERT INTO tblInqeryOption
(
inqueryID,
inqueryOption
 
 
)
VALUES
(
@inqueryID,
@inquery2
 
 
)SELECT @Err = @@Error
ENDIF ( @Err = 0 )
BEGIN
 INSERT INTO tblInqeryOption
(
inqueryID,
inqueryOption
 
 
)
VALUES
(
@inqueryID,
@inquery3
 
 
)SELECT @Err = @@Error
ENDIF ( @Err = 0 AND ( @inquey4 IS NOT NULL ) )
BEGIN
 INSERT INTO tblInqeryOption
(
inqueryID,
inqueryOption
 
 
)
VALUES
(
@inqueryID,
@inquery4
 
 
)SELECT @Err = @@Error
ENDIF ( @Err = 0 AND (@anketSecenek5 IS NOT NULL) )
BEGIN
SELECT @Err = @@ErrorINSERT INTO tblInqeryOption
(
inqueryID,
inqueryOption
 
 
)
VALUES
(
@inqueryID,
@inquery5
 
 
)
 
ENDIF @Err <> 0
ROLLBACK TRANSACTION
ELSE
COMMIT TRANSACTION
ENDSET NOCOUNT OFF
RETURN

View 3 Replies View Related

How To Execute DBCC Statements Through Remote Stored Procedures

Jan 23, 2004

Hello,

Is it possible to execute DBCC statements remotely in destination servers through stored procedures existing in source server.

I don’t want to use isql, osql, openquery, openresultset because I have to pass user id or password.

I have linked the required SQL servers using Linked servers.

If so please give some example.

Thanks in Advance,
Sateesh

View 9 Replies View Related

Using EXECUTE Statements Calling An Extended Stored Procedures From Function..

Apr 29, 2004

Hi, all
I'm using Sql server 2000
I want to make select statement dynamically and return table using function.
in sp, I've done this but, in function I don't know how to do so.
(I have to create as function since our existing API..)

Following is my tials...
1.
alter Function fnTest
( @fromTime datetime, @toTime datetime)
RETURNS Table
AS

RETURN Exec spTest @from, @to
GO

Yes, it give syntax error..

2. So, I found the following


From Sql Server Books Online, Remark section of CREATE FUNCTION page of Transact-SQL Reference , it says following..

"The following statements are allowed in the body of a multi-statement function. Statements not in this list are not allowed in the body of a function: "
.....
* EXECUTE statements calling an extended stored procedures.

So, I tried.

alter Function fnTest
( @fromTime datetime, @toTime datetime)
RETURNS Table
AS

RETURN Exec master..xp_msver
GO

It doesn't work... syntax err...

Here I have quick question.. How to execute statements calling an extended stored procedures. any examples?


Now, I'm stuck.. how can I create dynamic select statement using function?

I want to know if it's possible or not..

View 13 Replies View Related

Transact SQL :: GO Statements To Execute Large Stored Procedure In Batches

Jun 19, 2015

I want to include GO statements to execute a large stored procedure in batches, how can I do that?

View 9 Replies View Related

IsNull() Works In Query But Not In Stored Procedur

May 29, 2007

Hi,

I'm using IsNULL(<insert something SQL witty here>) to zero out a derived column if there's no return result. When I submit my query in Management Console the results come back perfectly, when I send it over as a stored procedure (as an alter or create) then execute, my last few columns come back 0 not populated as in the query run. Anyone know why this happens?

View 9 Replies View Related

Need A SqlServer Stored Procedur To Check Login Credentials

Mar 10, 2006

Sid writes "Hi,
can anybody plz provide me the stored procedure for checking the credentials(uid,Pwd) of a login page in sqlserver.

Thanks,
Sid."

View 2 Replies View Related

Multiple Statements In Stored Procedure

Apr 29, 2008

I believe we can you multiple statements in stored procedures?

Suppose I have a stored procedure and I pass parameters to this SP.
What I am aiming for is to pass some values to the stored procedure, use a select statement to retrieve some values, then have two update statements as below. Updating the same table but with opposite values, both passed as a parameter and retrived, as given below:

CREATE sp_temp_proc
@order_id int,
@order_position int,
@temp_order_id OUTPUT
@temp_order_position OUTPUT,

SELECT order_id AS temp_order_id
FROM <TABLE> WHERE order_position < @order_position

@temp_order_id = temp_order_id


UPDATE <TABLE> SET order_position = @order_position WHERE order_id =
@temp_order_id

UPDATE <TABLE> SET order_position = @temp_order_position WHERE order_id = @order_id

View 2 Replies View Related

Multiple SQL Statements In A Stored Procedure

Jul 23, 2005

Hi!I got 2 stored procedure, proc1 executes proc2,proc2 does some updates and inserts on different tables ...proc1:ALTER PROCEDUREASexecute proc2SELECT * FROM tblFoo______________________my problem is, that when executing proc1, I receive the message:"THE SP executed successfully, but did not return records!"But I need the resultset from "SELECT * FROM tblFoo" that is executedat the end of proc1.I'm not sure, but I think that I solved a similira problem with "setnocount on", I put it into both SP, but it's still the same ... noresultset ...How can I display "SELECT * FROM tblFoo" within a SP, where SQLstatements are executed before?!Thank you!

View 1 Replies View Related

Stored Procedure With Multiple Update Statements

Jan 31, 2008

I have a SP that has the correct syntax. However when I run my web-app it gives me this error: "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. "
 The procedure takes in three parameters and retrieves 23 values from the DB to display on my form.
Any ideas?
 

View 4 Replies View Related

Multiple Select Statements + Stored Procedure

Aug 9, 2007



Hi all,

I have 2 select statements in my Stored Proc.

I want to display the results of each query in my DataGridView.

However, only the data of the last select query is returned.

Why is this?

Thanks.

View 7 Replies View Related

Stored Procedure With Multiple Select Statements And SQLDataSource

May 24, 2007

I have created a stored procedure with multiple select statements using MSSQL 2000. When I connect to this using a SQLDataSource it only seems to get the first SELECT. I need to access the multiple tables returned by the stoped procedure. Can anyone point me in the dirrection of how to do this.ThanksClearz 

View 3 Replies View Related

Multiple Select Statements In Single Stored Proc

May 19, 2008



Hi,

I have used several sql queris to generate a report. This queries pull out data from different tables. But sometimes at the same table too.
Basically those are SELECT statements.
I have created stored proc for each SELECT statement. now I'm wondering can I include all SELECT statements in one stored proc and run the report.
If possible, can anyone show me the format?

Thanks

View 4 Replies View Related

Returning And Reading Multiple Select Statements From One Stored Procedure

Dec 3, 2006

Hey Guys. I’m having a little trouble and was wondering if you could help me out. I’m trying to create a custom paging control, so I create a stored procedure that returns the appropriate records as well as the total amount of records. And that works fine. What I’m having problems with is reading the data from the second select statement within the code. Anyone have any idea on how to do this? Also.. how can I check how many tables were returned?
Here's my code. I'm trying to keep it very generic so I can send it any sql statement:public DataTable connect(string sql)
{
DataTable dt = new DataTable();

SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ToString());
SqlDataAdapter SqlCmd = new SqlDataAdapter(sql, SqlCon);
System.Data.DataSet ds = new System.Data.DataSet();
SqlCmd.Fill(ds);

dt = ds.Tables[0];

//Here's where I don't know how to access the second select statement

return dt;
}  Here's my stored procedure:
 ALTER PROCEDURE dbo.MyStoredProcedure
(
@Page int,
@AmountPerPage int,
@TotalRecords int output
)

AS


WITH MyTable AS
(

Select *, ROW_NUMBER() OVER(ORDER BY ID Desc) as RowNum
From Table
where Deleted <> 1
)


select * from MyTable
WHERE RowNum > (((@Page-1)*@AmountPerPage)) and RowNum < ((@Page*@AmountPerPage)+1);

Select @TotalRecords = COUNT(*)
from Table
where Deleted <> 1
RETURN

Thanks

View 3 Replies View Related

SQL 2012 :: Select Statements And Ended Up Seeing Multiple Cached Instances Of Same Stored Procedure

Nov 24, 2014

I ran the below 2 select statements and ended up seeing multiple cached instances of the same stored procedure. The majority have only one cached instance but more than a handful have multiple cached instances. When there are multiple cached instances of the same sproc, which one will sql server reuse when the sproc is called?

SELECT o.name, o.object_id,
ps.last_execution_time ,
ps.last_elapsed_time * 0.000001 as last_elapsed_timeINSeconds,
ps.min_elapsed_time * 0.000001 as min_elapsed_timeINSeconds,
ps.max_elapsed_time * 0.000001 as max_elapsed_timeINSeconds

[code]...

View 4 Replies View Related

How To Execute A Stored Procedure With Multiple Parameters In VB

Aug 3, 2012

Here is my stored procedure:

ALTER PROCEDURE dbo.SP_UpdateFixedRev
/*
(
@parameter1 int = 5,
@parameter2 datatype OUTPUT
)
*/
(
@Number int,
@FixedRev money
)
AS
BEGIN
/* SET NOCOUNT ON */
Update Ticket set FixedRev = @FixedRev where Number = @Number;
End

Here is my code:

Dim dbConn As New OleDbConnection
Dim dbComm As OleDbCommand
dbConn.ConnectionString = connStr 'connStr is class-level vrbl
dbConn.Open()
dbComm = dbConn.CreateCommand
dbComm.Parameters.Add("@Number", OleDbType.Integer).Value = txtDatabaseTicketNo.Text
dbComm.Parameters.Add("@FixedRev", OleDbType.Currency).Value = txtFixedRev.Text
dbComm.CommandText = "SP_UpdateFixedRev"
dbComm.CommandType = CommandType.StoredProcedure
dbComm.ExecuteNonQuery()
dbConn.Close()

However its not updating my database when I run the app from a button click event.

View 7 Replies View Related

DTS - Using Multiple Stored Procedures In One Execute SQL Task

Jan 3, 2008

I'm running this legacy DTS package under SQL Server 2005, and need to make some changes.

I have some (say, 3) stored procedures, and they all have one same parameter. Each SP returns a dataset. I need to import each dataset to a table using DTS. Both the SPs and the destination tables are in the same database.


So, I created an "Execute SQL Task" and typed in "SQL Statement" something like this:


INSERT INTO TABLE TABLE1
EXEC SP1 ?
GO
INSERT INTO TABLE TABLE2
EXEC SP2 ?
GO
INSERT INTO TABLE TABLE3
EXEC SP3 ?
GO


And the execution returns an error: No value given for one or more required parameters.


Is it possible to assign a parameter to all three SPs? What is the work out if I don't want to change the SPs, and I don't want to create 3 Execute SQL Tasks?

View 4 Replies View Related

SQL Server Admin 2014 :: Estimated Query Plan For A Stored Procedure With Multiple Query Statements

Oct 30, 2015

When viewing an estimated query plan for a stored procedure with multiple query statements, two things stand out to me and I wanted to get confirmation if I'm correct.

1. Under <ParameterList><ColumnReference... does the xml attribute "ParameterCompiledValue" represent the value used when the query plan was generated?

<ParameterList>
<ColumnReference Column="@Measure" ParameterCompiledValue="'all'" />
</ParameterList>
</QueryPlan>
</StmtSimple>

2. Does each query statement that makes up the execution plan for the stored procedure have it's own execution plan? And meaning the stored procedure is made up of multiple query plans that could have been generated at a different time to another part of that stored procedure?

View 0 Replies View Related

Execute Statements In Order

Apr 13, 2006

Dear friends,

I am using query analyzer to build a database,
I want to do certain command in order, that is: not to execute the next statement until the previous one has been finish execution.
What is the command used for this purpose

Thanks for your valuable help

View 13 Replies View Related

Backup DB To Insert Statements And Execute On A Different Db

Jan 22, 2008

Hi all,

I am looking to transfer a database to another db but I just need to copy the data (not drop the tables and recreate them). Is this possible?

I was thinking of backing up the database in a set of insert statements in a file and execute this file to get the desired result. Or alternatively, to use a data flow task with multiple tables if possible.

Hope there is a way.

Thanks,
Yannis

View 22 Replies View Related

Transact SQL :: Transaction Count After EXECUTE Indicates Mismatching Number Of BEGIN And COMMIT Statements

Aug 19, 2015

I am getting an exception. And i don't know whether this exception is from the C# coding or SQL SERVER."Cannot roll back InsertRxs. No transaction or savepoint of that name was found.Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.A transaction that was started in a MARS batch is still active at the end of the batch. The transaction is rolled back."

View 2 Replies View Related

SQL Server 2012 :: Transaction Count After EXECUTE Indicates Mismatching Number Of BEGIN And COMMIT Statements

Oct 23, 2015

I'm all of a sudden getting this error on a Stored Procedure that has not been touched since it was created.

Msg 266, Level 16, State 2, Procedure usp_ArchivexactControlPoint, Line 0
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.

CREATE PROCEDURE [dbo].[usp_ArchivexactControlPoint]
AS
DECLARE @TableName VARCHAR (50)

[Code] ...

View 2 Replies View Related

How To Do Multiple If Statements

Oct 11, 2015

I want the below sql code to force a error if it falls on a saturday or sunday, and there are no rows in the OrderTrans table for the previous day (TransDate) but not sure how to do multiple if statements.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[OrderTrans](
[OrderId] [int] NOT NULL,

[Code] ....

View 0 Replies View Related

Using Transactions With Multiple SQL Statements

Oct 31, 2006

I am writing a fairly complex data automation procedure that basically uses about 5 stored procedures and some additional sql from C# to populate a database. i would like to utilize transactions in C# and sql to help me if something goes wrong.  My question is, do i have to maintain the same connection in order to have one transaction for all my Commands.  right now i do things like connection.Open();Command.ExecuteNonQuery(); connection.Close(); connection.Open();Command2.ExecuteNonQuery(); connection.Close(); i think i have to keep the same connection open for the duration of all my commands in order to utilize transactions, is this correct? thanks, mcm

View 5 Replies View Related

USING MULTIPLE SELECT STATEMENTS

Apr 23, 2008

how can take codes below and put them into one store procedure to supplie a gridview. also i will like to define the row name on the left like i did to the column on the top using the 'AS'
 Code1....
SELECT
SUM(CASE WHEN Month = 'January' THEN 1 ELSE 0 END) AS January, SUM(CASE WHEN Month = 'February' THEN 1 ELSE 0 END) AS February,
SUM(CASE WHEN Month = 'March' THEN 1 ELSE 0 END) AS March, SUM(CASE WHEN Month = 'April' THEN 1 ELSE 0 END) AS April,
SUM(CASE WHEN Month = 'May' THEN 1 ELSE 0 END) AS May, SUM(CASE WHEN Month = 'June' THEN 1 ELSE 0 END) AS June,
SUM(CASE WHEN Month = 'July' THEN 1 ELSE 0 END) AS July, SUM(CASE WHEN Month = 'August' THEN 1 ELSE 0 END) AS August,
SUM(CASE WHEN Month = 'September' THEN 1 ELSE 0 END) AS September, SUM(CASE WHEN Month = 'October' THEN 1 ELSE 0 END) AS October,
SUM(CASE WHEN Month = 'November' THEN 1 ELSE 0 END) AS November, SUM(CASE WHEN Month = 'December' THEN 1 ELSE 0 END) AS December,
SUM(CASE WHEN site_descr = 'SITE1' THEN 1 ELSE 0 END) AS AllTotal
FROM dbo.V_results
WHERE (site_descr = 'SITE1')
 
Code2.....
 
SELECT
SUM(CASE WHEN Month = 'January' THEN 1 ELSE 0 END) AS January, SUM(CASE WHEN Month = 'February' THEN 1 ELSE 0 END) AS February,
SUM(CASE WHEN Month = 'March' THEN 1 ELSE 0 END) AS March, SUM(CASE WHEN Month = 'April' THEN 1 ELSE 0 END) AS April,
SUM(CASE WHEN Month = 'May' THEN 1 ELSE 0 END) AS May, SUM(CASE WHEN Month = 'June' THEN 1 ELSE 0 END) AS June,
SUM(CASE WHEN Month = 'July' THEN 1 ELSE 0 END) AS July, SUM(CASE WHEN Month = 'August' THEN 1 ELSE 0 END) AS August,
SUM(CASE WHEN Month = 'September' THEN 1 ELSE 0 END) AS September, SUM(CASE WHEN Month = 'October' THEN 1 ELSE 0 END) AS October,
SUM(CASE WHEN Month = 'November' THEN 1 ELSE 0 END) AS November, SUM(CASE WHEN Month = 'December' THEN 1 ELSE 0 END) AS December,
SUM(CASE WHEN site_descr = 'SITE2' THEN 1 ELSE 0 END) AS AllTotal
FROM dbo.V_results
WHERE (site_descr = 'SITE2')
 
 thanks in advance

View 10 Replies View Related

Multiple SQL Statements In One SQLCommand

Oct 3, 2005

I am just wondering if it is possible using SQL Server 2000 to have multiple SQL Statements executed with one sqlComm.ExecuteNonQuery(); call?

View 1 Replies View Related

Multiple Select Statements

Dec 22, 2005

Hi guys and gals,
I am trying to create a select statement that will return an INT that I will later have to use in another select statement. I have the following code, however, I keep getting an error that says:
'Error116: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.'
My Code is below:
//Start of sql
CREATE PROCEDURE ADMIN_GetSingleUsers( @userID  int) AS
DECLARE @userSQL intSET @userSQL = (SELECT User_ID, TITLE.TITLE AS TITLE,    Cast(Users.Active as  varchar(50)) as Active,   Cast(Users.Approved as  varchar(50)) as Approved,   Users.Unit_ID As usersUnitID,   *    From TITLE, Users   WHERE    User_ID = @userID AND   TITLE.TITLE_ID = Users.Title_ID )
Select Unit_ID, Parent_ID, Unit_Name from UNITS WHERE Unit_ID = @userSQL
//End of sql
Can you point to what I am doing wrong? Thanks in advance!

View 4 Replies View Related

Multiple Case Statements

Mar 14, 2008

This query brings back 2 rows for each record, one for each case statement. How can I change this to bring in the contsupp.notes for both types of data? Or could it be fixed in the joins?

select
contact1.accountno,
contact1.key5 as "Ch#",
contact2.uexpsort as "Sort",
contact1.company as "Church",
contact1.contact as "Editor",
contact1.phone1 as "Phone",
contact2.uemerg as "Emergency",
contact1.Address1 as "Address",
contact1.city as "City",
contact1.state as "State",
contact1.zip as "Zip",
contact2.ubulletnqt as "Qty",
contact2.ubullcolor as "BullColor",
contact2.ubarcode as "Barcode",
contact2.udelivery as "Delivery",
contact2.uoutputdev as "OutputDev",
contact2.utimedeliv as "Time",
contact2.ucolor as "DelivColor",
contact2.ucollated as "Collated",
contact2.ustapled as "Stapled",
case when contsupp.contsupref = 'Delivery Notes' then contsupp.notes end as "Deliverynotes",
case when contsupp.contsupref = 'Cover Change Slip' then contsupp.notes end as "CoverChangeSlip"

from
Contact1 inner join contact2 on Contact1.Accountno = Contact2.Accountno
inner join contsupp on Contact1.Accountno=Contsupp.Accountno
where
contact1.key5 not like '' and contsupp.contsupref='Delivery Notes' or contsupp.contsupref ='Cover Change Slip' order by contact1.key5

Thanks for your help

View 2 Replies View Related

CTE With Multiple Update Statements?

Sep 19, 2006

HI Gurus

I have written one CTE (common table expression) and trying to use same CTE with three seperate UPDATE statements which gives me error saying "Invalid Object name" (it works fine when I try to use with 1 update statement (any one from three update statements)



Isnt it possible that I can use 1 CTE with mutiple update statements?



waiting for your reply....

View 4 Replies View Related

Multiple MDX Statements In A Report

Aug 28, 2007

Does anyone know how to execute more than one MDX statement in a single report? For example, If you wanted to create a session set, run some mdx with the set included, then drop the session set. In Management studio the mdx works perfectly if you separate the individual mdx statements with GO. I tried using semicolons as mdx statement terminators and this didn't work either.

Reporting Services does something between when the report begins it's execution and the time the MDX is submitted to AS. And running a trace to see exactly what is passed in doesn't work either - the only message displayed is the same error message as what is passed back to RS. (I ran a trace with all events selected).

Anyone have any ideas?

Thank you in advance,
John

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved