Getting Started with Adobe After Effects - Part 6: Motion Blur
First Time? You can support us by signing up. It takes only 5 seconds. Click here to sign up. If you already have an account, click here to login.
Loading

1st Prize - Apple iPad


SQLServer Quiz 2011 - Advantages of With Result Set(Sql Server 2011)

  • In Sql Server 2011(code name Denali ) CTP1, we have With Result Set statement. What is the benefit of having this? In which real time scenario it will be helpful?

    Posted on 03-28-2011 00:00 |
    Niladri Biswas
    7 · 21% · 6710

4  Answers  

Subscribe to Notifications
  • Score
    4

    As per MSDN online:

    WITH RESULT SET syntax allows you to change the names and data types of the returning result set.

    When executing a statement that returns more than one result set, WITH RESULT SET clause gives you ability to specify different definition for every returned result set.

    The clause of the result set definition has a follow structure:

    {
        ColumnName
        DataType
        [ COLLATE collationname]
        [NULL | NOT NULL]
    }
    
    Replied on Mar 28 2011 1:08AM  . 
    Igor Zakharov
    158 · 1% · 300
  • Score
    9

    The benefit of WITH RESULT SET is the ability to control the metadata returned by a stored procedure. As per BOL, EXECUTE (Transact-SQL) there are three options:

    • RESULT SETS UNDEFINED
    • RESULT SETS NONE
    • RESULT SETS ( < resultsetsdefinition > [,...n ] )

    UNDEFINED: there will be no errors related to the shape of the result set. It's basically like the behavior of the EXECUTE statement before DENALI

    NONE: There will be an error if a result set is returned (the result of a PRINT command is not considered a result set though).

    RESULT SETS ( < resultsetsdefinition > [,...n ] ): specify the data type of one or more result sets. There will be an error if the number of returned columns does not match the definition in the RESULTS SETS section. An error will also be raised if the value cannot be converted. This option can be used to change data types (including Nullability setting) and column names.

    There are three real-time scenarios I can think of (or I have found...):

    1. If there is a need to convert a data type or a column name for some applications that currently requires an intermediate storage in a temp table. An example could be sp _who2 with the need to return the SPID column in an INTEGER format as well as unique column names (sp _who2 returns the column name SPID twice).
    2. If there is the need to change the data type of a column but the sproc is used by multiple applications.
    3. When using stored procedures as data sources in SSIS, the data type no longer strictly depends on the data type returned by the sproc.

    The examples above are based on this post over at stackoverflow including the sub-link to James Rowland-Jones' blog

    Replied on Mar 28 2011 1:15PM  . 
    lmu92
    0 · 0% · 0
  • Score
    8

    With Result Sets

    The With Result Sets feature of Denali allow us to change the column names and data types of the result set that a stored procedure returns.

    Before going to explore that,let us observe how in earlier versions of Sql Server (pre-Denali), we used to get the values from an executing stored procedure.

    For this demonstration, we will use the below table (tbl_Test), having 3 columns as the example. alt text

    Now let us populate some records (say 1000) to the table by using the below script Collapse

    -- Drop the table if it exists
    IF EXISTS (SELECT * FROM sys.objects WHERE name = N'tbl_Test' AND type = 'U')
        DROP TABLE tbl_Test
    GO
    SET ANSI_NULLS ON
    GO
    --Create the table
    CREATE TABLE [dbo].[tbl_Test](
        [Id] [int] NOT NULL,
        [Name] [varchar](50) NOT NULL,
        [PhoneNumber] [int] NOT NULL
    ) ON [PRIMARY]
    GO
    
    --Populate the Cte with some records
    ;With Cte(Id,Name,PhoneNo) As (
    Select 
        Id = 1
        ,Name='Name' + CAST( 1 As Varchar(50))
        , PhoneNo=12345678
    Union All 
    Select 
        Id+1
        ,Name= 'Name' + CAST( Id+1 As Varchar(50)) 
        , PhoneNo+1
    From Cte
    Where Id <1000
    )
    --Insert the records into the table
    Insert Into dbo.tbl_test
    Select * From Cte
    Option( Maxrecursion 0)
    
    --Display the records
    Select * 
    From tbl_Test
    

    Running the script will bring the below record set (partial) Collapse

    Id  Name	PhoneNumber
    1   Name1	12345678
    2   Name2	12345679
    3   Name3	12345680
    4   Name4	12345681
    5   Name5	12345682
    

    Let us write a stored procedure for fetching the result from the table tbl_Test. Collapse

    CREATE PROCEDURE dbo.Usp_FetchRecords
    AS
    BEGIN 
    
           Select 
        		Id
        		,Name
        		,PhoneNumber
        	From dbo.tbl_Test
    END
    

    In order to get the result set from an executing stored procedure, there are various approaches available .We will,however, look into one of the approaches

    Temporary Table Approach Collapse

    --If the #Temp object exists in the tempdb, then drop it
    IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
    BEGIN
    Drop Table #Temp 
    END
    
    --Create a temporary table
    CREATE TABLE #Temp 
    (
        Id int, 
        EmpName Varchar(50),
        PhoneNo int 
    ) 
    --Insert records into the Temporary table from the executed stored proc
    INSERT INTO #Temp 
    ( 
        Id
        ,EmpName
        ,PhoneNo
    )
    EXEC dbo.Usp_FetchRecords
    
    --Display the records inserted into the temporary table
    Select * from #Temp
    

    The above approach is fine if we know in advance the columns and their data types being returned by the stored procedure.

    Disadvantages of the pre-Denali approaches are

    1. None of the approach was straight forward. In the sense, we need the help of a temporary table or variable, dispose that once the operation is over;else that will consume unnecessary database space
    2. Process was lengthy
    3. In the case of Open Row Set or Open query, we need to turn on the ‘Ad Hoc Distributed Queries’ feature and then to proceed.
    4. In the case of Temporary table or Table variable approach, we need to know in advance what is the data type of the column

    Denali’s (Sql Server 2011) With Result Set Approach

    Denali’s With Result Set has overcome the above drawbacks. Let us see how. Let us execute the below query(for single result set) Collapse

    EXEC Usp_FetchRecords 
    
    WITH RESULT SETS
    
    (
           (      [Emp Id] int,
    
                  [Emp Name] varchar(50),
    
                  [Phone Number] varchar(50)
    
           )  
    
    )
    

    The output being (partial output) Collapse

    Emp Id  Emp Name	Phone Number
    1   Name1		12345678
    2   Name2		12345679
    3   Name3		12345680
    4   Name4		12345681
    5   Name5		12345682
    

    The general syntax of With Result Set will be Collapse

    WITH RESULT SETS
    
    (
           (      
                 Column Name1 DataType [Size]
                , Column Name2 DataType [Size]
                ,  . .  . .  .  . .  . . . . .
                ,  . . . . . . . . . . . . . . 
                , Column Name-n DataType [Size]
    
           )  
    
          ,
    
           (      
                 Column Name1 DataType [Size]
                , Column Name2 DataType [Size]
                ,  . .  . .  .  . .  . . . . .
                ,  . . . . . . . . . . . . . . 
                , Column Name-n DataType [Size]
    
           )  
           . . . . . . . . . . . . . . . . . .
           . .  . . . . . . . . . . . . . . . 
           ,
    
           (      
                 Column Name1 DataType [Size]
                , Column Name2 DataType [Size]
                ,  . .  . .  .  . .  . . . . .
                ,  . . . . . . . . . . . . . . 
                , Column Name-n DataType [Size]
    
           )      
    )
    

    Henceforth, we can make out that, irrespective of the column name(s) returned in the result set, we can change the column names and it’s data Types as long as the data Type conversion is compatible with the original result set(i.e. the data types defined in the table schema). Else the database engine will report error.

    e.g. in the below example we have changed the Name columns data type(originally as varchar(50)) to int. Collapse

    EXEC Usp_FetchRecords
    WITH RESULT SETS
    
    (
           (      [Emp Id] int,
    
                  [Emp Name] int, -- Changed to int data type
    
                  [Phone Number] varchar(50)
    
           )  
    
    )
    

    Upon execution, we will receive the below error message

    Msg 8114, Level 16, State 2, Procedure Usp_FetchRecords, Line 5 Error converting data type varchar to int.
    

    Whereas changing the same to Text (for example) data type works fine.

    The above query was made for demonstration purpose of transforming a single Result Set with Execute’s With Result Set. However, it can be extended to transform for multiple result set. Let us see how.

    Consider the below stored procedure, which returns two different record sets. Collapse

    CREATE PROCEDURE [dbo].[Usp_ModifiedFetchRecords]
    AS
    BEGIN 
    
           Select 
        		Id
        		,Name
        		,PhoneNumber
        	From dbo.tbl_Test;
    
        	Select
        		Id
        		,Name
        	From dbo.tbl_Test
        	Where PhoneNumber % 2 = 0
    END
    

    The second select statement generates the records for those Names who are having an even digit phone number.

    The partial output is as under after executing the stored procedure alt text

    Now , let us execute the below query Collapse

    EXEC Usp_ModifiedFetchRecords 
    
    WITH RESULT SETS
    
    (
           (      [Emp Id From First Result Set] int,
    
                  [Emp Name From First Result Set] varchar(50),
    
                  [Phone Number From First Result Set] varchar(50)
    
           )  ,
    
            (      [Emp Id From Second Result Set] int,
    
                  [Emp Name From Second Result Set] varchar(50)             
    
           ) 
    
    )
    

    The partial output being alt text

    However, since the stored procedure is returning two record set(in this case), if we try to obtain only one record set in the With Result Sets clause , the engine will report the below error

    Msg 11535, Level 16, State 1, Procedure Usp_ModifiedFetchRecords, Line 11 EXECUTE statement failed because its WITH RESULT SETS clause specified 1 result set(s), and the statement tried to send more result sets than this.

    As can be seen that the With Result Set clause of the Execute command basically does transformation on the result set of the stored procedure. It has eliminated the drawbacks of the aforesaid procedures for sharing data of the stored procedure.

    How can get the values from the With Result Set

    We may sometime need to get the value from the With Result Set clause. In such a case we can go ahead with a Temporary table or Table variable approach.

    Here we will look into the Table Variable Approach Collapse

    Declare @tblStoreWithResultSetsData Table
    ([Employee Id] int
    , [Employee Name] varchar(50)
    ,[Emp Phone No] int)
    
    insert into @tblStoreWithResultSetsData
    
    EXEC Usp_FetchRecords
    
    WITH RESULT SETS
    
    (
           (      [Emp Id] int,
    
                  [Emp Name] varchar(6), -- as a proof of concept, 
        				  --  change the dataType size to 6. 
        				  --	Records will be truncated
    
                  [Phone Number] varchar(50)
    
           )  
    
    ) 
    Select * From @tblStoreWithResultSetsData
    

    The output being as expected (last 10 records shown) alt text

    Applicability

    1. Data conversion will become simpler in SSIS as described well in this article
    2. Changing the data type without changing the schema. Suppose a dotnet application is expecting a Boolean and the underlying schema was designed as of type int for that column.Ideally we do a conversion at runtime as Case When Then 1 Else 0. Instead of that, we can directly change the data type to bit.
    3. Another example can be say the dotnet application is expecting a int but the column type is float.
    4. Another usage may be say the schema has been changed and the DAL layer is not aware of this. May be the same stored procedure is called from multiple places. In such a scenario, we can just change the column names at runtime in the With Result Set so that the table schema as well as the DAL logic will be un touched.

    DrawBacks

    We cannot return selected columns. The number of columns has to be same as that of the result set. For example, if we write something as under Collapse

    EXEC Usp_FetchRecords 
    
    WITH RESULT SETS
    
    (
           (      [Emp Id] int,              
    
                  [Phone Number] varchar(50)
    
           )  
    
    )
    

    The engine will report the below error

    Msg 11537, Level 16, State 1, Procedure Usp_FetchRecords, Line 5 EXECUTE statement failed because its WITH RESULT SETS clause specified 2 column(s) for result set number 1, but the statement sent 3 column(s) at run time.

    Replied on Mar 29 2011 11:30PM  . 
    indika saminda kannangara
    185 · 1% · 251
  • Score
    9

    SQLServer Quiz 2011 - Advantages of With Result Set(Sql Server 2011)

    Solution:

    In SQL Server Versions prior to Denali aka SQL Server 2011, there was no way to call a stored procedure without knowing what is in the result set and dump it to a table. In these older versions of SQL Server, in order to trap the result set from executing a stored procedure, there need to be a way to work around, and this is because there is no way to dynamically know the columns and data types the stored procedure is returning. There was always a limitation in the previous versions of SQL Server that whenever we wanted to change a Column Name or a Data Type within the result set of a Stored Procedure we ended up making changes to all the references within a Stored Procedure. This limitation has been overcome with the release of WITH RESULT SETS feature in SQL Server Denali.

    The WITH RESULT SETS feature does allow us to change the column names and data types of the result set stored procedure returns, however it does not allow us to define a subset of columns to return. Therefore, if a new column is added to the result set of a procedure that is called using WITH RESULT SETS, an error will occur. This is a very useful feature especially when one needs to display a result set of a stored procedure by changing the names and data types of the returning result set. Here, we will take a look at an example which uses the new WITH RESULT SETS feature in SQL Server Denali.

    Let’s take a look at this new feature; first we’ll create a sample stored procedure:

    -- Creating a sample table 
    
    IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbl_Quiz_28]') AND type in (N'U'))
    DROP TABLE [dbo].[tbl_Quiz_28]
    GO
    CREATE TABLE [dbo].[tbl_Quiz_28]
    (
     [ContactID]   [INT]   NOT NULL,
     [ContactPersonType]  [NCHAR](15)  NOT NULL,
     [FirstName]  NVARCHAR(50) NOT NULL,
     [MiddleName]  NVARCHAR(50)  NULL,
     [LastName]  NVARCHAR(50)  NOT NULL,
    ) ON [PRIMARY]
    GO
    
    
    ---Inserting a record into [tbl_Quiz_28] 
    INSERT INTO dbo.tbl_Quiz_28 VALUES (1,'Employee','Abi','C.','Chapagai')
    GO
    
    ---Creating a sample stored procedure  from the demo.
    
    IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Quiz_28]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[Proc_Quiz_28]
    GO
    CREATE PROCEDURE Proc_Quiz_28
    AS
    BEGIN
     SELECT
      ContactID, 
      FirstName + ' ' + MiddleName +' '+ LastName AS Name, 
      ContactPersonType 
     FROM dbo.tbl_Quiz_28
    END
    GO
    
    
    --Execute Stored Procedure 
    EXEC Proc_Quiz_28
    GO
    
    --  Show how  WITH Result Sets Feature Of Denali .
    -- Execute Stored Procedure using  With Result Sets
    
    EXEC Proc_Quiz_28
    WITH RESULT SETS
    (
     ( 
      ContactID INT,
      ContactPersonName VARCHAR(150),
      ContactPersonType VARCHAR(15)
     ) 
    ) 
    GO
    

    In the above example, we can see that using WITH RESULTS SETS feature of SQL Server Denali we have changed the Column Name and Data Type to meet our needs irrespective of the Column Name and Data Type returned within the result set of the Stored Procedure. The Column Name is changed from Name (frist name, middle name and last name) to ContactPersonName and also Data Type for Name is changed from NVARCHAR to VARCHAR and Data Type for ContactPersonType is changed from NCHAR to VARCHAR while displaying the result set. This feature can be very useful when executing a stored procedure in SSIS where we can execute the Stored Procedure with the required columns names and appropriate data types.

    Issue that I have encountered with this new feature:

    • The EXECUTE syntax seems to be potential error creator if columns, types and result set counts are not explicitly defined correct.

    To summarize, following are the real time benefits of using WITH RESULT SET:

    • When there is a need to convert a data type and a column name.

    • Change the data type of a column when stored procedure is used by several applications.

    • More manageable and capability to control the metadata returned by stored procedures.

    • We can use WITH RESULT SET with slow schema change.

    • It helps to fix output of system stored procedures, such as sp_who2

    • Easier translation in SSIS.

    This is actually a neat feature in Denali since many of us are waiting for this kind good feature to be used in our code.

    Reference: http://sqlblog.com/blogs/aaronbertrand/archive/2010/12/20/sql-server-v-next-denali-metadata-discovery.aspx

    Thanks,

    Abi

    Replied on Apr 25 2011 9:38PM  . 
    Abi Chapagai
    69 · 3% · 808

Your Answer


Sign Up or Login to post an answer.
Please note that your answer will not be considered as part of the contest because the competition is over. You can still post an answer to share your knowledge with the community.

Copyright © Rivera Informatic Private Ltd.