Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 12»»

Recursive Stored Procedure Expand / Collapse
Author
Message
Posted Thursday, October 3, 2013 3:42 PM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Saturday, September 13, 2014 1:40 PM
Points: 10, Visits: 190
I have requirement where I need to create stored procedure which accepts States(Multiple) and StudentID(Single) .

User will input the set of State's and also mention a single student ID, so my procedure should bring the details of that studentID from different states.

Assuming the Data for different state is in each different database with same table name.

I am not able to figure out how to make the SP recursive on state by keeping the studentID constant.

Result set is somewhat looks like below.



Help on this is greatly appreciated.

Thanks,
VSP
Post #1501365
Posted Friday, October 4, 2013 8:52 AM


Mr or Mrs. 500

Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500

Group: General Forum Members
Last Login: Today @ 1:56 PM
Points: 592, Visits: 920
Can you provide some DML and some sample data with a required output? This will help you get an answer quicker.



Microsoft Certified Master - SQL Server 2008
Follow me on twitter: @keith_tate

Forum Etiquette: How to post data/code on a forum to get the best help
Post #1501626
Posted Friday, October 4, 2013 9:36 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Saturday, September 13, 2014 1:40 PM
Points: 10, Visits: 190
Thank you Keith for your reply. Sorry for not providing the enough info.

CREATE PROCEDURE [dbo].[USP_Student_History_Search]
@State VARCHAR(2)
@StudentID INT
AS
SET NOCOUNT ON;

DECLARE @index INT
DECLARE @N INT =SELECT CHARINDEX(',',@State)
WHILE @Index <= @N

BEGIN
SET @DB = N'Select
[State],
[StudentID],
[Marks]
FROM [Academics_'+@State+'].[dbo].[StudentsHistory]'

Declare @SP table
( [State],
[StudentID],
[Marks]
)
SET @index = @index + 1
END

INSERT INTO @SP VALUES(SELECT FROM @DB)


If the user passes states - 'TX, MI, CA' then the query should loop over three states from 3 different databases one after other and pull the information.
and finally place it in a single table like the picture shown above.

help is greatly appreciated.
Post #1501649
Posted Friday, October 4, 2013 10:21 AM
SSC Journeyman

SSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC Journeyman

Group: General Forum Members
Last Login: Thursday, September 18, 2014 6:28 AM
Points: 94, Visits: 333
one of many ways:


if isnull(object_id('result'), 0 ) <> 0
drop table result

create table result ( state varchar(2), studentId varchar, marks varchar )


declare @db varchar(500)
DECLARE @index INT =0
DECLARE @N INT = len(@State)-len(replace( @State,',',''))

WHILE @Index <= @N
BEGIN

SET @DB = N' insert into result Select
[State],
[StudentID],
[Marks]
FROM [Academics_'+left(@State,2)+'].[dbo].[StudentsHistory]'

SET @index = @index + 1
if @index <= @n
set @state = right(@state, len(@state)-3)

exec @db

end
select * from result
Post #1501670
Posted Sunday, October 6, 2013 12:10 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Today @ 8:46 PM
Points: 35,218, Visits: 31,676
Both of the above methods leave you wide open to SQL Injection attacks.

With that in mind, let me ask... are all of the Academics_xx tables identical in every way except for their name and content? If so, it would likely be much better to create a partitioned view using the tables and join to that single view using the splitup version of the states parameter, instead.


--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #1501939
Posted Wednesday, October 9, 2013 12:23 PM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Saturday, September 13, 2014 1:40 PM
Points: 10, Visits: 190
Thank you SrcName for your reply. I have followed your query and came up with this sample query. It was successfully created but when I am trying to execute, I am getting the below error.

Error Message:
Msg 214, Level 16, State 2, Procedure sp_executesql, Line 1
Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.
Msg 214, Level 16, State 2, Procedure sp_executesql, Line 1
Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.

MyQuery:
CREATE PROCEDURE [dbo].[uspChannelHistory]
( @Channel_nbr INT
, @ChannelLevelID INT
, @ChannelName VARCHAR(50)
, @ChannelID INT
, @StateCode VARCHAR(60)
)
AS
SET NOCOUNT ON

IF OBJECT_ID('tempdb..##Result') IS NOT NULL
DROP TABLE ##Result

CREATE TABLE ##Result
(
Channel_nbr INT,
ChannelLevelID INT,
ChannelName VARCHAR(50),
ChannelID INT,
StateCode VARCHAR(2)
)

DECLARE @DB VARCHAR(500)
DECLARE @Count INT = 0
DECLARE @N INT = LEN(@StateCode) - LEN(REPLACE(@StateCode, ',', ''))

WHILE @Count <= @N
BEGIN
SET @DB = N'INSERT INTO ##Result
SELECT
Channel_nbr
ChannelLevelID
ChannelName
ChannelID
StateCode
FROM [Sample_'+ LEFT(@StateCode, 2) +'].[dbo].[StudentHistory]
WHERE Channel_nbr = @Channel_nbr
AND ChannelLevelID = @ChannelLevelID
AND ChannelName = @ChannelName
AND ChannelID = @ChannelID'
SET @Count = @Count + 1
IF @Count <= @N
SET @StateCode = RIGHT(@StateCode, LEN(@StateCode) - 3)

EXEC sp_executesql @DB, N'@Channel_nbr INT , @ChannelLevelID INT , @ChannelName VARCHAR(50), @ChannelID INT, @StateCode VARCHAR(60) ', @Channel_nbr, @ChannelLevelID, @ChannelName, @ChannelID, @StateCode
SELECT * FROM ##Result
END

--EXEC [dbo].[USP_Producer_History_Search] 2,4,'Media', 4, 'FL, TX'
Post #1503254
Posted Wednesday, October 9, 2013 12:42 PM


Mr or Mrs. 500

Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500

Group: General Forum Members
Last Login: Today @ 1:56 PM
Points: 592, Visits: 920
sp_execute needs the statement to be unicode, so change @DB to NVARCHAR...



Microsoft Certified Master - SQL Server 2008
Follow me on twitter: @keith_tate

Forum Etiquette: How to post data/code on a forum to get the best help
Post #1503263
Posted Wednesday, October 9, 2013 1:07 PM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Saturday, September 13, 2014 1:40 PM
Points: 10, Visits: 190
Thank you Keith for prompt reply. I have changed the @DB to NVARCHAR.
SP Executed succeessfully but when I executed by passing parameters it throws error.

Msg 207, Level 16, State 1, Line 19
Invalid column name 'ChannelName'.
Msg 207, Level 16, State 1, Line 20
Invalid column name 'ChannelID'.
Msg 207, Level 16, State 1, Line 6
Invalid column name 'ChannelName'.
Msg 207, Level 16, State 1, Line 7
Invalid column name 'ChannelID'.
Msg 207, Level 16, State 1, Line 19
Invalid column name 'ChannelName'.
Msg 207, Level 16, State 1, Line 20
Invalid column name 'ChannelID'.
Msg 207, Level 16, State 1, Line 6
Invalid column name 'ChannelName'.
Msg 207, Level 16, State 1, Line 7
Invalid column name 'ChannelID'.


But I have those fields in the base table as well as I declared those in the temp table also.
Post #1503269
Posted Wednesday, October 9, 2013 1:16 PM


Mr or Mrs. 500

Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500

Group: General Forum Members
Last Login: Today @ 1:56 PM
Points: 592, Visits: 920
add a "select @DB" before you run the sp_execute statement and verify that the query looks correct.



Microsoft Certified Master - SQL Server 2008
Follow me on twitter: @keith_tate

Forum Etiquette: How to post data/code on a forum to get the best help
Post #1503274
Posted Wednesday, October 9, 2013 2:15 PM
SSChasing Mays

SSChasing MaysSSChasing MaysSSChasing MaysSSChasing MaysSSChasing MaysSSChasing MaysSSChasing MaysSSChasing Mays

Group: General Forum Members
Last Login: Thursday, September 11, 2014 8:23 AM
Points: 625, Visits: 2,128
looks like some missing commas
Post #1503298
« Prev Topic | Next Topic »

Add to briefcase 12»»

Permissions Expand / Collapse