Write A Stored Procedure Based On Recursive Data.

Feb 25, 2008

Hello, I am hoping someone can help me in this. I am looking to write a stored procedure that will return the heirarchy of an organization. I will display how the heirarchy might look and then list the tables involved.

John Smith

- Jacob Jones
- Lisa Thompson
- Samuel Barber

- Paul Smith
- John Jackson

Ok, so Jacob, Lisa, an Samuel report up to John Smith. Paul and John Jackson report up to Samuel Barber.

Here are the tables:

Users holds the user_id, first_name, last_name, and reports_to_user_id.
User_Roles holds the user_id, role_type_id
Role_Types holds the role_type_id, and the type (which could be Administrator, Standard, Guest) for example. In addition, Role_Types also has ranking which must be taken into consideration as well. 1 being the top rank and 9 being the lowest.

Thanks very much in advance,
Saied

View 12 Replies


ADVERTISEMENT

How To Convert Recursive Function Into Recursive Stored Procedure

Jul 23, 2005

I am having problem to apply updates into this function below. I triedusing cursor for updates, etc. but no success. Sql server keeps tellingme that I cannot execute insert or update from inside a function and itgives me an option that I could write an extended stored procedure, butI don't have a clue of how to do it. To quickly fix the problem theonly solution left in my case is to convert this recursive functioninto one recursive stored procedure. However, I am facing one problem.How to convert the select command in this piece of code below into an"execute" by passing parameters and calling the sp recursively again.### piece of code ############SELECT @subtotal = dbo.Mkt_GetChildren(uid, @subtotal,@DateStart, @DateEnd)FROM categories WHERE ParentID = @uid######### my function ###########CREATE FUNCTION Mkt_GetChildren(@uid int, @subtotal decimal ,@DateStart datetime, @DateEnd datetime)RETURNS decimalASBEGINIF EXISTS (SELECTuidFROMcategories WHEREParentID = @uid)BEGINDECLARE my_cursor CURSOR FORSELECT uid, classid5 FROM categories WHERE parentid = @uiddeclare @getclassid5 varchar(50), @getuid bigint, @calculate decimalOPEN my_cursorFETCH NEXT FROM my_cursor INTO @getuid, @getclassid5WHILE @@FETCH_STATUS = 0BEGINFETCH NEXT FROM my_cursor INTO @getuid, @getclassid5select @calculate = dbo.Mkt_CalculateTotal(@getclassid5, @DateStart,@DateEnd)SET @subtotal = CONVERT (decimal (19,4),(@subtotal + @calculate))ENDCLOSE my_cursorDEALLOCATE my_cursorSELECT @subtotal = dbo.Mkt_GetChildren(uid, @subtotal,@DateStart, @DateEnd)FROM categories WHERE ParentID = @uidENDRETURN @subtotalENDGORod

View 4 Replies View Related

Grouping Data Based On Return From Stored Procedure

Jun 15, 2007

I'm having some difficulty getting the appropriate results for my scenerio. I have two different datasets that I'm using. One is consisting of two joined tables and the other consisting of one sp. The sp's parameters rely on two things- one is the companyNum (inputed when the user runs the report) and two is the ContactNumType. The ContactTypeNum comes from the dataset of tables. I need to have a table consisting of this format:


ContactNumType1 (From the Tables)
File_Name1 (From the sp)
File_Name4 (From the sp)
File_Name3 (From the sp)



ContactNumType2 (From the Tables)
File_Name2 (From the sp)
File_Name7(From the sp)



ContactNumType3 (From the Tables)
File_Name5 (From the sp)



ContactNumType4 (From the Tables)
File_Name6 (From the sp)

File_Name10 (From the sp)
File_Name8(From the sp)
File_Name9 (From the sp)

So essentially what is going on is that every returned File_Name is grouped based upon the type of ContactNumType. My table returns the appropriate ContactNumTypes and the appropriate number of File_Names but returns only the first File_Name for each row. The File_Names should only grouped by the ContactTypeNums and each be unique. Is there any way to do that?


-------------------------------------------------------------------------------------------
Edited: I still am trying to work this out. I've tried a few run-arounds but none have worked. Adding custom code apparently is too risky at this point because of the security precautions that I've been instructed to take. Any help would be greatly appreciated as this project has been going on for days now....

View 3 Replies View Related

Data Migration Script - Execute Stored Procedure Set-based

Sep 18, 2013

I am writing a number of data migration scripts, like the (simplified version) below

Code:
INSERT INTO newDatabase.dbo.DaDestinationTable(col1, col2, col3)
SELECT col1,
col27,
col13
FROM OldDatabase.dbo.DaSourceTable

There are no validation rules defined in the database (don't ask why), only in the program code. Because of the absence of validations in the database, the data migration scripts could violate business rules (NOT NULL, FK violations, domain values in a column, ...).

A solution could be that both the program and the data migration call the same stored procedure to insert records in the destination table, so the validation rules must only be defined in one place (the stored procedure).

I have never used stored procedures in a "set-based" situation. Is this even possible? The only solution I see is to call those sp's in a loop (WHILE or CURSOR). Something like

Code:
SET @my_id = -1
SELECT @my_id = MIN(id)
FROM OldDatabase.dbo.DaSourceTable
WHERE id > @my_id
WHILE @my_id IS NOT NULL

[Code] ....

For each record, the table OldDatabase.dbo.DaSourceTable is hit twice, once to get the next id (@my_id), once to get the column values. I could combine both with one SELECT script by using ROW_NUMBER(), but I doubt that that will perform faster.

I only work set-based, I have barely ever used a WHILE loop, let alone a CURSOR. What the consequences will be on performance. There are millions of records that have to be migrated.

I was thinking of CROSS APPLY, but you can't use that in combination with a SP.

View 6 Replies View Related

Stored Recursive Procedure

Mar 11, 2007

Hi,
I would like some help on a stored recursive procedure I have been working on for my assigment. I had the solution from my course master some time back, but accidentally deleted the file before finishing the course, and would like the solution to that problem.
The questions are as follows:
1) Create a recursive stored procedure that counts from 1 to 10
2) Create a recursive stored procedure that counts from 10 to 1

I believe there's more than one approach in solving these procedures, and any feeback is welcome.

cheers

View 1 Replies View Related

Recursive Stored Procedure?

Oct 16, 2006

How do I call my Stored Procedure recursively:CREATE PROCEDURE dbo.GetParentIONode(@IONodeID int,@FullNodeAddress char(100) OUTPUT)ASBEGINDECLARE @ParentIONodeID intIF EXISTS (SELECT ParentIONodeID FROM IONodes WHERE IONodeID = @IONodeID)BEGINSET @FullNodeAddress = CAST((SELECT ParentIONodeID FROM IONodes WHEREIONodeID = @IONodeID) AS VARCHAR) + ' / ' + @FullNodeAddress--CALL SP Again with @ParentIONodeID and @FullNodeAddress untilParentIONodeID = NULLSELECT @FullNodeAddressENDENDGO

View 4 Replies View Related

Stored Procedure Based Custom Conflict Resolver Truncates Data

May 17, 2007

I created a stored procedure based custom conflict resolver in SQL 2005, I return the winning result set and also save that result set to a test table to compare the values. The values saved to the test table are correct but some of the values saved as the conflict winter are truncated.

Example a char(3) filed is updated at the subscriber as €˜111€™ and updated at the publisher as €˜222€™, in my custom conflict resolver if I use the value from the subscriber the conflict resolver updates the field as €™11 €˜, if I use the publisher value the conflict resolver updates the field as €™22 €˜. Now the same records is saved to the test table correctly as either €˜111€™ or €˜222€™ depending on the logic I used. So the result set has the correct values, its after the custom conflict resolver is called where the values is somehow truncated. Has anybody run into this before and what steps can I take to avoid this.

Thank you,
Pauly C

View 1 Replies View Related

'Recursive Stored Procedure In SQL SERVER

Aug 31, 2003

Hi,

I have 2 SQL SERVER tables MSTHDRML (Header table) & MSTDTLML(details Table)

MSTHDRML

MLID int 4
MLITemID int 4
ConcatStringvarchar 20
EffectiveDateFromsmalldatetime
EffectiveDateTodatetime

MSTDTLML

MLID int40
ItemID int40
ConcatStringvarchar201
Qty money81

The MLID in the header table will be generated automatically.All the Parents will be stored in the HEADER and their childs in the DETAIL.When a child is added to a parent,the Parent's MLID will be stored in the MLID field in the DETAIL table with the newly added child.That child will come to the PARENT table when a child is added to that.The MLITEM id in the parent table can be repeated when that item undergoes a rivision.But the MLID for this will be a new one.An item in the Parent Table can have any number of childs and these childs can have any number of children(there is no limit for the level.)

Some Sample Data

MSTHDRML
--------------
MLIDMLITemID ConcatStringEffectiveDateFromEffectiveDateTo
11000 56V 01/06/200331/12/9999
21003 Red 01/08/200331/12/9999
31001 01/08/200331/12/9999
41007 01/08/200331/12/9999
51008 01/08/200331/12/9999
61002 01/08/200331/12/9999
71005 01/08/200331/12/9999
82000 01/08/200331/12/9999




MSTDTLML
--------------
MLIDItemIDConcatStringQty
11001Round 10
11002Square 20
21004Blue 19
11005Green 22
31007Flat 223
41008 100
51009 200
61010 11
71011 22
71010 45
71012 454
82001 5


Now if i select an item id '1000' (for example from the Header Table) with a concatstring (it could be without a concat string also).all its childs and their children should be printed in a report like the following

1000
|
--- 1001
| |
| --1007
| |_ 1008
----1002 |__1009
| |_1010
|
----1005

************************************************** ***************************
I NEED TO CREATE THE TREE USING BOTH THE HEADER(MSTHDRML) AND THE DETAIL TABLE(MSTDTLML)
************************************************** ***************************


How can this be done.Is it necessary to use a recursive function in a stored procedure to generate this ...... i have never used Recursive function in SQL SERVER Stored Procedures.Can anyone help me on this(with Code).if not stored procedure, then what else can be done for this.

View 1 Replies View Related

Recursive Stored Procedure Problem

Feb 10, 2008

thnx

View 3 Replies View Related

Recursive Calls To Stored Procedure

Aug 24, 2007

I need to develope a stored procedure (eventually called by a trigger) that creates a record in an event table for all the descendants of a drawing. There are 3 tables involved as example tables shown below:



DwgTable


DwgID (integer)--drawing record identifier

PrntDwgID (integer)--parent drawing record identifier (a previously defined DwgID from this table)

DwgEventTable


DwgEventID (integer)--record identifier

DwgID (integer)--value from DwgTable

EventID (integer)--value from EventTable

EventTable


EventID
There are other fields in two of the tables and only the fields shown in the DwgEventTable, but only the fields shown are required for adding a record in the DwgEventTable for a new event in the EventTable. The problem is identifying all the DwgID's of the descendant of the DwgID where the EventID occurred. There may be 0 to N descendants in 0 to N generations. I need to add a record for the original DwgID and all the descendant DwgID's in the DwgEventTable for the event identified by EventID.

I could do this from the client side, but a better place would be from the server side. I need some clue(s) on how to start coding a recursive stored procedure in SQL Server 2005. From what I have read, you cannot create a managed code procedure that appends or updates records--if managed code can add/modify records then I can do the above with managed code procedure.

Any Suggestions?

View 4 Replies View Related

SQL 2012 :: SSIS Passing Parameters To Stored Procedure That Changes Based On The Data Being Passed?

Jun 23, 2015

Using the following:

SQL Server: SQL Server 2012
Visual Studio 2012

I have created an SSIS package where I have added an Execute SQL Task to run an existing stored procedure in my SQL database.

General Tab:

Result Set: None
Connection Type: OLE DB
SourceType: Direct Input
IsQueryStoredProcedure: False (this is greyed out and cannot be changed)
Bypass Prepare: True
SQL Statement: EXEC FL_CUSTOM_sp_ml_location_load ?, ?;

Parameter Mapping:

Variable Name Direction Data Type Prmtr Name Prmtr Size
User: system_cd Input NVARCHAR 0 10
User: location_type_cd Input NVARCHAR 1 10

Variables:

location_type_cd - Data type - string; Value - Store (this is static)
system_cd - Data type - string - ??????
The system code changes based on the system field for each record in the load table

Sample Data:

SysStr # Str_Nm
3 7421Store1
3 7454Store2
1815061Store3
1815063Store4
1615064Store5
1615065Store6
1615066Store7
7725155Store8

STORED PROCEDURE: The stored procedure takes data from a load table and inserts it into another table:

Stored procedure variables:
ALTER PROCEDURE [dbo].[sp_ml_location_load]
(@system_cd nvarchar(10), @location_type_cd nvarchar(10))
AS
BEGIN .....................

This is an example of what I want to accomplish: I need to be able to group all system 3 records, then pass 3 as the parameter for system_cd, run the stored procedure for those records, then group all system 18 records, then pass 18 as the parameter for system_cd, run the stored procedure for those records and keep doing this for each different system in the table until all records are processed.

I am not sure how or if it can be done to pass the system parameter to the stored procedure based on the system # in the sys field of the data.

View 6 Replies View Related

Recursive Stored Procedure To Populate Tree

Jan 17, 2008

I apologize if I posted in the wrong section, but I cannot find a solution to this. I was hoping that some one can help me figure this out.
I need this solution in a stored procedure VS using dataset because there are thousands of categories and it is extremely slow with a dataset.
I have a category table
ID intPARENTID intNAME
SAMPLE DATA:








ID
NAME
PARENT_ID

1
ANIMALS
0

2
DOGS
1

3
CATS
1

4
Abyssinian
3

5
Persian
3

6
Rurkish Van
3

7
Dalmation
2

8
German Shepherd
2

9
Irish Setter
2

10
Bulldog
2
 
I need the stored proc to return results in a single record set like this:
ANIMALS - DOGS - - Dalmation - - German Shepherd - - Irish Setter - - Bulldog - CATS - - Abyssinian - - Persian - - Turkish Van
Seems fairly easy but I have been battling with this for days now.
Thank you in advance,
EL

View 7 Replies View Related

How To Write A Recursive Query?

Dec 23, 2004

I am wondering if there is some type of recursive query to return the values I want from the following database.

Here is the setup:

The client builds reptile cages.

Each cage consists of aluminum framing, connectors to connect the aluminum frame, and panels to enclose the cages. In the example below, we are not leaving panels out to simplify things. We are also not concerned with the dimensions of the cage.

The PRODUCT table contains all parts in inventory. A finished cage is also considered a PRODUCT. The PRODUCT table is recursively joined to itself through the ASSEMBLY table.

PRODUCTS that consist of a number of PRODUCTS are called an ASSEMBLY. The ASSEMBLY table tracks what PRODUCTS are required for the ASSEMBLY.

Sample database can be downloaded from http://www.handlerassociates.com/cage_configurator.mdb

Here is a quick schema:

Table: PRODUCT
--------------------------
PRODUCTIDPK
PRODUCTNAMEnVarChar(30)


Table: ASSEMBLY
--------------------------
PRODUCTIDPK(FK to PRODUCT.PRODUCTID)
COMPONENTIDPK(FK to PRODUCT.PRODUCTID)
QTYINT


I can write a query that takes the PRODUCTID, and returns all



PRODUCT
=======
PRODUCTIDPRODUCTNAME
--------------------
1Cage Assembly - Solid Sides
2Cage Assembly - Split Back
3Cage Assembly - Split Sides
4Cage Assembly - Split Top/Bottom
5Cage Assembly - Split Back and Sides
6Cage Assembly - Split Back and Top/Bottom
7Cage Assembly - Split Back and Sides and Top/Bottom
833S - Aluminum Divider
933C - Aluminum Frame
10T3C - Door Frame
11Connector Kit
12Connector Socket
13Connector Screws



ASSEMBLY
=========
PRODUCTIDCOMPONENTQTY
---------------------
198
1104
1111
211
281
311
381
411
481
511
582
611
682
711
783
11128
11138



I need a query that will give me all parts for each PRODUCT.

Example: I want all parts for the PRODUCT "Cage Assembly - Split Back"

The results would be:


PRODUCTIDPRODUCTNAME
--------------------
2Cage Assembly - Split Back
1Cage Assemble - Solid Back
933C - Aluminum Frame
10T3C - Door Frame
11Connector Kit
833S - Aluminum Divider
12Connector Socket
13Connector Screws

Is it possible to write such a query or stored procedure?

View 1 Replies View Related

Need To Write A Stored Procedure

May 10, 2007

Hi,I need to write a stored procedure to check if the string = "web_version" exists in another string called FromCode.The stored procedure accepts 2 parameters like this:Create proc [dbo].[spGetPeerFromCode]( @FromCode VARCHAR(50)) (@WebVersionString VARCHAR(50))as   please assist. 

View 1 Replies View Related

How To Write Stored Procedure?

Jan 28, 2008

 
Hi all,
   I want to write a stored procedure for the following,
  The table have the following field,
  CategoryID, CategoryName,                    Parent_categoryID
  123             Kids Dresses                        0
  321             Kids Boys                            123
  322             Kids Baby                            123
  401             Kids Boys school Uniform     321
  501            Kids Boys Formals                321
  541            Kids Baby school Uniform      322
  542            Kids Baby Formals                322
  601            Household Textile                  0
  602           Bathrobe                               601
  603           Carpet                                  601
  604           Table Cloth                           601
 
 From the above example the categoryID acts as a parent_categoryID for some products,
 when i pass a categoryID the stored procedure should return all the categoryID which are subcategory to given categoryID,
 subcategory may contain some subcategory, so when i give a categoryID it should return all the subcategoryID.
 For example when i pass categoryID as 123 it should return the following subcategoryIDs
 321,322,401,501,541,542 because these are all subcategory of categoryID 123.
 How to write stored procedure for this?
 
Thanks!
 

View 2 Replies View Related

How To Write Stored Procedure

Mar 21, 2007

Hai Friends,
I heard that stored procedures can be written using two servers
how to write stored procedures by using two servers
CAN ANYONE GIVE INFORMATION ABT THIS

Malathi Rao

View 4 Replies View Related

Where Do You Write A Stored Procedure?

Mar 21, 2008

Hi, where do you write an SQL stored procedure?

View 1 Replies View Related

How To Write Stored Procedure With Two Parameters

Aug 23, 2007

 How to write stored procedure with two parametershow to check those variables containing  values or  empty in SP
 if those two variables contains values they shld be included in Where criteiriea in folowing Query with AND condition, if only one contains value one shld be include not other one       
Select * from orders  plz write this SP for me thanks  

View 3 Replies View Related

How To Write A Stored Procedure In SQL Server2000?

Jan 28, 2008

 
Hi all,
 
  I want to write a stored procedure for the following,
  The table have the following field,
  CategoryID, CategoryName,                    Parent_categoryID
  123             Kids Dresses                        0
  321             Kids Boys                            123
  322             Kids Baby                            123
  401             Kids Boys school Uniform     321
  501            Kids Boys Formals                321
  541            Kids Baby school Uniform      322
  542            Kids Baby Formals                322
  601            Household Textile                  0
  602           Bathrobe                               601
  603           Carpet                                  601
  604           Table Cloth                           601
 
 From the above example the categoryID acts as a parent_categoryID for some products,
 when i pass a categoryID the stored procedure should return all the categoryID which are subcategory to given categoryID,
 subcategory may contain some subcategory, so when i give a categoryID it should return all the subcategoryID.
 For example when i pass categoryID as 123 it should return the following subcategoryIDs
 321,322,401,501,541,542 because these are all subcategory of categoryID 123.
 How to write stored procedure for this?
 
Thanks!

View 6 Replies View Related

Can Anyone Help Me To Write A Stored Procedure For The Following Scenario...

Feb 7, 2008

Hai friends, 
The project i'm working on is an asp.net project with SQL Server 2000 as the database tool.
I've a listbox (multiline selection) in my form, whose selected values will be concatenated and sent to the server as comma separated numbers (Fro ex: 34,67,23,60).Also, the column in the table at the back end contains comma separated numbers (For ex: 1,3,7,34,23).
What i need to do is -
1. Select the rows in the table where the latter example has atleast one value of the former example (In the above ex: 34 and 23).
2. Check the text value of these numbers in another table (master table) and populate the text value of these numbers in a comma separated format in a grid in the front end.
 I've programmed a procedure for this. but it takes more than 2 minutes to return the result. Also the table has over 20,000 rows and performance should be kept in mind.
Suggessions on using the front-end (asp.net 2.0) concepts would also be a good help.
 Anybody's helping thought would be greatly appreciated...
Thanks lot...

View 2 Replies View Related

Read / Write Into .doc From SQL Stored Procedure

Jun 25, 2007

I need to create a flat file as word document, may i know how to write text from stored procedure if a file is already exist then the text will append, how to do it ?



Thank you.

View 1 Replies View Related

Hi I Want To Know How To Write Stored Procedure ..then I Have To Include (IF Condition ) With SP ..

Sep 20, 2007

hi i want to know how to write  stored procedure ..then i have to include (IF condition ) with SP ..
let me this post ..................anybody ??????????

View 5 Replies View Related

Could You Write A Special Stored Procedure For Me In SQL 2005?

Apr 6, 2006

Could you write a special stored procedure for me in SQL 2005?
When I execute the SQL "select TagName from Th_TagTable where IDTopic=@IDTopic" , it return several rows such as TagName= SportTagName= NewTagName= Health
I hope there is a stored procedure which can join all TagName into a single string and return,it means when I pass @IDTopic to the stored procedure, it return "Sport,New,Health"
How can write the stored procedure?

View 2 Replies View Related

Stored Procedure To Read And Write Between XML And SQLServer

Mar 28, 2004

Hi All,
I need some help from you experts.

I need to develop something that reads from xml files and writes in to sqlserver, also it should read from SQLServer and writes to xml.

I should be able to give this as a job to exectue daily ,etc.

Can we do this using stored procedures in SQLServer.
Pls paste some sample code, if any or direct me to any url with better info.

Thanks in advance

View 11 Replies View Related

Write To A Text File From A Stored Procedure

Oct 19, 2011

I have a sp which saves the necessary information regarding the status of action(whether success or failure, rows affected etc) to a log table say( StatusLog )After this, I was sending a database mail with information taken from the log table via sp_send_dbmail. Now I would like to write the status information to a 'txt' file instead of sending via mail.How can I write to a text file from a stored procedure in ms sql server 2005?

View 6 Replies View Related

Write An Xml File With A Stored Procedure RESOLVED

Sep 22, 2006

Can you, and if yes, how do you, write an xml file using a stored procedure. For example the sp below writes this new record to a sql table. How would I change it to write it to an xml file ?

CREATE Procedure [spOB_AddtblOB_Properties]

@strPropertyRef varchar (100),
@strRouteNo numeric,
@strAdd1 nvarchar(1000),
@strPostcode nvarchar(10)

as

Insert into tblOB_Properties (
PR_PropertyRef,
PR_RouteNo,
PR_Add1,
PR_Postcode)

values(
@strPropertyRef,
@strRouteNo,
@strAdd1,
@strPostcode)
GO

View 1 Replies View Related

Is It Possible To Write Clr Stored Procedure With Out Using Adomd Server.

Dec 5, 2006

hi,

I need to write a clr stored prodeure.i have to call that stored procedure from my prediction query.My Application is going to make use of that query to get the prediction output.

Is it possible to write clr stored procedure with out using adomd server.How?

For example:

In My Assembly i am having a function PredictPerformance(),Which is having my DMX Query.I need to execute that function from my analysis service by calling like this,

select aly. PredictPerformance() FROM [Model].

how to do this?

View 1 Replies View Related

Could You Write A Special Stored Procedure For Me In SQL 2005?

Aug 19, 2007



When I execute the SQL "select TagName from Th_TagTable where IDTopic=@IDTopic" , it return several rows such as
TagName= http://www.hothelpdesk.com
TagName= http://www.hellocw.com
TagName= http://www.supercoolbookmark.com


I hope there is a stored procedure which can join all TagName into a single string and return,
it means when I pass @IDTopic to the stored procedure, it return "http://www.hothelpdesk.com, http://www.hellocw.com, http://www.supercoolbookmark.com"

How can write the stored procedure?

View 1 Replies View Related

How Should I Write Stored Procedure And Pass It Into Sql Server Express?

Feb 28, 2008

 Hi i m using vwd2005 express and sql express.1. I want to write stored procedure in sql express using sql server management studio express. I m not sure where to write and how to execute the stored procedure in sql server management studio express. Can any one explain the steps required to achieve this? 2.And what is the difference between creating database using:-       a. right click the project in solution explorer-> add new item->SQl database(creating .mdf file)and b.clicking a database explorer->data connection->Add connection ....       thanks.  jack.  

View 4 Replies View Related

How To Write Such A Stored Procedure To Return Monthly Sales?

Mar 8, 2005

I have a Orders and OrderDetails table having the columns listed below:

Orders (OrderID, OrderDate, CustomerID, ...)
OrderDetails (OrderID, ProductID, UnitPrice, Quantity, ...)

Now, I want to obtain monthly sales from the data in the two tables by passing in a Year parameter. How to develop such a stored procedure? I have no idea where to get started. I was thinking to call a SELECT statement on each month. But, things trouble me are:

1. how to loop through each month to make a SELECT query for each month for a given Year? Use a cursor or what?
2. how to determine month boundary for a given year and construct the where clause on OrderDate using the month boundary for the SELECT query ? What happens if it is a leap year?
3. how to stop processing for the rest of the year when last order month is done?

Any suggestion would be appreciated. Thanks.

View 1 Replies View Related

How To Write Stored Procedure To Deal With This Kind Of Question?

Sep 13, 2005

I can get following data information from table1Name                        DescriptionA                              AviationA01                           Aviation GeneralCA01                        CapitalCA01-006                 NEW CTB SignageA02                           CapitalCA05-005                  East End RoadwayCA05-006                 Modify RoadHow do I write stored procedure to get following results based on the data from table1Code                        Name                        Description                        Level  1                               A                              Aviation                                    1  1.01                         A01                           Aviation General                        2  1.01.01                    CA01                        Capital                                       3  1.01.01.006            CA01-006                 NEW CTB Signage                    4  1.02                          A02                           Capital                                      2  1.02.01                    CA05-005                  East End Roadway                    3  1.02.01.006             CA05-006                 Modify Road                              4Thank a lot!

View 1 Replies View Related

T-SQL (SS2K8) :: Write A Stored Procedure That Will Be Used Registered Server?

Mar 14, 2014

Is it possible to write a stored procedure that will be used registered server?

For example I have registered server named 'Test Servers' and I want to use it in stored procedure

View 3 Replies View Related

SQL 2012 :: How To Write Insert Into With Select And Where In Stored Procedure

Sep 25, 2015

I am trying to write a stored procedure that is an INSERT INTO <sql table> FROM <other sql tables> WHERE <where clause>.

I need to insert 3 columns from multiples SQL tables into one SQL table. Here is my code snippet:

ALTER PROCEDURE [dbo].[sp_insert_test]
@MID INT OUTPUT,
@CIDINT OUTPUT,
@MemberNVARCHAR OUTPUT

[Code] ....

i cannot pass any of the values to the tblVotings table and not sure how to enter the @MID, @CID and @Member to the INSERT INTO statement.

View 7 Replies View Related







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