Search code examples
ssmspragma

Can I tell when a query is running in SSMS vs elsewhere?


Is there any kind of environment variable (or something) that will tell me if a script is running inside SSMS? For example at the top of my query in SSMS I have this:

declare @StartDate datetime, @EndDate datetime, @ThisYear datetime, @IncludeZeroBalance int;
set @StartDate = '20080101';
set @EndDate = '20170201';
set @ThisYear = year(GetDate());
set @IncludeZeroBalance = 0;

I'd like to be able to leave that in the query but "wrap" it with something so it's only seen/run when in SSMS. Some kind of pragma like #IF SSMS or similar.

I'm thinking there's not something like this (searching has proven fruitless) but am hoping someone knows a trick to do that kind of thing...


Solution

  • You can use the APP_NAME() function to get the name of the application that the calling application specified in its connectionstring. Example:

    declare @MyAppname nvarchar(50);
    select @MyAppname = app_name();
    if (@MyAppname = 'Microsoft SQL Server Management Studio - Query')
        begin
            print 'Do SSMS stuff here'
        end
        else
        begin
            print 'Do non-SSMS stuff here'
        end;