
Understanding Using Tokens
Security Note: |
|---|
|
Any Windows user with write permissions on the Windows Event Log can access job steps that are activated by SQL Server Agent alerts or WMI alerts. To avoid this security risk, SQL Server Agent tokens that can be used in jobs activated by alerts are disabled by default. These tokens are: A-DBN, A-SVR, A-ERR, A-SEV, A-MSG., and WMI(property).
If you need to use these tokens, first ensure that only members of trusted Windows security groups, such as the Administrators group, have write permissions on the Event Log of the computer where SQL Server resides. Then, right-click SQL Server Agent in Object Explorer, select Properties, and on the Alert System page, select Replace tokens for all job responses to alerts to enable these tokens.
|
SQL Server Agent token replacement is simple and efficient: SQL Server Agent replaces an exact literal string value for the token. All tokens are case-sensitive. Your job steps must take this into account and correctly quote the tokens you use or convert the replacement string to the correct data type.
For example, you might use the following statement to print the name of the database in a job step:
PRINT N'Current database name is $(ESCAPE_SQUOTE(A-DBN))' ;
In this example, the ESCAPE_SQUOTE macro is inserted with the A-DBN token. At run time, the A-DBN token will be replaced with the appropriate database name. The escape macro escapes any single quotation marks that may be inadvertently passed in the token replacement string. SQL Server Agent will replace one single quotation mark with two single quotation marks in the final string.
For example, if the string passed to replace the token is AdventureWorks'SELECT @@VERSION --, the command executed by the SQL Server Agent job step will be:
PRINT N'Current database name is AdventureWorks''SELECT @@VERSION --' ;
In this case, the inserted statement, SELECT @@VERSION, does not execute. Instead, the extra single quotation mark causes the server to parse the inserted statement as a string. If the token replacement string does not contain a single quotation mark, no characters are escaped and the job step containing the token executes as intended.
To debug token usage in your job steps, use print statements such as PRINT N'$(ESCAPE_SQUOTE(SQLDIR))' and save job step output to a file or table. Use the Advanced page of the Job Step Properties dialog box to specify a job step output file or table.