Click here to Skip to main content
15,867,330 members
Articles / Database Development / SQL Server
Tip/Trick

Best practice when getting the structure of the resulting query or table.

Rate me:
Please Sign up or sign in to vote.
4.71/5 (3 votes)
29 Jun 2011CPOL 16.2K   3   1
Use the SET FMTONLY ON and OFF option
There are several instances when we require the structure of the query or the table. One of the most common practices to achieve this is to use "WHERE 1=0" along with the select part of the statement. It's really not practical when the query has several parameters or when you want to use a stored procedure.
As a best practice, it is recommended to use SET FMTONLY ON and OFF.
One big advantage of using this option is SqlServer will not generate, compile a query plan, because the actual statement is not being executed.
When SQL Reporting Services and Visual Studio read stored procedures for the first time to retrieve column names, they use SET FMTONLY ON and OFF.
When this option is set, only the metadata is read.
Let's see this by example, in your Query Analyzer, make sure you switch on the "Include Actual Execution Plan" to see this in action and run the following queries:

USE Northwind

SET FMTONLY ON 
EXEC dbo.CustOrderHist 'ALFKI'
SET FMTONLY OFF 

SET FMTONLY ON 
SELECT * FROM dbo.Customers
SET FMTONLY OFF 

SELECT * FROM dbo.Customers where 1=0

Only the last statement has the execution plan included.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 I never knew about this (I'm guilty ... Pin
AspDotNetDev29-Jun-11 10:54
protectorAspDotNetDev29-Jun-11 10:54 
Reason for my vote of 5
I never knew about this (I'm guilty of the WHERE 1 = 0 technique).

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.