Set Key/Value Pairs in the Session Context in SQL Server (sp_set_session_context)

In SQL Server, you can use the sp_set_session_context stored procedure to set key/value pairs in the session context.

These key/value pairs then remain in your session context until your connection to SQL Server closes. You can use these values in stored procedures and other T-SQL code throughout the life of your session.

This method for maintaining session state was first introduced in SQL Server 2016. Prior to that release, you would need to use SET CONTEXT_INFO, which provides a similar, but much more limited way of storing session state.

Continue reading

How to Delete Files in SQL Server 2019

In SQL Server 2019, you can use the sys.xp_delete_files stored procedure to delete a file on the file system.

This stored procedure was introduced in SQL Server 2019, and it can be used in conjunction with sys.xp_copy_file and sys.xp_copy_files (both of which were also introduced in SQL Server 2019), which enable you to copy files.

Prior to SQL Server 2019, you would need to use xp_cmdshell, which spawns a Windows command shell and passes in a string for execution. The new stored procedures introduced in SQL Server 2019 allow you to copy and delete files without relying on xp_cmdshell.

Continue reading

New Way to Copy Files in SQL Server 2019

Two new stored procedures introduced in SQL Server 2019 are sys.xp_copy_file and sys.xp_copy_files, which enable you to copy files.

Prior to SQL Server 2019, you would need to use xp_cmdshell, which spawns a Windows command shell and passes in a string for execution. The new stored procedures introduced in SQL Server 2019 allow you to copy files without relying on xp_cmdshell.

Continue reading

Use DB_ID() to Return the ID of a Database in SQL Server

In SQL Server, you can use the DB_ID() function to return the ID of the current database, or another specified database.

The way it works is, you pass the name of the database as an argument, and then the function will return the ID of that database. If you don’t pass a name it will return the ID of the current database.

Continue reading