Skip to main content

Flexible Custom Reports for SQL Server

Flexible Custom Reports for SQL Server

This article is written by developer for other developers, sharing my experience with a technique that I found in Kimberly Tripp's SQL Server blog article titled " Building High Performance Stored Procedures". In her article, she demonstrated a dynamic SQL technique that allows for "Query By Example" screens that allow most fields to be optional. I would strongly encourage you to read her article along with the associated cautionary notes. I would further add that this technique should not be used for any automated reporting tasks. If you have a known report requirement, make a dedicated stored procedure for it!

I am writing this article to share a few refinements as well as a nice way to catch refactoring dependencies when this stored procedure is part of a database project in Visual Studio.  As a point of reference, I used MS SQL 2014 and Visual Studio 2017, but the technique should work with older versions of SQL.

1) Include a reference copy of the QUERY in the stored procedure.  This might create a junk query plan, but it will allow you to find table and field references in Visual Studio.  If this causes performance problems, I would love to hear about it.  If we only had conditional compilation, we could include the reference query in a DEBUG build, but remove it from production builds.  I am aware that I could probably do this with some marker comments and a tricky Perl regular expression, but I try to avoid complexity where I can.

/*
 ** Stored Procedure Comments and History go here **
*/
create procedure Foo_Report_AllInOne
(
   @Key1Id int = null,
   @Key2Id int = null,
   @Name1 varchar(50) = null,
   @Start datetime = null,
   @End datetime = null
)
as
set nocount on;

-- check parameters
if ( @Key1Id is null
    and @Key2Id is null
    and @Name1 is null
    and @StartDate is null
    and @EndDate is null )
begin
    raiserror ('You must supply at least one parameter.', 16, -1);
    return;
end;

declare @ExecStr nvarchar (4000),
        @Recompile  bit = 0;
 
if (1=0)
begin
   -- include a non-executing version of the query with ALL conditional fields referenced, so we
   -- can find this code when refactoring.
   select
     Key1Id, Field1, Key2Id, Field2, Name1, EventDate
     from myschema.FOO
     where 1=1
     and Key1Id = @Key1Id
     and Key2Id = @Key2Id
     and Name1 like @Name1
     and EventDate >= @Start
     and EventDate < @End
end

-- continue with code from the Kimberly Tripp article.

Everything inside the "if (1=0)" code block MUST be a full copy of the dynamic query with all possible options included, otherwise it has no value for field reference and refactoring purposes. Since this query will never execute, it doesn't have to be a logically sound query.  This also allows you to quickly copy and paste new query code (down to the "where 1=1") into your dynamic query after Visual Studio has checked the syntax.

2) Include a print statement at the bottom of the procedure with all of the parameters and the dynamic query statement to be executed.  Ideally you would print a declare statement, set statements and the dynamic code so it could be manually executed for testing and debugging.  In fact, the best way to debug dynamic code is just to comment out the sp_executesql call (uncomment the print statements if needed) and view the generated code.

3) If your query is longer than 4000 characters, use care to avoid truncating and remember to always append to the larger type - @ExecStr in our case.

Comments

Popular posts from this blog

Castle ActiveRecord with DetachedCriteria

My current development environment is Visual Studio Express C# Edition (read that as free ), Castle ActiveRecord's latest svn trunk(usually within a few days), and NHibernate svn trunk. As of NHibernate version 1.2.0, there is a very cool new class out there ... DetachedCriteria. This class lets you set all of your Castle relational attributes like BelongsTo, HasMany, etc. as lazy fetch, and over-ride this for searches, reports, or anytime you know ahead of time that you will be touching the related classes by calling detachedCriteria.SetFetchMode(..., FetchEnum.Eager). As a good netizen, I have tried to contribute to NHibernate and Castle ActiveRecord even if only in the smallest of ways . Oh yeah, I tried mapping to a SQL VIEW, and it worked GREAT! I received a comment after my last post, indicating that there is a better way, and I am sure of it, but the view guaranteed that I only have one database request for my dataset. NHibernate was wanting to re-fetch my missing as...

Castle ActiveRecord calling a Stored Procedure

Update: I have contributed patch AR-156 that allows full integration of Insert, Update and Delete to ActiveRecord models . If you've been reading my blog lately, you know that I have been seriously testing the Castle ActiveRecord framework out. I really love it, but I have an existing Microsoft SQL Server database with many stored procedures in it. I have tested the ActiveRecord model out, and I am sure that I will learn enough to be able to use it for standard CRUD (create, read, update, delete aka. insert, select, update, delete) functionality. BUT ... If I really want to integrate with my existing billing procedures, etc, I will have to be able to call stored procedures. I have taken two approaches ... write the ARHelper.ExecuteNonQuery(targetType, dmlString) method that gets a connection for the supplied type, executes dmlString, and closes it. write the ARHelper.RegisterCustomMapping(targetType, xmlString) method that allows me to add mappings that refer to my auto-gener...

Castle Active Record Code Generator

I have finally released my Code Generator to Google Code as Active-Record-Gen . What does it generate? It generates ActiveRecord classes mainly, but I have used it to generate stored procedures and sys-admin scripts as well. This code generator does not (yet) generate a full Windows application project or a Mono-Rail web site, but the generated code could be used in either. In fact, with a few tweaks, this could be used to generate NHibernate "poco" and .xbm files. If you want to know more, look at the screen shots above, or head over to Google Code and run it. In my haste to make my first EXE release before supper, I forgot to add the Template directory, which should be at the same directory level as the EXE and config files. I just (1.5 hours later) uploaded a new EXE, but 2 people have already downloaded the EXE (not the source though). As for the basic table object, it is built with the following assumptions: Table name is plural, class name is singular. Field ...