Running Stored Procedure Within A Stored Procedure
May 9, 2008
I have a custom built users table for storing some values and I am also utilizing the aspnet_Users table. I want to delete a user from my users tables then execute the aspnet_Users_DeleteUser sproc and pass into the stored procedure the username of the user to delete because the DeleteUser method requires this. When I execute the command from within my asp.net web application I get the exception below. Both values are being obtained from the asp.net application and are represented in my DAL that is also below. Any thoughts as to why I am receiving this exception? Thanks.
Procedure or function 'aspnet_Users_DeleteUser' expects parameter '@UserName', which was not supplied.
public static bool DeleteUser(int userID, string username)
{int result = 0;using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
SqlCommand myCommand = new SqlCommand("Users_DeleteUser", myConnection);myCommand.CommandType = CommandType.StoredProcedure;
Hi all - I'm trying to optimized my stored procedures to be a bit easier to maintain, and am sure this is possible, not am very unclear on the syntax to doing this correctly. For example, I have a simple stored procedure that takes a string as a parameter, and returns its resolved index that corresponds to a record in my database. ie exec dbo.DeriveStatusID 'Created' returns an int value as 1 (performed by "SELECT statusID FROM statusList WHERE statusName= 'Created') but I also have a second stored procedure that needs to make reference to this procedure first, in order to resolve an id - ie: exec dbo.AddProduct_Insert 'widget1' which currently performs:SET @statusID = (SELECT statusID FROM statusList WHERE statusName='Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID) I want to simply the insert to perform (in one sproc): SET @statusID = EXEC deriveStatusID ('Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID) This works fine if I call this stored procedure in code first, then pass it to the second stored procedure, but NOT if it is reference in the second stored procedure directly (I end up with an empty value for @statusID in this example). My actual "Insert" stored procedures are far more complicated, but I am working towards lightening the business logic in my application ( it shouldn't have to pre-vet the data prior to executing a valid insert). Hopefully this makes some sense - it doesn't seem right to me that this is impossible, and am fairly sure I'm just missing some simple syntax - can anyone assist?
I executed them and got the following results in SSMSE: TopSixAnalytes Unit AnalyteName 1 222.10 ug/Kg Acetone 2 220.30 ug/Kg Acetone 3 211.90 ug/Kg Acetone 4 140.30 ug/L Acetone 5 120.70 ug/L Acetone 6 90.70 ug/L Acetone ///////////////////////////////////////////////////////////////////////////////////////////// Now, I try to use this Stored Procedure in my ADO.NET-VB 2005 Express programming: //////////////////--spTopSixAnalytes.vb--///////////
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlConnection As SqlConnection = New SqlConnection("Data Source = .SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = ssmsExpressDB;")
Dim sqlDataAdapter As SqlDataAdapter = New SqlDataAdaptor("[spTopSixAnalytes]", sqlConnection)
'Pass the name of the DataSet through the overloaded contructor
'of the DataSet class.
Dim dataSet As DataSet ("ssmsExpressDB")
sqlConnection.Open()
sqlDataAdapter.Fill(DataSet)
sqlConnection.Close()
End Sub
End Class ///////////////////////////////////////////////////////////////////////////////////////////
I executed the above code and I got the following 4 errors: Error #1: Type 'SqlConnection' is not defined (in Form1.vb) Error #2: Type 'SqlDataAdapter' is not defined (in Form1.vb) Error #3: Array bounds cannot appear in type specifiers (in Form1.vb) Error #4: 'DataSet' is not a type and cannot be used as an expression (in Form1)
Please help and advise.
Thanks in advance, Scott Chang
More Information for you to know: I have the "ssmsExpressDB" database in the Database Expolorer of VB 2005 Express. But I do not know how to get the SqlConnection and the SqlDataAdapter into the Form1. I do not know how to get the Fill Method implemented properly. I try to learn "Working with SELECT Statement in a Stored Procedure" for printing the 6 rows that are selected - they are not parameterized.
I am trying to upload an excel file into a sql server database. I uploading the spreadsheet from an asp.net page and then running the dts froma stored procedure. But it doesn't work, I am totally lost on what I am doing wrong. Any help would be greatly appreciated.
Asp.net code;
Dim oCmd As SqlCommand
oCmd = New SqlCommand("exportData", rtConn) oCmd.CommandType = CommandType.StoredProcedure rtConn.Open()
With oCmd .CommandType = CommandType.StoredProcedure Response.write("CommandType.StoredProcedure") End With
Try oCmd.ExecuteNonQuery() Response.write("ExecuteNonQuery") Finally rtConn.Close() End Try
StoredProcedure;
CREATE PROCEDURE exportData AS Exec master..xp_cmdshell 'DTSRUN /local/DTS_ExamResults' GO
I have some code that I need to run every quarter. I have many that are similar to this one so I wanted to input two parameters rather than searching and replacing the values. I have another stored procedure that's executed from this one that I will also parameter-ize. The problem I'm having is in embedding a parameter in the name of the called procedure (exec statement at the end of the code). I tried it as I'm showing and it errored. I tried googling but I couldn't find anything related to this. Maybe I just don't have the right keywords. what is the syntax?
CREATE PROCEDURE [dbo].[runDMQ3_2014LDLComplete] @QQ_YYYY char(7), @YYYYQQ char(8) AS begin SET NOCOUNT ON; select [provider group],provider, NPI, [01-Total Patients with DM], [02-Total DM Patients with LDL],
I'm having problems running a stored procedure, I'm getting an error that I don't understand. My procedure is this:
ALTER PROC sp_get_allowed_growers @GrowerList varchar(500) AS BEGIN SET NOCOUNT ON
DECLARE @SQL varchar(600)
SET @SQL = 'SELECT nu_code, nu_description, nu_master FROM nursery WHERE nu_master IN (' + @GrowerList + ') ORDER BY nu_code ASC'
EXEC(@SQL) END GO
and the code I'm using to execute the procedure is this:
public DataSet GetGrowers(string Username) { System.Text.StringBuilder UserRoles = new System.Text.StringBuilder(); UsersDB ps = new UsersDB(); SqlDataReader dr = ps.GetRolesByUser(Username); while(dr.Read()) { UserRoles.Append(dr["RoleName"]+","); } UserRoles.Remove(UserRoles.Length-1,1); //Create instance of Connection and Command objects SqlConnection transloadConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionStringTARPS"]); SqlDataAdapter transloadCommand = new SqlDataAdapter("sp_get_allowed_growers",transloadConnection); //Create and fill the DataSet SqlParameter paramList = new SqlParameter("@GrowerList",SqlDbType.VarChar); paramList.Value = UserRoles.ToString(); transloadCommand.SelectCommand.Parameters.Add(paramList); DataSet dsGrowers = new DataSet(); transloadCommand.Fill(dsGrowers); return dsGrowers;
}
The UserRoles stringbuilder has an appropriate value when it is passed to the stored procedure. When I run the stored procedure in query analyser it runs just fine. However, when I step through the code above, I get the following error:
Line 1: Incorrect syntax near 'sp_get_allowed_growers'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'sp_get_allowed_growers'.
The MsgBox pops up indicating that the Stored Procedure has run, and there are no errors produced by either SQL Server or Access. However, when I inspect the results of the Stored Procedure, it has not processed all the records it should have. It appears to stop processing after between 6 and 11 records out of a total of 50. The wierd thing is that if I execute the procedure on the server manually, it works perfectly. HELP ME IF U CAN ! THANKS.
hi, i'm using SQL server 2000. i'm getting the below error when i run a store procedure. "Specified column precision 500 is greater than the maximum precision of 38." I have created a temporary table inside the stored procedure inserting the values by selecting the fields from other table. mostly i have given the column type as varchar(50) and some fields are numeric(50).
We have a stored procedure which is running fine on a SQL server 2000 from Query Analyzer. However, when we try to execute the same stored procedure from ADO.NET in an executable, the execution is hung or takes extremely long. Does anyone have any ideas or suggestions about how it could happen and how to fix. thanks
I'm not sure if this is really the right place for this but it is related to my earlier post. Please do say if you think I should move it.
I created a Stored procedure which I want to run from Visual basic (I am using 2008 Express with SQL Sever 2005 Express)
I have looked through many post and the explaination of the sqlConection class on the msdn site but I am now just confussed.
Here is my SP
ALTER PROCEDURE uspSelectBarItemID2
(
@BarTabID INT,
@DrinkID INT,
@ReturnBarItemID INT OUTPUT
)
AS
BEGIN
SELECT @ReturnBarItemID = barItemID
FROM [Bar Items]
WHERE (BarTabID = @BarTabID) AND (DrinkID = @DrinkID)
END
In VB I want to pass in the BarTabID and DrinkID varibles (Which Im grabbing from in as int variables) to find BarItemID in the same table and return it as an int.
What I dont understand is do I have to create a unique connection to my database because it is already liked with a dataset to my project with a number of BindingSources and TableAdapters.
Is there an easier way, could I dispense with SP and just use SQL with the VB code, I did think the SP would be neater.
HI all, I'd like to run a simple stored procedure on the Event of a button click, for which I don't need to pass any parameters, I am aware how to run a Stored Procedure with parameters, but I don't know how without, any help would be appreciated please.thanks.
I’m binding the distinct values from each of 9 columns to 9 drop-down-lists using a stored procedure. The SP accepts two parameters, one of which is the column name. I’m using the code below, which is opening and closing the database connection 9 times. Is there a more efficient way of doing this? newSqlCommand = New SqlCommand("getDistinctValues", newConn)newSqlCommand.CommandType = CommandType.StoredProcedure Dim ownrParam As New SqlParameter("@owner_id", SqlDbType.Int)Dim colParam As New SqlParameter("@column_name", SqlDbType.VarChar)newSqlCommand.Parameters.Add(ownrParam)newSqlCommand.Parameters.Add(colParam) ownrParam.Value = OwnerID colParam.Value = "Make"newConn.Open()ddlMake.DataSource = newSqlCommand.ExecuteReader()ddlMake.DataTextField = "distinct_result"ddlMake.DataBind()newConn.Close() colParam.Value = "Model"newConn.Open()ddlModel.DataSource = newSqlCommand.ExecuteReader()ddlModel.DataTextField = "distinct_result"ddlModel.DataBind()newConn.Close() and so on for 9 columns…
Hi, I'm running a CLR stored procedure through my web using table adapters as follows: res = BLL.contractRateAdviceAdapter.AutoGenCRA() 'with BLL being the business logic layer that hooks into the DAL containing the table adapters. The AutoGen stored procedure runs fine when executed directly from within Management Studio, but times out after 30 seconds when run from my application. It's quite a complex stored procedure and will often take longer than 30 seconds to complete. The stored procedure contains a number of queries and updates which all run as a single transaction. The transaction is defined as follows: ---------------------------------------------------------------------------------------------------------------------- options.IsolationLevel = Transactions.IsolationLevel.ReadUncommittedoptions.Timeout = New TimeSpan(1, 0, 0) Using scope As New TransactionScope(TransactionScopeOption.Required, options) 'Once we've opened this connection, we need to pass it through to just about every 'function so it can be used throughout. Opening and closing the same connection doesn't seem to work 'within a single transactionUsing conn As New SqlConnection("Context Connection=true") conn.Open() ProcessEffectedCRAs(dtTableInfo, arDateList, conn) scope.Complete() End Using End Using ---------------------------------------------------------------------------------------------------------------------- As I said, the code encompassed within this transaction performs a number of database table operations, using the one connection. Each of these operations uses it's own instance of SQLCommand. For example: ----------------------------------------------------------------------------------------------------------------------Dim dt As DataTable Dim strSQL As StringDim cmd As New SqlCommand cmd.Connection = conn cmd.CommandType = CommandType.Text cmd.CommandTimeout = 0Dim rdr As SqlDataReaderstrSQL = "SELECT * FROM " & Table cmd.CommandText = strSQL rdr = cmd.ExecuteReader SqlContext.Pipe.Send(rdr) rdr.Close() ---------------------------------------------------------------------------------------------------------------------- Each instance of SQLCommand throughout the stored procedure specifies cmd.CommandTimeout = 0, which is supposed to be endless. And the fact that the stored procedure is successful when run directly from Management studio indicates to me that the stored procedure itself is fine. I also know from output messages that there is no issues with the database connection. I've set the ASP.Net configuration properties in IIS accordingly. Are there any other settings that I need to change? Can I set a timeout property when I'm calling the stored procedure in the first place? Any advice would be appreciated.
I am new to ASP.NET so please excuse what may seem like a dumb question. I have a stored procedure that I need to run when the user clicks on our submit button. I am using Visual Studio 2005 and thought I could use the SqlDataSOurce Control. IS it possible to us the control or do I need to create a connection and call the stored procedure in the the button_click sub? Thanks in advance MF
Hi all, I wonder if you can help me with this. Basically, Visual Web Developer doesn't like this part of my code despite the fact that the stored procedure has been created in MS SQL. It just won't accept that bold line in the code below and even when I comment it just to cheat, it still gives me an error about the Stored Procedure. Here's the line of code: // Define data objects SqlConnection conn; SqlCommand comm; // Initialize connection string connectionString = ConfigurationManager.ConnectionStrings[ "pay"].ConnectionString; // Initialize connection conn = new SqlConnection(connectionString); // Create command comm = new SqlCommand("UpdatePaymentDetails", conn); //comm.CommandType = CommandType.StoredProcedure; // Add command parameters comm.Parameters.Add("PaymentID", System.Data.SqlDbType.Int); comm.Parameters["PaymentID"].Value = paymentID; comm.Parameters.Add("NewPayment", System.Data.SqlDbType.VarChar, 50); comm.Parameters["NewPayment"].Value = newPayment; comm.Parameters.Add("NewInvoice", System.Data.SqlDbType.VarChar, 50); comm.Parameters["NewInvoice"].Value = newInvoice; comm.Parameters.Add("NewAmount", System.Data.SqlDbType.Money); comm.Parameters["NewAmount"].Value = newAmount; comm.Parameters.Add("NewMargin", System.Data.SqlDbType.VarChar, 50); comm.Parameters["NewMargin"].Value = newMargin; comm.Parameters.Add("NewProfit", System.Data.SqlDbType.Money); comm.Parameters["NewProfit"].Value = newProfit; comm.Parameters.Add("NewEditDate", System.Data.SqlDbType.DateTime); comm.Parameters["NewEditDate"].Value = newEditDate; comm.Parameters.Add("NewQStatus", System.Data.SqlDbType.VarChar, 50); comm.Parameters["NewQStatus"].Value = newQStatus; comm.Parameters.Add("NewStatus", System.Data.SqlDbType.VarChar, 50); comm.Parameters["NewStatus"].Value = newStatus; // Enclose database code in Try-Catch-Finally try { conn.Open(); comm.ExecuteNonQuery(); }
I have a table with information about a mobile account in one table, a table for mobile plans, and a table for planfeatures. Each mobile account is associated with a planid, and may be associated with any combination of the features associated with that plan. The plan features are stored in a bridgetable which contains 'invoicedate' (date stamped on the invoice in question), 'subaccountnumber' (the cell phone number), 'planid', and 'featureid'. I've tested the UpdateMobileFeature sp directly from the SQL Profiler--it works fine on it's own. I use a stored procedure to fill the mobile table (called from aspx page), and since I use three of the four columns written above for both the mobilesub and the mobilefeature tables, I tried just adding the parameter which holds the featureid's to the sp to update the mobilesub table. Then I call the UpdateMobileFeature sp from the updatemobile sp. (The code in mobilesub that is not calling UpdateMobileDetail works well). All seems to work fine--nothing crashes or anything, but nothing is being added to the mobilefeature table. Here is the code:CREATE procedure usp_updatemobile( @InvoiceDate smalldatetime, @SubaccountNumber varchar(50), @PlanId int, @FeatureList varchar(500) --added for UpdateMobileFeatures. In the form of a comma-seperated list, to imitate an array. --***irrelevant parameters removed***--) as exec dbo.UpdateMobileFeature '@InvoiceDate','@SubaccountNumber','@PlanId','@FeatureList' --the apparently nonfunctional call if exists ( //select for the mobile row in question ) Begin //update row End Else Begin //insert new row End GOCREATE PROC dbo.UpdateMobileFeatures( @InvoiceDate smalldatetime, @SubaccountNumber varchar(50), @PlanID int, @FeatureList varchar(500))ASBEGIN SET NOCOUNT ON CREATE TABLE #TempList ( InvoiceDate smalldatetime, SubaccountNumber varchar(50), PlanID int, FeatureID int ) DECLARE @FeatureID varchar(10), @Pos int SET @FeatureList = LTRIM(RTRIM(@FeatureList))+ ',' SET @Pos = CHARINDEX(',', @FeatureList, 1) IF REPLACE(@FeatureList, ',', '') <> '' BEGIN WHILE @Pos > 0 BEGIN SET @FeatureID = LTRIM(RTRIM(LEFT(@FeatureList, @Pos - 1))) IF @FeatureID <> '' BEGIN INSERT INTO #TempList (InvoiceDate, SubaccountNumber, PlanID, FeatureID) VALUES (@InvoiceDate, @SubaccountNumber, @PlanID, CAST(@FeatureID AS int)) --Use Appropriate conversion END SET @FeatureList = RIGHT(@FeatureList, LEN(@FeatureList) - @Pos) SET @Pos = CHARINDEX(',', @FeatureList, 1) END END --SELECT o.FeatureID, CustomerID, EmployeeID, FeatureDate --FROM dbo.Features AS o -- JOIN -- #TempList t -- ON o.FeatureID = t.FeatureID
Insert Into MobileFeatures Select InvoiceDate, SubaccountNumber, PlanID, FeatureID From #TempList ENDGOHere is the method I used to call the first sp: (also with irrelevant stuff removed)public void saveCurrentMobile() { calculateTotals(); InvoiceDataSet dataset = InvoiceDataSet.GetInstance(); SqlConnection conn = (SqlConnection)Session["connection"]; SqlCommand cmdUpdateMobile; cmdUpdateMobile = new SqlCommand("usp_updatemobile", conn); cmdUpdateMobile.CommandType = CommandType.StoredProcedure; SqlParameter invoicedate = cmdUpdateMobile.Parameters.Add("@InvoiceDate", SqlDbType.SmallDateTime); invoicedate.Value = DateTime.Parse(Request.Params["InvoiceDate"].ToString()); SqlParameter cellnumber = cmdUpdateMobile.Parameters.Add("@SubaccountNumber", SqlDbType.VarChar, 50); cellnumber.Value = txtCellNumber.Text.Trim(); SqlParameter plan = cmdUpdateMobile.Parameters.Add("@PlanId", SqlDbType.Int); plan.Value = planid; SqlParameter featurelist = cmdUpdateMobile.Parameters.Add("@FeatureList", SqlDbType.VarChar, 500); featurelist.Value = planform.FeatureList;
//Response.Write(isthirdparty.ToString()); Response.Write(thirdpartycompany); SqlParameter cycle = cmdUpdateMobile.Parameters.Add("@Cycle", SqlDbType.Int); cycle.Value = Convert.ToInt32(Request.Params["Cycle"]); int returnvalue = runStoredProcedure(cmdUpdateMobile); //the sp is called within this method.
I have a stored procedure being called from Visual Cafe 4.0 that takes over 30 minutes to run. Is there any way to backround this so that control returns to the browser that the JFC Applet is running in? The result set is saved to local disk and an email message sent to the user on completion. Thanks, Dave.
I wrote a Stored Procedure I wish to run as a job. It inserts data to a linked server. The stored procedure runs fine from the sql query analyzer but fails as a job. There are no permissions assigned to this stored procedure as I beleive it runs under the context of sa which has default access granted.
Can someone give me some insite why this stored procedure won't run as a scheduled job?
ALTER PROCEDURE tsul_insertintolinkedserver AS DECLARE @srvname varChar(20) SELECT @srvname = @@servername insert into THOMAS.tsnet.dbo.usagelog select id, tsgroup, account, error, failedpin, type, servername, ipbrowser, cid, logintime, expand , msgspresent, msgslistened, @srvname from usagelog where id > ( select max(id) from THOMAS.tsnet.dbo.usagelog where hostserver = @srvname )
I've come a huge ways with your help and things are getting more and more complicated, but i'm able to figure out a lot of things on my own now thanks to you guys! But now I'm REALLY stuck.
I've created a hierarchal listbox form that drills down From
Product - Colour - Year.
based on the selection from the previous listbox. i want to be able to populate a Grid displaying availability of the selected product based on the selections from the listboxes.
So i've written a stored procedure that selects the final product Id as an INPUT/OUTPUT based on the parameters PRODUCT ID - COLOUR ID - and YEAR ID. This outputs a PRODUCT NUMBER.
I want that product number to be used to populate the grid view. Is there away for me to do this?
I have created a stored procedure for a routine task to be performed periodically in my application. Say, i want to execute my stored procedure at 12:00 AM daily.
How can I add my stored procedure to the SQL server agent jobs??
in my procedure, I want to count the number of rows that have erroredduring an insert statement - each row is evaluated using a cursor, soI am processing one row at a time for the insert. My total count tobe displayed is inside the cursor, but after the last fetch is called.Wouldn't this display the last count? The problem is that the count isalways 1. Can anyone help?here is my code,.... cursor fetchbegin ... cursorif error then:beginINSERT INTO US_ACCT_ERRORS(ERROR_NUMBER, ERROR_DESC, cUSTOMERNUMBER,CUSTOMERNAME, ADDRESS1, ADDRESS2, CITY,STATE, POSTALCODE, CONTACT, PHONE, SALESREPCODE,PRICELEVEL, TERMSCODE, DISCPERCENT, TAXCODE,USERCOMMENT, CURRENCY, EMAILADDRESS, CUSTOMERGROUP,CUSTINDICATOR, DT_LOADED)VALUES(@ERRORNUM, @ERRORDESC,@CUSTOMERNUMBER, @CUSTOMERNAME, @ADDRESS1, @ADDRESS2, @CITY,@STATE, @POSTALCODE, @CONTACT, @PHONE, @SALESREPCODE,@PRICELEVEL, @TERMSCODE, @DISCPERCENT, @TAXCODE,@USERCOMMENT, @CURRENCY, @EMAILADDRESS, @CUSTOMERGROUP,@CUSTINDICATOR, @DTLOADED)SET @ERRORCNT = @ERRORCNT + 1END --error--FETCH NEXT FROM CERNO_US INTO@CUSTOMERNUMBER, @CUSTOMERNAME, @ADDRESS1, @ADDRESS2, @CITY, @STATE,@POSTALCODE, @CONTACT,@PHONE,@SALESREPCODE, @PRICELEVEL,@TERMSCODE,@DISCPERCENT, @TAXCODE, @USERCOMMENT, @CURRENCY,@EMAILADDRESS,@CUSTOMERGROUP, @CUSTINDICATOR, @DTLOADED--IF @ERRORCNT > 0INSERT INTO PROCEDURE_RESULTS(PROCEDURE_NAME, TABLE_NAME, ROW_COUNT,STATUS)VALUES('LOAD_ACCOUNTS', 'LOAD_ERNO_US_ACCT', @ERRORCNT, 'FAILEDINSERT/UPDATE')END -- cursorCLOSE CERNO_USDEALLOCATE CERNO_US
I am running a stored procedure as a job step and in the stored procedure I use return to pass one of several possible values when there is an error in processing (not an system error) so that the job step will fail. However, even when I return a non-zero value using return the job step completes as successful. What should I be doing so that the job step picks up the non-zero value and then indicates the step failed?
I have a stored procedure in SQL 2005 that purges data, and may take a few minutes to run. I'd like to report back to the client with status messages as the sp executes, using PRINT statements or something similar. I imagine something similar to BACKUP DATABASE, where it reports on percentage complete as the backup is executing.
I can't seem to find any information on how to do this. All posts on this subject state that it's not possible; that PRINT data is returned after the procedure executes. However it would seem possible since BACKUP DATABASE, for example, does this.
Is there any way to send status type messages to the client as the sp is executing??
I have a sub that passes values from my form to my stored procedure. The stored procedure passes back an @@IDENTITY but I'm not sure how to grab that in my asp page and then pass that to my next called procedure from my aspx page. Here's where I'm stuck: Public Sub InsertOrder() Conn.Open() cmd = New SqlCommand("Add_NewOrder", Conn) cmd.CommandType = CommandType.StoredProcedure ' pass customer info to stored proc cmd.Parameters.Add("@FirstName", txtFName.Text) cmd.Parameters.Add("@LastName", txtLName.Text) cmd.Parameters.Add("@AddressLine1", txtStreet.Text) cmd.Parameters.Add("@CityID", dropdown_city.SelectedValue) cmd.Parameters.Add("@Zip", intZip.Text) cmd.Parameters.Add("@EmailPrefix", txtEmailPre.Text) cmd.Parameters.Add("@EmailSuffix", txtEmailSuf.Text) cmd.Parameters.Add("@PhoneAreaCode", txtPhoneArea.Text) cmd.Parameters.Add("@PhonePrefix", txtPhonePre.Text) cmd.Parameters.Add("@PhoneSuffix", txtPhoneSuf.Text) ' pass order info to stored proc cmd.Parameters.Add("@NumberOfPeopleID", dropdown_people.SelectedValue) cmd.Parameters.Add("@BeanOptionID", dropdown_beans.SelectedValue) cmd.Parameters.Add("@TortillaOptionID", dropdown_tortilla.SelectedValue) 'Session.Add("FirstName", txtFName.Text) cmd.ExecuteNonQuery() cmd = New SqlCommand("Add_EntreeItems", Conn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@CateringOrderID", get identity from previous stored proc) <------------------------- Dim li As ListItem Dim p As SqlParameter = cmd.Parameters.Add("@EntreeID", Data.SqlDbType.VarChar) For Each li In chbxl_entrees.Items If li.Selected Then p.Value = li.Value cmd.ExecuteNonQuery() End If Next Conn.Close()I want to somehow grab the @CateringOrderID that was created as an end product of my first called stored procedure (Add_NewOrder) and pass that to my second stored procedure (Add_EntreeItems)
I have a stored procedure and in that I will be calling a stored procedure. Now, based on the parameter value I will get stored procedure name to be executed. how to execute dynamic sp in a stored rocedure
at present it is like EXECUTE usp_print_list_full @ID, @TNumber, @ErrMsg OUTPUT
I want to do like EXECUTE @SpName @ID, @TNumber, @ErrMsg OUTPUT
Hi, I need to write a select query that will run all returned results through a separate stored procedure before returning them to me. Something like.... SELECT TOP 10 userid,url,first name FROM USERS ORDER by NEWID() ......and run all the selected userids through a stored procedure like..... CREATE PROCEDURE AddUserToLog (@UserID int ) AS INSERT INTO SelectedUsers (UserID,SelectedOn) VALUES (@UserID,getdate()) Can anyone help me to get these working togethsr in the same qurey?
I've created this stored procedure to run two DTS packages which pull in data from two Excel files. I'd like to supress the Results tab since the results from the DTS packages are fed to it. I'd like to keep the Messages tab visible.
CREATE PROCEDURE [dbo].[ImportHelpDeskTickets] AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON
[Code] ....
For those of you like me who will spend 8 hours trying to figure out how to get this working... Double up on the quotes as shown above. Also, be certain that NT SERVICEMSSQLSERVER has been granted appropriate rights to the folders with the the saved packages and the Excel files. You may also need to download the Access Database Engine.
Keywords: run dts package from stored procedure xp_cmdshell
'C:Program' is not recognized as an internal or external command, operable program or batch file.'