Generating Charts and Drawings in SQL Server Management Studio
You don't have to settle for T-SQL's monochrome text output. These stored procedures let you quickly and easily turn your SELECT queries' output into colorized charts and even computer-generated art.To turn your own data into a line, column, area, or bar chart using the Chart stored procedure, you need to design a SELECT query that serves as the first parameter in the stored procedure call.
The monochrome text output that T-SQL provides by default isn't very impressive, especially to business analysts and other end users. Although you can use the geometry data type introduced in SQL Server 2008 to add images and colors to T-SQL output, you have to define every image before it can be displayed in SQL Server Management Studio (SSMS), which is a lot of work. We've written several stored procedures that let you easily and quickly turn your SELECT queries' output into colorized line, column, bar, area, and pie charts and even computer-generated art. Before we show you how to use them, though, we'll discuss the geometry data type basics.
Understanding the Geometry Data Type
The geometry data type and the methods that support it let you draw simple shapes (e.g., lines, polygons) using planar coordinates (X,Y). Geometric shapes are described using a subset of the Well-Known Text (WKT) format. This text markup language is regulated by an Open Geospatial Consortium standard that's supported to varying degrees by all major database systems. For example, a line from point (0,0) to point (1,1) is specified as LINESTRING(0 0,1 1). You can visualize this simple shape in SSMS by executing the following SELECT statement using the STGeomFromText method to convert the WKT string into a drawing:
SELECT geometry::STGeomFromText('LINESTRING(0 0,1 1)', 0 );
Before you execute this statement in an SSMS query window, make sure that your output mode is set to Results to Grid. After executing it, you'll see three tabs in the result set window: Results, Spatial results, and Messages. Go to the Spatial results tab to see the drawing.
A colored square with the side length of 1 and the left bottom corner at (0,0) can be specified as a polygon with five points, where the first and the last points are the same: POLYGON((0 0,0 1,1 1,1 0,0 0)). Two squares can be described as one geometry object: MULTIPOLYGON(((0 0,0 1,1 1,1 0,0 0)),((2 0,2 1,3 1,3 0,2 0))). To convert these WKT strings to drawings, you can execute the following commands from a query window:
SELECT geometry::STGeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',0 );SELECT geometry::STGeomFromText('MULTIPOLYGON(((0 0,0 1,1 1,1 0,0 0)),((2 0,2 1,3 1,3 0,2 0)))', 0 );
Building Charts from Primitive Shapes
After you know how to draw lines, polygons, and multipolygons, you can combine these primitive shapes into various charts. To begin, create and populate a test table using the CreateTestTable.sql file, which you can download by clicking the hotlink at the top of this page. The test table contains two columns: FY (which specifies the fiscal year) and Sales (which contains sales amounts). You can display data from this table graphically if you concatenate all values from the rows into a WKT string, then use the STGeomFromText method in a SELECT statement to convert the WKT string into a line chart. Listing 1 shows this code, and Figure 1 shows the spatial results from it.
DECLARE @WKT AS VARCHAR(8000);SET @WKT = STUFF( (SELECT ',' + CAST( FY AS CHAR(4) ) + ' ' + CAST( Sales AS VARCHAR(30) ) FROM #Sales ORDER BY FY FOR XML PATH('')), 1, 1, '');SELECT geometry::STGeomFromText( 'LINESTRING(' + @WKT + ')', 0 );
Note that values across the horizontal axis correspond to values in the FY column in the test table and values on the vertical axis correspond to values in the Sales column. The result is a simple line chart representing the data in the table.
To display the same data as a column chart, you have to create a WKT string for a multipolygon, where each data point is described as a rectangle with the height equal to the sales value. The code concatenating the test data and generating the chart is shown in Listing 2, and the resulting image is shown in Figure 2.
DECLARE @WKT AS VARCHAR(8000);SET @WKT = STUFF( (SELECT ',((' + CAST( FY - 0.3 AS VARCHAR(30) ) + ' 0,' + CAST( FY - 0.3 AS VARCHAR(30) ) + ' ' + CAST( Sales AS VARCHAR(30) ) + ',' + CAST( FY + 0.3 AS VARCHAR(30) ) + ' ' + CAST( Sales AS VARCHAR(30) ) + ',' + CAST( FY + 0.3 AS VARCHAR(30) ) + ' 0,' + CAST( FY - 0.3 AS VARCHAR(30) ) + ' 0))' FROM #Sales ORDER BY FY FOR XML PATH('')), 1, 1, '');SELECT geometry::STGeomFromText( 'MULTIPOLYGON(' + @WKT + ')', 0 );
Granted, these charts aren't as pretty as those that can be produced in Microsoft Excel, but you can generate them quickly in SSMS without having to copy data from the result set window into a spreadsheet and taking extra steps to produce a chart there.
We have created a stored procedure named Chart and two supporting functions to turn the results of a given SELECT statement into a WKT string and display it in SSMS. The code for the stored procedure and functions is in the Chart_20111224.sql script, which you'll find in the zip file located via the "Download the Code" link at the top of the page. You can execute the script in a database of your choice, then use the Chart stored procedure to generate various charts and images from your SELECT queries.
You can produce a line or column chart by feeding a simple SELECT command to the Chart stored procedure, without writing code to compose a WKT string from table data. For example, the following call generates the same line chart shown in Figure 1:
EXEC dbo.Chart 'SELECT 0, FY, Sales FROM #Sales', @Legend = 0, @Y_Grid = 0;
This call generates the same column chart shown in Figure 2:
EXEC dbo.Chart 'SELECT 0, FY, Sales FROM #Sales', 'COLUMN', @Legend = 0, @Y_Grid = 0;
Note that the Chart stored procedure supports SQL injection by definition because it executes the code given in the first parameter as a dynamic SQL batch. There's no security risk when the Chart stored procedure is executed from a query window in SSMS because the user executing it wouldn't receive any elevated privileges. Just don't implement applications that take parameters from a user and then execute the Chart stored procedure through a connection with elevated permissions that the end user isn't granted directly.
Besides line and column charts, the stored procedure supports area, bar, and pie charts. Each example that we have shown so far has depicted a single series of data. The Chart stored procedure can also handle multiple series, displaying them in different colors in the resulting graph.
Running Prebuilt Charts
To demonstrate the different chart types, we have written several stored procedures that create sample charts using data from system tables. You might find these charts useful in your job. You'll find the following stored procedures in the Chart_20111224.sql script:
Chart_DB_Size. Produces a column chart that compares SQL Server database sizes. Figure 3 shows a sample chart produced by this stored procedure.
Chart_Free_Disk_Space. Makes a pie chart of free space by disk drive. A sample chart is shown in Figure 4.
Chart_Job_Duration. Displays a line chart depicting the duration of a given scheduled job over time.
Chart_Job_Step_Duration. Is similar to the Chart_Job_Duration stored procedure, except it breaks down the overall job duration into steps and displays it as an area chart. Figure 5 shows a sample chart.
Chart_All_Jobs_History. Makes a floating bar chart that shows every scheduled job as a series of bars on a separate horizontal line. The horizontal axis represents time. Each bar illustrates the execution of one job, with the position of the bar on the time axis depicting its start time and end time. Thus, the width of the bar corresponds to the job's duration. This chart can help you analyze scheduled job conflicts when they overlap and the relative duration of each job over time. A sample chart is shown in Figure 6.