Learning Stored Procedures For Querying Tables With Parameters
Sep 3, 2007
I am learning T SQL and SQL queries and have limited VB knowledge, and have a some simple queries to run on a table with parameters, and would like verification of the proposed methodology and suggestions.
Simply put, I have a [Transactions] table with columns [Price], [Ticker], [TransDate], [TransType] and calculated columns for [Days] and [Profit].
There are two parameters, [@Dys] (to query a the table for transactions within a certain period[Days = 30] and [@TT] to query only the closed transactions ie... [TransType='C']
I have been studying Stored Procedures and will be writing a Stored Procedure, but need verification if the following will work... Getting the SUM and AVG calcluations for the fields above is not a problem but I need to display SUM and AVG information also for those transactions where [Profit >0] and [Profit <0], which is easy enough by creating a subquery. But the problem is:
1. If I use a SubQuery for [Profit <0] and for [Profit>0], can I create an alias for [Count(*)] (to get a row or transaction count for each, and then divide that into the Total [Count(*)] alias for the Transactions table to get a value for % profitable or Probability (% total Profitable trades versus % total Unprofitable trades)?
2. Or, do I need to create either temporary tables or views to have 3 distinct tables (1 table for Transactoins and 2 temp or Views for [Profit >0] and [Profit <0])?
Any suggestions and advice or examples on how to do this would be appreciated.
I was just wondering if something could be explained to me.
I have the following:
1. A table which has fields with data types and lengths / sizes 2. A stored procedure for said table which also declares variables with datatype and lengths/ sizes 3. A function in written in VB .net that uses said stored procudure. The code used to add the parameters to the sql command also requires that i give a data type and size.
How come i need to specify data type and length in three different places? Am i doin it wrong?
Any information is greatly appreciated.
Thanks
Im using SQL Server 2000 with Visual Studio .Net using Visual Basic..
are there any tutorials online for a person wanting to learn about writing stored procedures in sql server 2000, i know sql, but want to learn more about that, as i might be getting more involved in the database side for a coming project. or any books someone could recommend.thanks.
What I am trying to do now is combine multiple complex queries into one table and query it showing the results on an ASP.net page.
I am currently using SQL Server 2000 backend. Each one of these queries are pretty complex so I created each query as a Stored Procedure. These queries are dynamic by each user, so the results will never be the same globally.
What I have done so far was created a master stored procedure passing the current user's username as a parameter. Within the master SP (Stored Procedure) it creates a temporary table inserts and executes multiple stored procedures and inserts into the temporary directory. Each of the sub stored procedures all have the same columns. After the insert to the temp tables, I then query the temp table and return it to the function it was executed in code and fill it as a System.Data.DataTable. I then bind the DataTable to a Repeater.DataSource.
Problem: When the page is rendered, it returns nothing. I tested the master SP in the data environment and it works fine.
Suspect: ASP.net when the SP is executed, it sees that the data is a disconnected datasource? Perhaps the session in the SQL Server when the temp table is created isn't in SYSOBJECTS system table?
Here is an example of the code from the master SP:
CREATE PROCEDURE dbo.TM_getAlerts @Username varchar(32)ASCREATE TABLE #MyAlerts ([DATE] datetime, [TEXT] varchar(200), [LINK] varchar(200) ) INSERT INTO #MyAlertsEXEC TM_getAlertsNewTasks @Username INSERT INTO #MyAlertsEXEC TM_getAlertsLateTasks @Username SELECT [DATE] AS 'DATE', [TEXT] AS 'TEXT', [LINK] AS LINK FROM #MyAlerts GO
It is a fairly simple call... but why doesn't ASP.net doesn't see it when the the DataTable is filled. I tried just executing one of the sub SP without creating temporary tables and it works flawlessly. But the query in one of the sub SP is a normal but complex select.
I want to create a stored procedure with SQL Server 6.5 that CAN take 3 parameters, all of which are optional. The declaration for the stored procedure is : CREATE PROCEDURE BackOrdersII @CustCode varchar(10), @FromDate datetime, @ToDate datetime AS SELECT * FROM ISO_Details WHERE DATEDIFF(dd, fldEst_Del_Date, getdate()) > 0 AND CONVERT(char(12),fldActual_Del_Date,3)=`01/01/00` AND CONVERT(char(12),fldEst_Del_Date,3)<>`01/01/00` AND fldDeleted<>1 ORDER BY DATEDIFF(dd, fldEst_Del_Date, getdate()) DESC
How do I formulate the procedure to allow me to select from the table, keeping the current WHERE clause but adding extra items to allow the results to be further filtered depending upon which of the parameters are given to the procedure. Any one, two, or all three parameters could be given.
Sorry if this seems like a simple question but I am only just getting into using stored procedures.
Have looked everywhere and cannot find the answer! So perhaps someone here can answer.
I have an Access 2000 front-end to a SQL Server 2000 database.
I know how to create Stored Procedures that receive parameters; and also how to open a Stored Procedure in the query results window using the DoCmd object. For example,
I use a stored procedure that is calling several other stored procedurewhich update or append values in several tables. All of them are storedprocedures with input parameters by which they filter rows to be updated orinserted into other tables.Filtration is based on certain actual values on forms (form with severalsubforms).My question is following: How to pass parameters to those stored proceduresthat are triggered by a button?Those stored procedures are not recordset of forms, so I can't pass it usingInput Parameters property of forms (or I can?).Thanks.Zlatko
My colleague and I (both are newbie’s to .NET) are divided on whether to use stored procedures or parameters.
His viewpoint is, using stored procedures you are spreading the load i.e. SQL server and web server etc. This is not a good solution because it is not a portable when it has to be relocated.
Is he right?
I thought to avoid SQL injection it is best to use stored procedures but I do see his reasoning as well.
Yazzy is Very confused!! Thanks in advance for any of your thoughts
How can I pass a name of a table to a stored procedure. I want to pass the name as a parameter. The table already exists in the db. After that, I will do "SELECT ..... FROM @tableparameter" What is the right way to do that?
I seached around for an answer to this question but didn't have much luck. Hopefully someone can help.
I am passing two parameters from a web page to a stored procedure. The first paramater @Field is the name of the field in the database I want to search, the second @Value is the value to seach for. The @Value works fine but the SP does not seem to recongnize the field parameter. I'm not sure if what I am attemping is not supported or wheather I just need to format the @Field in a different manner. The code and stored procedure is below.
Thanks for your help, Gary
Here is the web code:
Dim conMSS As New SqlConnection(ConfigurationSettings.AppSettings("dsnMSS")) Dim cmdItems As New SqlCommand("DS-SPRS.dbo.s_ItemLookUp", conMSS)
I am creating a stored Procedure and I am getting an error which relates to DATENAME. SELECT COUNT(*) AS calls, DATENAME(@varDate, CALLSTARTTIME) AS 'Total Calls' FROM CALL_LOG_MASTER WHERE (COMMERCIALS='1') AND (CALLSTARTTIME >= @StartDate) AND (CALLENDTIME <=@EndDatesql doesn't like: DATENAME( @varDate, CallStartTime)sql works fine if I change @varDate into 'yy', 'mm', 'dd', or 'wk'Since I do not want to make 5 unique Stored Proc just because of @varDate.....Is there any way to work around this problem?
I need to create a SP that will accept a varying number of input parameters. A form that the user completes has a several controls that serve to narrow the number of records returned. The more parameters given, the fewer rows returned. In the past I have accomplished this by dynamically building an SQL statement. I dosen't appear possible to pass an SQL statement in a variable to a SP. Any help or pointers would be appreciated.
I need to set date parameters within Stored Procedures using a sql 2008 R2, with an access 2007 front end. The procedure needs to allow me to set parameters for a start date and an end date.
I am using SQL Server 2000. I have a table with, say, 20 columns. Ihave one procedure which updates all 20 columns at once, accepting aparameter for each column. However, I want to be able to pass anycombination of parameters and only update those columns if passed. SoI created the sp as something likecreate update_t1(@col1 int = null,@col2 int = null,@col3 int = null,....@col20 int = null)asupdate t1set col1 = @col1,col2 = @col2,col3 = @col3,.....col20 = @col20This way I can explicitly specify columns or not as I choose. Forexample I could call "exec update_t1 @col1 = 23, @col4 = 49" to updateonly the first and fourth column. Of course this will obviouslyupdate the remaining columns to null. Is there any way to identifywithin the procedure which parameters were actually specified? Ican't simply do a null check because the user could be updating thevalue to be null. Is there any way for the procedure to know theexact command that invoked it?For example, if I called "exec update_t1 @col1 = 23, @col4 = 49" Iwould want to know only col1 and col4 were specified. If I called"exec update_t1 @col1 = 23, @col4 = 49, @col17 = null" I would want toknow that col1, col4 and col17 were specified, even though col17 wasset to the default of null.
I've a SqlDataSource control that has stored procedures specified for each of its commands: SelectCommand, InsertCommand, UpdateCommand, DeleteCommand . And for Insert, Update and Delete, I've specified asp:parameters for each stored procedure's parameters. Now, my stored procedures all have return values, and I've successfully accessed the return values for Insert and Update, but for some reason, I'm getting very wrong results for Delete. <DeleteParameters> <asp:Parameter Name="result" Type="Int32" Direction="ReturnValue" /> <asp:Parameter Name="myID" Type="Int32" /></DeleteParameters>The moment I add my "result" with the direction ReturnValue, I instantly get a "Procedure or function <storedprocedurename> has too many arguments specified." error. I checked my SQL Profiler, and it seems that the page is passing result as an Input parameter, instead of keeping it as a ReturnValue! e.g. exec spName @myID=1, @result=NULLwhen it should be exec spName @myID=1I get the correct behavior with Update and Insert, so I'm wondering whether if this is a bug or by-design behavior or something very screwy with my computer?Help? Thoughts?
I have written a simple C# console application that create my own Stored Procedures the code is here ----------------------------------------------------------------------------
static void Main(string[] args) { SqlConnection cn; string strSql; string strConnection; SqlCommand cmd; strConnection="server=(local);database=Northwind;integrated security=true;"; strSql="CREATE PROCEDURE spmahdi @CustomerID nchar(5) @counter int OUTPUT AS SELECT OrderID, OrderDate,RequiredDate,ShippedDate FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID SET @counter=@@rowcount"; cn=new SqlConnection(strConnection); cn.Open(); cmd=new SqlCommand(strSql,cn); cmd.ExecuteNonQuery(); cn.Close(); Console.WriteLine("Procedure Created!"); }
------------------------------------------------------------------------------------ but it has some errors becuase of my strSql strSql="CREATE PROCEDURE spmahdi @CustomerID nchar(5) @counter int OUTPUT AS SELECT OrderID, OrderDate,RequiredDate,ShippedDate FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID SET @counter=@@rowcount"; I mean in creating the stored procedure if i delete the Output parameter from my stored procedure and my strSql would be somethimg like this strSql="CREATE PROCEDURE spmahdi @CustomerID nchar(5) AS SELECT OrderID, OrderDate,RequiredDate,ShippedDate FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID "; There will be no errors I use Visual Studio.NET 2003(full versoin)and MSDE(not Sql Server) Could someone help me solve this problem? Thanks and Regards.
I have a stored procedure some thing like this.. When I pass empty strings to both the parameters ..it is returning all the rows from the table.
IF I pass both empty strings to @LLASTNAME_I Char(21), @DEPARTMENTCODE_I char(7),it should not select any rows from the table.. can any one suggest me as to how to accomplish this..
CREATE procedure Ceb_Phone_Book @LLASTNAME_I Char(21), @DEPARTMENTCODE_I char(7) AS Select EM010132.DEPARTMENTCODE_I, DEPARTMENTNAME_I, LLASTNAME_I, FFIRSTNAME_I, EM010132.WORKPHONE_I, EM010132.MSTRING_I_5 FROM EM010132 INNER JOIN HR2DEP01 ON HR2DEP01.DEPARTMENTCODE_I = EM010132.DEPARTMENTCODE_I WHERE INACTIVE = 0 AND LLASTNAME_I LIKE LTRIM(RTRIM(@LLASTNAME_I)) + '%' AND EM010132.DEPARTMENTCODE_I LIKE LTRIM(RTRIM(@DEPARTMENTCODE_I)) + '%' ORDER BY LLASTNAME_I,FFIRSTNAME_I
I guess I'm the only one with this problem -- couldn't find anything on it in the back questions. Maybe it's a weird problem. :)
Anyway, although I'm not new to SQL, I am a bit new to stored procedures, and MS SQL Server 7. (I've been using mySQL, decent, but doesn't have many features ... )
I used some ASP and stored procedure code from 4guysfromrolla.com for session tracking through SQL Server.
I've modified most of the stored procedures so that they actually work. :)
To answer some questions before they're asked: It's a resume database, and does need to be able to store 8000 characters at a shot. (I'm hoping 8000 is as large as it gets for this particular field.)
There's only one problem now: One of the stored procedures enters information into the sessionvalue field of the table. However, much of our data contains apostrophes ('), and we need to be able to store them. I thought that modifying the execute statement would do it, something like:
I use EXEC statement to execute query in NVARCHAR format. Query is constructed using WHILE loop. Lenght of parameter @query in limited on 4000 ch. But my parameter is longer. Data types ntext and text can't be used for parameters. Any idea?
I'm trying to pass parameters to an extended stored procedure, to noavail. I would like to pass two integers to the dll and I have thefollowing three snippets:1. The C++ portion of the dll:....declspec(dllexport) int myAddNumbers(int m, int n)....2. The creation of the extended stored procedure:EXEC sp_addextendedproc myAddNumbers , 'foodll.dll';3. The usage:create function TestFunction()returns integerasbegindeclare @rc integerexec @rc = myAddNumbersreturn (@rc)endHow do any of the above three things need to be modified in order tomake this work?Thanks!!!
When I execute a stored procedure from an OLE DB Command transformation, where the sp takes a parameter and RetainSameConnection=TRUE and DelayValidation=TRUE are set, I get the error
"Syntax error, permission violation, or other nonspecific error"
If I take out the param or set RetainSameConnection=FALSE on the connection, all is fine again?
Hi guys, hoping one of you may be able to help me out. I am using VS 2005, and VB.net for a Windows application. I have a table in SQL that has a list of Storedprocedures: Sprocs Table: SPID - PK (int), ID (int), NAME (string), TYPE (string)The ID is a Foreign key (corresponding to a Company ID), the name is the stored procedure name, and Type (is the type of SP). On my application I need to a certain SP depending on the company selected and what page you are on. I have a seperate SP that passes in parameters for both Company, and Type and should output the Name value: ALTER PROCEDURE [dbo].[S_SPROC] ( @ID int, @TYPE CHAR(10), @NAME CHAR(20) OUTPUT )AS SELECT @NAME = NAME FROM SPROCSWHERE [ID] = @IDAND [TYPE] = @TYPE Unfortunately I dont seem to be able to get the output in .Net, or then be able to fill my dataset with the Stored Procedure.Has anyone done something similar before, or could point me in the right direction to solving this problem. ThanksPhil
I've created a search page in my asp.net app that allows the user to enter optional parameters to narrow down the result set. It looks something like:Find all parts where: manuafacturer: <dropdownlist>ANY | manufacturer 1 |... </dropdownlist> model: <dropdownlist>ANY | model 1 |... </dropdownlist> cost: between <textbox> and <textbox> dollarsCurrently I create the SQL command on the fly building the WHERE based on what the user selects. For example if in the form above they select manufacturer = manufacturer1 model = ANY cost = between 10 and 15the WHERE string is ... WHERE manufacturer='manufacturer1' AND cost BETWEEN 10 AND 15Since the user doesn't care about model I leave it out of the WHERE. OK so here is my question. I want to move my queries to strored procedures however I'm not sure how to create the query since it changes based on what the user enters. Using the example above I'm assuming I can create one query with 4 parameters however what value would I use for ANY? parameter1 (manufacturer) = "manufacturer1" parameter2 (model) = ??? parameter3 (price low) = 10 parameter4 (proce high) = 15I see there is an ANY operator in T-SQL but it doesn't look like the right thing to use. Should I use LIKE '%'? Seems that using LIKE would result in addition overhead.ThanksSimon
I've read that stored procedures should use output parameters instead ofrecordsets where possible for best efficiency. Unfortunately I need toquantify this with some hard data and I'm not sure which counters touse. Should I be looking at the SQL Server memory counters or somethingelse.*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
I have just starting creating some stored procedures for our system and have a question related to management of these.
When using input parameters using the following syntax:
CREATE PROCEDURE sp_someInputProcedure @Username as varchar(16) @Password as varchar(12) @Name as varchar(50) @Address as varchar(60) @Zip as int @City as varchar(30) ... etc.
This is all well and good, but what if I make a change in the datamodel - for instance changing a datatype or the length of a varchar - do I need to remember to manually update all stored procedures that uses these columns/variables?
Seems like a bit of a hazzle. Is there an easier way to do this?
Consider a situation where a stored procedure taking a varbinary(max) (BLOB) input parameter then calls a nested stored procedure and passes along that varbinary(max) as an input parameter to the nested stored procedure.
Is a copy of the BLOB provided to the nested stored procedure (passed by value) OR is the BLOB passed by reference.
My interest is in understanding the potential memory hit when handling large BLOBs in this environment.
For example, if the BLOB is 200MB, will SQL server need to allocate memory for a new copy each time it's passed to another stored procedure?
Looks like table type parameters are passed by reference, but I haven't been able to find any info on BLOBS in this context.
There is a form in an Access Project (.adp, Access front end with SQLServer) for entering data into a table for temporary storing. Then, byclicking a botton, several action stored procedures (update, append) shouldbe activated in order to transfer data to other tables.I tried to avoid any coding in VB, as I am not a professional, but I havefound a statement in an article, that, unlike select queries, form's InputProperty can't be used for action queries. Therefore, parameters can bepassed to action stored procedure only by using ADO through VB.As I'm not very familiar with VB, I had to search in literature.So, this is a solution based on creating Parameter object in ADO and thenappending values to Parameter collection.Please, consider the following procedure I created for passing parametersfrom form's control objects (Text boxes) to a stored procedureDTKB_MB_UPDATE:Private Sub Command73_Click()Dim cmd As ADODB.CommandSet cmd = New ADODB.Commandcmd.ActiveConnection = CurrentProject.Connectioncmd.CommandText = "DTKB_MB_UPDATE"cmd.CommandType = adCmdStoredProcDim par As ADODB.ParameterSet par = cmd.CreateParameter("@DATE", adDBTimeStamp, adParamInput)cmd.Parameters.Append parSet par = cmd.CreateParameter("@BATCH_NUMBER", adVarWChar, adParamInput, 50)cmd.Parameters.Append parSet par = cmd.CreateParameter("@STATUS", adVarWChar, adParamInput, 50)cmd.Parameters.Append parSet par = cmd.CreateParameter("@DEPARTMENT", adVarWChar, adParamInput, 50)cmd.Parameters.Append parSet par = cmd.CreateParameter("@PRODUCTION", adVarWChar, adParamInput, 50)cmd.Parameters.Append parSet par = cmd.CreateParameter("@SAMPLING_TYPE", adVarWChar, adParamInput,50)cmd.Parameters.Append parcmd.Parameters("@DATE") = Me.DATEcmd.Parameters("@BATCH_NUMBER") = Me.BATCH_NUMBERcmd.Parameters("@STATUS") = Me.STATUScmd.Parameters("@DEPARTMENT") = Me.DEPARTMENTcmd.Parameters("@PRODUCTION") = Me.PRODUCTIONcmd.Parameters("@SAMPLING_TYPE") = Me.SAMPLING_TYPEcmd.ExecuteSet cmd = NothingEnd SubUnfortunately, when clicking on the botton, the following error apears:"Run-time error'-2147217913 (80040e07)':Syntax error converting datetimefrom character string."Obviously, there is some problem regarding parameter @DATE. In SQL Server itis datetime, on the form's onbound text box it is short date (dd.mm.yyyy)data type. I have found in literature that in ADO it should beadDBTimeStamp.So, what is the problem ?Greetings,Zlatko
How do I search for and print all stored procedure names in a particular database? I can use the following query to search and print out all table names in a database. I just need to figure out how to modify the code below to search for stored procedure names. Can anyone help me out? SELECT TABLE_SCHEMA + '.' + TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
Hi,I'm using c# with a tableadapter to call stored procedures. I'm running into a problem where if I have over a certain byte size or number of parameters being passed into my stored proc I get an exception that reads: "Cannot evaluate expression because a thread is stopped at a point where garbage collection is impossible, possibly because the code is optimized." If I remove one parameter, the problem goes away. Has anyone run into this before? Thanks,Mark