... Executing Stored Procedures In An INSERT Statement ...
Aug 28, 2002
I am trying to simulate the <sequence name>.nextval of oracle in SQL Server 2000.
The situation is that i need to be able to run programmatically INSERT statements. In Oracle I am able to do INSERT INTO TABLE_A (ID, NAME) VALUES (TABLE_A_SEQUENCE.NEXTVAL, 'MIKKO') in a single prepared statement in my code.
I know that to recreate this in SQL Server 2000 I need to create a stored procedure and table to set up a way to generate "the next value" to use in my INSERT. but the schema below forces me to do my insert in 2 steps (first, to get the next value. second, to use that value in the INSERT statement), since I cannot execute the stored procedure inside my INSERT statement.
Is there any way for me to generate values within my INSERT statement that would simulate Oracle's <sequence name>.nextval and allow me to execute my INSERT in 1 line of code?
TABLE
-----
CREATE TABLE sequences (
-- sequence is a reserved word
seq varchar(100) primary key,
sequence_id int
);
MS SQL SERVER STORED PROCEDURE:
-------------------------------
CREATE PROCEDURE nextval
@sequence varchar(100)AS
BEGIN
-- return an error if sequence does not exist
-- so we will know if someone truncates the table
DECLARE @sequence_id int
set @sequence_id = -1
UPDATE sequences
SET @sequence_id = sequence_id = sequence_id + 1
WHERE seq = @sequence
I know that syscomments stores the stored procedures in chunks of 4000 characters. Some of my Stored proc's are >4000 characters.I use a temporary table to stock them after some modifications made to them.How can I execute them one by one, do i need to concatenate one whole stored proc's text in one single line(if yes, how can that be done?) Can variables be dynamically created, assigned values and then destroyed? Please help.
Hi All,I am running SQL2000. Can anyone tell me how I can use the contents ofa table as parameters for a stored procedure that resides on adifferent SQL server?I have a table:Customers:Cust_IDCust_NameCust_ContactCust_PhoneI need to execute a stored procedure and pass each of the above asparameters:@CustID, @CustName, @CustContact,@CustPhoneThe stored procedure also returns an error code.Thanks,Danny
I have a table with a list of stored procedures, I iterate using a Foreach loop which i iterate through an ADO.NET recordset that I created by executing a select SQL statement.
Now my problem is that in the foreach loop i have an execute sql task container which basically just executes these stored procedures using the 'exec ?' statement (i grab the name of each procedure into a variable). However, error trapping seems to be very difficult. I just figured out how to get a ReturnCode from the execute statement, but apparently I have to use it outside the Execute SQL task ....prolly use an IF condition to see if its not 0....but how do I go about doing this?
Also, I want to error trap if a stored procedure doesnt execute because of some error, how could i possibly handle an error like that? I dont want the foreach iteration to stop on an error because a stored procedure wasnt called either, but currently it does stop the entire package.
I am having trouble executing a series of 4 stored procedures from VB. The connection code connects and the first 3 stored procedures run through, although the 4th procedure stops running mid execution. No errors are reported to VB. When I run the series of procedures in the SQL Server Query Analyzer everything completes as it should. Anyone have any suggestions on what could be the problem?
Hey guys, I have found out that we can execute multiple queries and receive multiple resultsets in a SqlDataReader by executing the queries with ";" separators, However, what if we wanted to execute two sqlcommand storedprocedures? are there any other way rather than placing "Execute sp1;Execute sp2" in the command text? I would like to do it in a way whereby I can pass in two storedprocedures with parameters binding capability rather than execute sp1(param1, param2);execute sp2(param1, param2, param3) Hope to get some suggestions and advice from you guys, Thank you very much in advance.
Hi I have a database created on SQL Server 2000 server. And I have created a new database with SQL Server2005. I want to extract some data from old SQL Server2000 database. I have written a SP at SQL Server 2000 database and I want to know how to execute a SQL Server2000 SP from SQL Server2005.
I would be grateful if someone can provide some kind of explanation over why this issue has happened.
I had the following statements in a query window.
exec dbo.usp_sProc1 go exec dbo.usp_sProc2
go exec dbo.usp_sProc3 go
In order to monitor the progress of each procedure, I have a table called progress_log into which each step executing in the procedure is written. Each procedure has a "Begin" and "End" text written to this progress_log.
When I clicked the execution button on the window, I made the assumption that each stored procedure will finish before the next one executes. However something different happened.
From the above (S/N: 5) , it can be seen that the procedure did not finish executing Sproc1 because there was no "END" statement written to the Progress_Log before the "Begin" statement of SProc2.
On checking the error_log, I found there were no errors in the stored procedure. However, a message was written to the query window about insufficient space on the database at S/N:10 in the log above.
How is it possible that the Sproc2 stored procedure can be started without the Sproc1 stored procedure having ended?
If I have several stored procedures, all of them making inserts/updates to the same tables, what is the safest way to run them in sequence?
The context is an asp.net application; I have an aspx page where a click on a button (or more) will launch stored procedures in execution. I have encountered the unfortunate situation before, when stored proc #2 started long before stored proc #1 finished and this caused problems.
If I group all stroed procs in one that simply calls all of them in the needed sequence:
exec stproc1 exec stproc2 ..... exec stprocn
Will they execute in a single thread? Is there any guarantee that stproc2 will be executed when stproc1 finishes, and so on?
Hi. Does anyone know how to display the results if i execute "xp_fixeddrives, xp_availablemedia and xp_subdirs" commands with VC++ 6.0? I can't obtained the results using Recordset class. Can someone help me? Thank you.
I have about 30 different reports that I want to pull into a dashboard. I need to make sure that they don't execute in serial to get good performance.
There are two ways I can approach it
1) I can create a stored procedure for each report and then make sync calls for each of the reports from the web site. So, basically this will be controlled from the web end.
2) I can do this from the SQL Server database, if there is someway to execute these stored procedures in parallel.
I have user XY in SQL 05. I would like to find all stored procedures, where user XY has permission for executing. Is there any way to find it than look in every stored procedure?
I'm a new developer to both SQL Server 2005 & Windows 2003, so forgive me if this question seems a little too basic. I'm coming from a Oracle and UNIX background.
I've create a stored procedure in SQL Server 2005. I now want to execute this from the command line in Windows 2003. Eventually, I want our UNIX scheduler, autosys (which runs on a different UNIX machine obviously) to be able to execute this. In my old environment, I created a UNIX shell script as a wrapper let's say 123.sh. This shell script would accept as a parameter the name of the stored procedure I wanted to execute. If this stored procedure also had parameters it needed to be passed to it, I would have strung these values out in the command line in UNIX. Two examples of how the command line in UNIX I used to execute the Oracle stored procedure might look are listed below.
This way anytime I created a new stored procedure, I could reuse the shell script wrapper 123.sh and just pass in the name of the newly created stored procedure and any parameters it needed.
How can I accomplish this same type of functionality in the SQL Server 2005/Windows 2003 environment.
I am using Excel VBA to run a stored procedure which executes a package using the built-in SQL Server stored procedures. The VBA passes two values from excel to the stored proc., which is then supposed to pass these "parameters" to the package to use as a variable within the package.
@Cycle sql_variant = 2 WITH EXECUTE AS 'USER_ACCOUNT' - account that signs on using windows authentication AS BEGIN SET NOCOUNT ON; declare @execution_id bigint
[code]....
When I try to execute the package, from SQL Server or Excel using the Macro I built, I get the following error:"The parameter '[User::Cycle]' does not exist or you do not have sufficient permissions." I have given the USER_ACCOUNT that runs executes the stored procedure permission to read/write to the database and the SSIS project folder.
I received this stored procedure that I modified to run on my system. Specifically, I only changed the database and filter text and left the rest alone. When I execute the stored procedure, I get the error:
Msg 515, Level 16, State 2, Procedure ObjectNotesInsert, Line 18 Cannot insert the value NULL into column 'RefRowPointer', table 'pSCI_App.dbo.ObjectNotes'; column does not allow nulls. INSERT fails. The statement has been terminated.
Here is the actual stored procedure I am running. I should add that I can execute each step and get results and if I hard code the resulting values into the procedure, the execution works.
USE [pSCI_App] GO /****** Object: StoredProcedure [dbo].[_JAMTestSp] Script Date: 09/21/2015 11:32:09 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON
I have a webpage with a grid view in it that has sorting and filtering options. I am trying to take the sql statement and turn them into stored procedures. The problem I am having is converting this into a stored procedure. SQL = "Select CustSite.CustSite, FileInfo.FileID, FileInfo.Date, FileInfo.OriginalFileName, ReportType.ReportType, Equip.Equip, Tech.Name From [CustSite], [FileInfo], [ReportType], [Equip], [Tech] Where(FileInfo.CustomerID = '" & Session("CustomerID") & "') AND (CustSite.CustSiteID IN (Select Customer_CustSite.CustSiteID From [Customer_CustSite] Where(CustomerID = '" & Session("CustomerID") & "'))) AND (ReportType.ReportTypeID = FileInfo.ReportTypeID) AND (Tech.TechID = FileInfo.TechID) AND (Equip.EquipID = FileInfo.EquipID) AND (Equip.CustSiteID = CustSite.CustSiteID)" If Site.SelectedItem.Value <> "" Then SQL += " AND (CustSite.CustSiteID = '" & Site.SelectedItem.Value & "')" End If If Date_Set.SelectedItem.Value = "Single" Then SQL += " AND (FileInfo.Date = '" & Start_Date.SelectedItem.Value & "')" ElseIf Date_Set.SelectedItem.Value = "Between" Then SQL += " AND (FileInfo.Date Between '" & Start_Date.SelectedItem.Value & "' AND '" & End_Date.SelectedItem.Value & "')" End If If Report_Name.SelectedItem.Value <> "" Then SQL += " AND (FileInfo.FileID = '" & Report_Name.SelectedItem.Value & "')" End If If Report_Type.SelectedItem.Value <> "" Then SQL += " AND (FileInfo.ReportTypeID = '" & Report_Type.SelectedItem.Value & "')" End If If Equipment.SelectedItem.Value <> "" Then SQL += " AND (FileInfo.EquipID = '" & Equipment.SelectedItem.Value & "')" End If If Tech.SelectedItem.Value <> "" Then SQL += " AND (FileInfo.TechID = '" & Tech.SelectedItem.Value & "')" End If
Can someone point me in the right direction? Thanks in advance for the help.
Now I need to generate a datagrid with the following details: MyID, MyName, Doc's Name, Friend's Name, Pet's Name.
I have some success with the following code:
PROCEDURE dbo.PeopleISawTodayDB @ID as Int AS BEGIN SELECT PeopleISawTodayDB.MyID, PeopleISawTodayDB.MyName, PeopleISawTodayDB.DocID, PeopleISawTodayDB.FriendID, PeopleISawTodayDB.PetID, DoctorsDB.ID, DoctorsDB.Name, FriendDB.ID, FriendDB.Name, PetDB.ID, PetDB.Name FROM PeopleISawTodayDB INNER JOIN DoctorDB ON PeopleISawTodayDB.DocID = DoctorDB.ID INNER JOIN FriendDB ON PeopleISawTodayDB.FriendID = FriendDB.ID INNER JOIN PetDB ON PeopleISawTodayDB.PetID = Pet.ID WHERE PeopleISawTodayDB.JobID=@ID END
BUT it will only make a row appear if there are ID's in each of the PeopleISawTodayDB respective ID fields.
If I want to leave one blank (as in I didn't see that person that day), I would like it to still find the other details and populate the datagrid.
How can we call Stored Procedure inside any SQL Statement For Example. If we have procedure name sprocCurrentPriority select * from tablename where colmunname = exec sprocCurrentPriority
Hi Everyone, I have a Auto database table which store company auto business records. If I want to know how many BMW still in store, I use Stored Procedure as <code>Select Count(*) From AutoAd Where Make = 'BMW' and InStore = 1. </code> Now I want to know how many autos in store for all make (BMW, AUDI, HONDA, FORD...). Does single stored procedures can instead twenty stored procedures to solve this question? If can, please help me to show your stored procedures and how to reture the result to .NET program. Thanks, Lin
Hi,I'm trying to insert some values into 2 tables using stored procedures (which should be pretty straight forward) but I'm running into problems.Given below are my 2 sp that I'm using: USE [DBName] GO
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO
CREATE PROCEDURE [dbo].[AddToProject] (@DeptCode varchar(20), @ProjectTitle varchar(300), @ProjectDetails varchar(3000), @ProjectManagerID int, @RequestedBy varchar(100), @DateRequested datetime, @DueDate datetime, @ProjectStatusID int) AS BEGIN TRANSACTION SET NOCOUNT ON
DECLARE @Dept varchar(50), @ProjID varchar(50)
SET @Dept = REPLACE(CONVERT(char,@DeptCode),'.','')
GO I get the following errors: Msg 128, Level 15, State 1, Line 1The name "BAT" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.Msg 137, Level 15, State 1, Line 1Must declare the scalar variable "@ProjID".Msg 515, Level 16, State 2, Procedure AddToProject, Line 17Cannot insert the value NULL into column 'ProjID', table 'NYCEDC.dbo.tbl_Project'; column does not allow nulls. INSERT fails. If I run just the GetProjID sp, I get the following error: Must declare the scalar variable "@ProjID". -------------------------------------What I'm trying to do is, get a bunch of values from the aspx page, insert the DeptCode into the field DeptCode of the table 'tbl_ProjectNumber'+DeptCode so that the IDENTITY value field 'ProjectNumber'+DeptCode can increment by 1. After 'ProjectNumber'+DeptCode has incremented, I want to run the GetProjID sp so that I can insert ProjID into the 'tbl_Project' table along with the other values taken from the aspx page. ProjID is the primary key for the 'tbl_Project' table so it needs to be added along with the other values (other they obviously can't be added). I'm running the AddToProject as a Transaction to make sure that if more than 1 person is adding a project at the same time, the project numbers and other information don't get messed up. Any help would be appreciated.Thanks.
I am trying to call a stored procedure inside a SQL SELECT statement. Has anybody had to do this in the past? I have a SELECT statement in a Microsoft Access database and I need that SELECT statement to call the stored procedure in the SQL server. Any help would be appreciated
Hi,I'm trying to insert some values into 2 tables using stored procedures (which should be pretty straight forward) but I'm running into problems.Given below are my 2 sp that I'm using:
This is my foray into Stored procedures, so I'm hoping this is a fairly basic question.
I'm writing a stored procedure, in which I dynamically create an SQL statement. At the end of this, the SQL statement reads like:
Code SnippetSELECT COUNT(*) FROM StockLedger WHERE StockCode = 'STOCK1' AND IsOpen = 1 AND SizeCode = 'L' AND ColourCode = 'RED' AND LocationCode IS NULL AND RemainingQty > 0
Now this statement works a charm, and returns a single value. I want to assign this count to a variable, and use it further on in the stored procedure. This is where the problems start - I cant seem to do it.
If I hard code a statement, like
Code SnippetSELECT @LineCount = COUNT(*) FROM StockLedger that works fine (although it brings back a count of all the lines).
But if I modify the dynamically created SQL Statement from earlier on to:
Code SnippetSELECT @LineCount = COUNT(*) FROM StockLedger WHERE StockCode = 'STOCK1' AND IsOpen = 1 AND SizeCode = 'L' AND ColourCode = 'RED' AND LocationCode IS NULL AND RemainingQty > 0 it doesnt work - it complains: Must declare the scalar variable "@LineCount".
Just to clarify, when I say "dynamically created an SQL statement, I mean that by a bunch of conditional statements I populate a varchar variable with the statement, and then eventually run it exec(@SQLStatementString)
So, my question would be, how do I do this? How do I make a dynamically generated SQL statement return a value to a variable?
hi i need to insert the list of ipaddress using stored procedures. the user will give the from and to range of IP ADDRESS.i've to insert all the possible ip address between those values. how to do this..
I have my database: "RequestTrack" My table (with its columns): "Request"RequestKey (automatically generated)..and the Primary KeyEntryDate (datetime)Summary (nvarchar)RequestStatusCodeKey (bigint)EntryUserID (nvarchar)EntryUserEmail (nvarchar)I am wanting to create a basic web form where my user interface has 3 text boxes and a Submit button: txtUserID.TexttxtEmailAddress.TexttxtRequestSummary.Text **After I hit the submit button the information will then be inserted into the database. Also the RequestStatusCodeKey will be MANUALLY typed in so that will not require the user to add that. Please please please help ! I've been searching online for days and looking at various websites and still havent found anything. I've found somethings but they went into too much depth with too much information. I am just wanting to stay basic but w/o using SQLDataSource Controls. I would like to be able to store a lot of data. Thanks for your help!!!
I setup the databse and Visual Web Developer to use stored procedures when the insert command is used. The database also uses the field UserName that I pass using a SessionParameter within the InserParameter block from the Membership.GetUser.Username from the aspnet_ tables.
My difficulty is when using the "Formview" as the body to with which to insert (I wanted the design versatility of FormView) I get an error: "system.formatExpression: Input string was not in a correct format" when I leave the textboxes empty and invoke the insert command. I first assumed that the bound textboxes are not being converted correctly when left blank, so I used the ConvertEmptyStringToNull=True, with no success. I then coupled that with the Type=[correct format] still with the same error. Alas, my final attempt was to set defaults in the "ALTER PROCEDURE" within the stored procedure itself.
I am trying to write a stored procedure, which does a couple of things.
First thing is it looks up a persons Location based on an ID number, which is passed from an external Script. This will return four Values from a table.
I want to insert those four values into another table, along with another ID passed to the procedure from the same script.
My question is, what do I do to the script below to get the four values out of the first look up, into the insert?
The Field names returned from the SELECT are, AREA1, AREA2, AREA3, AREA4
I have a database schema that has an Address table used to store addresses for different entities such as Customers and Employees. I want to reuse the same Address record between different Customers and Employees without duplicating any address information. I'm not sure what the best approach might be.
Should have I have seperate stored procedures on the Address table that update and insert new addresses, where each Address record remains immutable once created? (So the update stored procedure actually creates a new Address record if the data changes). These stored procedures would then be invoked by business logic and used in tandem with stored procedures that act on Customers and Employees to ensure that no address records are duplicated.
Or should I create a view on a Customer joined with Address, and similarily with Employee and Address, and have stored procedures that act on these views and ensure that no Address records are duplicated. Should I use instead of triggers to override the behavior of insert and update on the view to achieve these?
I'm rather lost as to what direction I should take. Any help would be much appreciated, thanks!