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

RETURN @sequence_id
END

View 1 Replies


ADVERTISEMENT

Executing Stored Procedures From Asp.net

Nov 2, 2006

I have the following sp..REATE Procedure SSSP_VehicleReg_Add    @DECAL_NO varchar  (9)   , @NAME varchar  (26)  , @SSN varchar  (9)   , @DLN varchar  (10)   , @Address_1 varchar    , @Address_2 varchar    , @City varchar  (50)  , @State_Code varchar    , @Zip_Code varchar  (9)  , @Country_Code varchar  (4)   , @PHONE varchar  (12)   , @VM varchar  (10)   , @MODEL varchar  (10)   , @VLPNUMBER varchar  (10)   , @VLPSTATE varchar  (2)  , @Date_Iss datetime, @Date_Exp datetime, @tran_Date datetime, @Op_Code varchar (20) , @ReturnStatus   integer output, @ReturnMessage  Varchar (50) output /* Adds a record to the Vehicle Registration table.*/ AS     If @Decal_no = ' '          Begin  Set @ReturnStatus = 0         Set @ReturnMessage = 'Record not added Key Fields are not valid'  End     Else          If dbo.VehicleReg_Check (@Decal_No) = 0       Begin    Insert INTO VehicleReg (Decal_NO, Name, SSN, DLN, Address_1, Address_2, City, State_Code,                            Zip_Code, Country_Code, Phone, VM, Model, VLPNUMBER, VLPSTATE,                             Date_Iss, Date_Exp, Tran_Date, Op_Code)                  Values   (@Decal_NO, @Name, @SSN, @DLN, @Address_1, @Address_2, @City, @State_Code,              @Zip_Code, @Country_Code, @Phone, @VM, @Model, @VLPNUMBER, @VLPSTATE,               @Date_Iss, @Date_Exp, @Tran_Date, @Op_Code)    Set @ReturnStatus = 1         Set @ReturnMessage = 'Record added'          End     Else        Begin  Set @ReturnStatus = 0         Set @ReturnMessage = 'Record not added' EndGO That is being called via...Dim SqlCmd As New SqlCommand("SSSP_VehicleReg_ADD", MYGF.cnMydb)Dim Current_Time As String = CStr(Now.Date + Now.TimeOfDay)SqlCmd.CommandType = CommandType.StoredProcedureSqlCmd.Parameters.Add("@Decal_No", SqlDbType.VarChar, 9, txtDecal.Text)SqlCmd.Parameters.Add("@NAME", SqlDbType.VarChar, 26, txtName.Text)SqlCmd.Parameters.Add("@SSN", SqlDbType.VarChar, 9, txtStuid.Text)SqlCmd.Parameters.Add("@DLN", SqlDbType.VarChar, 10, txtDln.Text)SqlCmd.Parameters.Add("@Address_1", SqlDbType.VarChar, 50, txtAddress_1.Text)SqlCmd.Parameters.Add("@Address_2", SqlDbType.VarChar, 50, txtAddress_2.Text)SqlCmd.Parameters.Add("@City", SqlDbType.VarChar, 50, txtCity.Text)SqlCmd.Parameters.Add("@State_Code", SqlDbType.VarChar, 2, ddlState.Text)SqlCmd.Parameters.Add("@Zip_Code", SqlDbType.VarChar, 9, txtZip.Text)SqlCmd.Parameters.Add("@Country_Code", SqlDbType.VarChar, 4, " ")SqlCmd.Parameters.Add("@PHONE", SqlDbType.VarChar, 12, txtPhone.Text)SqlCmd.Parameters.Add("@VM", SqlDbType.VarChar, 10, txtMake.Text)SqlCmd.Parameters.Add("@MODEL", SqlDbType.VarChar, 10, txtModel.Text)SqlCmd.Parameters.Add("@VLPNUMBER", SqlDbType.VarChar, 10, txtTagNo.Text)SqlCmd.Parameters.Add("@VLPSTATE", SqlDbType.VarChar, 2, " ")SqlCmd.Parameters.Add("@Date_Iss", SqlDbType.DateTime, 8, txtIssDate.Text)SqlCmd.Parameters.Add("@Date_Exp", SqlDbType.DateTime, 8, txtExpDate.Text)SqlCmd.Parameters.Add("@tran_Date", SqlDbType.DateTime, 8, Current_Time)SqlCmd.Parameters.Add("@Op_Code", SqlDbType.VarChar, 20, "xxxx")Dim ReturnStatus As New SqlParameter(("@ReturnStatus"), SqlDbType.Int, 1, ParameterDirection.Output)Dim ReturnMessage As New SqlParameter(("@ReturnMessage"), SqlDbType.VarChar, 50, ParameterDirection.Output)SqlCmd.Parameters.Add(ReturnStatus)SqlCmd.Parameters.Add(ReturnMessage)SqlCmd.ExecuteNonQuery()Which fails with the following error...System.Data.SqlClient.SqlException was unhandled by user code  Class=16  ErrorCode=-2146232060  LineNumber=0  Message="Procedure 'SSSP_VehicleReg_Add' expects parameter '@DECAL_NO', which was not supplied."  Number=201  Procedure="SSSP_VehicleReg_Add"  Server=  Source=".Net SqlClient Data Provider"  State=6  StackTrace:       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()       at Vechicle_Registration.Move_to_database() in C:InetpubwwwrootssccintranetVechicle_Registration.aspx.vb:line 304       at Vechicle_Registration.BtnSave_Click(Object sender, EventArgs e) in C:InetpubwwwrootssccintranetVechicle_Registration.aspx.vb:line 34       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) Any help would be appreciated      

View 2 Replies View Related

Executing Stored Procedures From Asp.net

Nov 2, 2006

I changed "@Decal_No" to "@Decal_NO" same error 

View 2 Replies View Related

Executing Stored Procedures

Jun 9, 2004

Hello,

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.

View 3 Replies View Related

Executing Stored Procedures

Jan 29, 2007

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

View 3 Replies View Related

Executing Stored Procedures

Jul 3, 2007

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.



Thoughts anyone?

View 4 Replies View Related

Executing SQL Stored Procedures In VB

Aug 15, 2007

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?

View 1 Replies View Related

Executing More Than One Stored Procedures In A DataReader

Nov 28, 2007

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.

View 5 Replies View Related

Executing Distributed Stored Procedures

Oct 21, 2007

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.

Thanks & Regards!

View 2 Replies View Related

Issue While Executing Stored Procedures

Jan 8, 2008



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.


The progress_log shows the following

S/N proc_Name Step
1 sProc1 Begin
2 sProc1 sProctep1
3 sProc1 sproc1: Step2

4 sproc1 sproc1tep3
5 sProc2 sproc2:Begin
6 sProc2 sProc2tep1
7 sproc2 sProc2tep2
8 sproc2 sproc2:End
9 sProc3 Begin
10 sProc3 Sproc3: Step1


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?

I can give more explanation if not clear.

many thanks for any help


View 5 Replies View Related

Transact SQL :: Executing Stored Procedures And Threading

Jul 10, 2015

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?

View 2 Replies View Related

How To Get The Results When Executing Extended Stored Procedures.

May 28, 2007

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.



|_N_T_|

View 3 Replies View Related

Transact SQL :: Executing Stored Procedures Asynchronously / In Parallel

May 30, 2015

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.

View 8 Replies View Related

List Of Stored Procedures With Permission For Executing For User

Jul 26, 2007

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?

Thanks for tips

View 4 Replies View Related

Executing SQL Server 2005 Stored Procedures On Windows 2003

Jul 18, 2007

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.



123.sh sp_my_stored_procedure input_parm1 input_parm2



123.sh sp_different_stored_procedure input_parm1



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.



Thanks, Jim

View 4 Replies View Related

SQL 2012 :: Parameter Error When Executing A Package With Built In Stored Procedures

Jul 23, 2014

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.

View 4 Replies View Related

SQL Server 2012 :: Case Statement Executing A Stored Procedure

Aug 20, 2014

Is this possible, I am trying to execute a stored procedure depending on what parameter is selected, something like this????

Case
when field = 'value' then execute sp_procedure else execute sp_procedure_2 end
case

View 1 Replies View Related

Data Warehousing :: Cannot Insert Value NULL Into Column When Executing Stored Procedure

Sep 22, 2015

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

[Code] ....

View 30 Replies View Related

Stored Procedures IF Statement

Sep 12, 2007

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.

View 1 Replies View Related

If Statement In Stored Procedures Help

Jun 23, 2008

Hi all. This has kept me up all night! I'm trying to populate a datgrid with multiple tables with relating keys in each table.

For ease, I've made the databases hopefully understandable.

DoctorsDB - (ID, Name, Phone)
FriendsDB - (ID, Name, Phone)
PetsDB - (ID, Name)
PeopleISawTodayDB - (MyID, MyName, DocID, FriendID, PetsID)

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.

Can anyone lend a coding hand???? Cheers

View 7 Replies View Related

Calling Stored Procedures In SQL Statement

Aug 25, 2007

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

View 7 Replies View Related

One Stored Procedures (SQL Statement) Question

May 9, 2005

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

View 1 Replies View Related

Stored Procedures IF Statement (SQL2005)

Jan 30, 2006

Hello, I need to use a if statement in stored procedures.

What I need to know is the proper syntax because anything I try does not work.

I need to check if 24 hours passed:
datediff(hh, Users.LastLogin, GetDate())

Should return the number of hours that has passed. I need to use this in the IF statement, and I need to check if it's > 24.

Thanks =)!

View 2 Replies View Related

USE Statement In Stored Procedures Two Databases, How Please?

May 23, 2008

This works great in a query:


USE KCADOWNLOAD

USE OUTHOUSE

GO

DELETE FROM OUTHOUSE.KCA_BLDGS_ACCES

INSERT INTO OUTHOUSE.OUTHOUSE.KCA_BLDGS_ACCES

(MAJOR, MINOR, ACCYTYPE, ACCYDESCR,

QUANTITY, SIZE, UNIT, GRADE, EFFYR, PCNTNETCONDITION, ACCYVALUE, DATEVALUED, UPDATEDBY,

UPDATEDATE,PID)

SELECT MAJOR, MINOR, ACCYTYPE, ACCYDESCR,

QUANTITY, SIZE, UNIT, GRADE, EFFYR, PCNTNETCONDITION, ACCYVALUE, DATEVALUED, UPDATEDBY,

UPDATEDATE,PID

FROM KCADOWNLOAD.dbo.KCA_BLDGS_ACCES AS KCA_BLDGS_ACCES_1



But the stored procedure only creates ONE Use statement:


USE [KCADOWNLOAD]

...etc.


I assume I can run an SP utilizing two databases...


The SP fails because it hasn't got a clue what OUTHOUSE is...


Thank you!!!

View 3 Replies View Related

INSERT INTO Using Stored Procedures

Apr 28, 2007

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),'.','')

EXEC ('INSERT INTO dbo.tbl_ProjectNumber' + @Dept + '(DeptCode) VALUES(' + @Dept + ')')

EXEC GetProjID @Dept, @ProjID OUTPUT


INSERT INTO dbo.tbl_Project (ProjID, ProjectTitle, ProjectDetails, ProjectManagerID, RequestedBy, DateRequested, DueDate, ProjectStatusID)
VALUES (@ProjID, @ProjectTitle, @ProjectDetails, @ProjectManagerID, @RequestedBy, @DateRequested, @DueDate, @ProjectStatusID);


COMMIT TRANSACTION

---------------------------------------------------------------------


USE [DBName]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[GetProjID] (@DeptCode varchar(20), @ProjID varchar(50) OUTPUT)
AS
BEGIN
SET NOCOUNT ON

DECLARE @ProjectNumber varchar(100), @Table varchar(100)
SET @ProjectNumber = 'ProjectNumber' + REPLACE(CONVERT(char,@DeptCode),'.','')
SET @Table = 'dbo.tbl_ProjectNumber' + REPLACE(CONVERT(char,@DeptCode),'.','')
EXEC ( 'SELECT @ProjID = MAX('+@ProjectNumber + ') FROM ' + @Table )

SET @ProjID = @ProjID + '-' + @DeptCode

END When I run the AddToProject sp using the following values: USE [DBName]
GO

DECLARE@return_value int

EXEC@return_value = [dbo].[AddToProject]
@DeptCode = N'BAT',
@ProjectTitle = N'Some Title',
@ProjectDetails = N'Some Details',
@ProjectManagerID = 3,
@RequestedBy = N'Me',
@DateRequested = N'04/27/2007',
@DueDate = N'05/04/2007',
@ProjectStatusID = 4

SELECT'Return Value' = @return_value

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.  

View 13 Replies View Related

Calling Stored Procedures In A Select Statement

Feb 26, 2004

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

View 4 Replies View Related

INSERT INTO Tables Using Stored Procedures

Apr 28, 2007

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: 

View 5 Replies View Related

Stored Procedures - Using Return Value From Dynamically Created SQL Statement

Jul 29, 2007

Hello,

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?


View 3 Replies View Related

How To Insert The Range Of Ip Address In SQL Using Stored Procedures

Sep 14, 2007

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

View 3 Replies View Related

Using Stored Procedures To Insert And Pull Data From Database

Mar 21, 2008

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

View 4 Replies View Related

Having Difficulty With FormView, Stored Procedures And Insert Parameter

Feb 17, 2005

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.

Any help would be most appreciated. Thanks.
.

View 2 Replies View Related

Stored Procedures - Insert Data Gathered From Sele

Mar 28, 2008

Hi,

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

Thanks

David


CREATE PROCEDURE UserAssign_Location

@UserID Int, @AreaID Int
AS
BEGIN
SET NOCOUNT ON;

SELECT * From Locations Where EntryID = @AreaID

INSERT INTO Members_Locations (UserID, Location1, Location2, Location3, Location4, Active)
VALUES (@UserID, 'AREA1', 'AREA2', 'AREA3', 'AREA4', 1)

END
GO

View 1 Replies View Related

Writing Insert And Update Stored Procedures For Normalized Schemas?

May 25, 2006

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!

View 1 Replies View Related







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