SQL Server's extended stored procedures extend the power of T-SQL by letting your T-SQL batches interact with the OS and other objects outside the SQL Server database. Last month, I looked at some undocumented extended stored procedures that you can use to work with the registry. Here are seven more extended stored procedures that can add power to your T-SQL code.
This extended stored procedure lets you test for the existence of an OS file. If the file exists, xp_fileexist returns a 1 in the File Exists column. For example, to check for the existence of a file named C:\autoexec.bat, you'd use the following extended procedure:
You can use xp_enumdsn to get a list of the configured Data Source Names (DSNs) that are available on the system:
At times, you might want to send batch error notifications or even result sets by email. If you've configured SQL Mail, you can do both. The following example shows how to use xp_sendmail to send an email message:
Xp_sprintf lets you build a string by substituting variable values for placeholders. This capability lets you build dynamic SQL statements and output messages. The following example shows how to use xp_sprintf to build a simple INSERT statement:
EXEC xp_sprintf @sql_string output,
'INSERT INTO %s VALUES (%s, %s)', 'mytable', '1', '2'
Writing to the event log is a great way to log the status of your T-SQL stored procedures. You can use xp_logevent to write a completion message to the event log:
logged this message' , informational
If you're using SQL Server 7.0, you can use SQL Server's undocumented xp_eventlog extended stored procedure to return a result set of entries for a specific event log. (Unfortunately, the xp_eventlog extended stored procedure doesn't work in SQL Server 2000.) The following example shows how you can retrieve the contents of the Application log:
The powerful and potentially dangerous xp_cmdshell extended stored procedure lets you execute almost any program from within a T-SQL batch or stored procedure. Because you can use xp_cmdshell to execute nearly any OS command, you should carefully restrict access to it. The following example shows how to use xp_cmdshell to copy the file C:\temp\myws.xls: