Monday, 4 March 2013

MSSQL How to add sub query to stored procedure

Example of stored procedure with sub query and if else statement

Watch this example online

I have 2 tables
GroupMaster adn
StyleMaster

When user is calling TestSubQuery - he/she has to provide us with StyleName.
Then, in stored procedure, I am checking what is the group that this style belongs to.
If group id is 1 then program is returning details about that group
If not, program is returning all styles that belong to another group.


CREATE PROCEDURE TestSubQuery
    @StyleName As VarChar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
   
    Declare @GroupId int
   

    Select @GroupId = GroupId From StyleMaster Where(StyleName = @StyleName)
   
    If @GroupId = 1
    Begin
        Select GroupId, GroupName, GroupDescription
        From GroupMaster
        Where GroupId = @GroupId
    End
    Else
    Begin
        Select StyleId, StyleName, StyleDescription
        From StyleMaster
        Where GroupId = @GroupId
    End
END
GO

No comments:

Post a Comment