Sei sulla pagina 1di 1978

Table of Contents

Overview
Spatial Indexes
sp_help_spatial_geometry_index
sp_help_spatial_geometry_index_xml
sp_help_spatial_geography_index
sp_help_spatial_geography_index_xml
sp_help_spatial_geometry_histogram (Trasnact-SQL)
sp_help_spatial_geography_histogram
Temporal tables
Temporal Table - sys.sp_cleanup_temporal_history
Temporal Table - sp_xtp_flush_temporal_history
Snapshot Backup
Snapshot Backup - sp_delete_backup_file_snapshot
Snapshot Backup - sp_delete_backup
PolyBase
PolyBase stored procedures - sp_polybase_join_group
PolyBase stored procedures - sp_polybase_leave_group
Filestream and Filetable
Filestream and FileTable - sp_filestream_force_garbage_collection
Filestream and FileTable - sp_kill_filestream_non_transacted_handles
Active Geo-Replication
sp_wait_for_database_copy_sync
Catalog
sp_column_privileges
sp_columns
sp_databases
sp_fkeys
sp_pkeys
sp_server_info
sp_special_columns
sp_sproc_columns
sp_statistics
sp_stored_procedures
sp_table_privileges
sp_tables
Change Data Capture
sys.sp_cdc_add_job
sys.sp_cdc_change_job
sys.sp_cdc_cleanup_change_table
sys.sp_cdc_disable_db
sys.sp_cdc_disable_table
sys.sp_cdc_drop_job
sys.sp_cdc_enable_db
sys.sp_cdc_enable_table
sys.sp_cdc_generate_wrapper_function
sys.sp_cdc_get_captured_columns
sys.sp_cdc_get_ddl_history
sys.sp_cdc_help_change_data_capture
sys.sp_cdc_help_jobs
sys.sp_cdc_scan
sys.sp_cdc_start_job
sys.sp_cdc_stop_job
Cursor
sp_cursor_list
sp_cursor
sp_cursorclose
sp_cursorexecute
sp_cursorfetch
sp_cursoropen
sp_cursoroption
sp_cursorprepare
sp_cursorprepexec
sp_cursorunprepare
sp_describe_cursor
sp_describe_cursor_columns
sp_describe_cursor_tables
sp_execute
sp_prepare (Transact SQL)
sp_prepexec
sp_prepexecrpc
sp_unprepare
Data Collector
sp_syscollector_create_collection_item
sp_syscollector_create_collection_set
sp_syscollector_create_collector_type
sp_syscollector_delete_collection_item
sp_syscollector_delete_collection_set
sp_syscollector_delete_collector_type
sp_syscollector_delete_execution_log_tree
sp_syscollector_disable_collector
sp_syscollector_enable_collector
sp_syscollector_set_cache_directory
sp_syscollector_set_cache_window
sp_syscollector_set_warehouse_database_name
sp_syscollector_set_warehouse_instance_name
sp_syscollector_start_collection_set
sp_syscollector_stop_collection_set
sp_syscollector_run_collection_set
sp_syscollector_update_collection_item
sp_syscollector_update_collection_set
sp_syscollector_update_collector_type
sp_syscollector_upload_collection_set
Database Engine
sp_add_data_file_recover_suspect_db
sp_add_data_file_recover_suspect_db
sp_addextendedproc
sp_addextendedproperty
sp_add_log_file_recover_suspect_db
sp_addmessage
sp_addtype
sp_addumpdevice
sp_altermessage
sp_attach_db
sp_attach_single_file_db
sp_autostats
sp_batch_params
sp_bindefault
sp_bindrule
sp_bindsession
sp_certify_removable
sp_clean_db_free_space
sp_clean_db_file_free_space
sp_configure
sp_control_plan_guide
sp_create_plan_guide
sp_create_plan_guide_from_handle
sp_create_removable
sp_createstats
sp_datatype_info
sp_db_increased_partitions
sp_db_vardecimal_storage_format
sp_dbcmptlevel
sp_dbmmonitoraddmonitoring
sp_dbmmonitorchangealert
sp_dbmmonitorchangemonitoring
sp_dbmmonitordropalert
sp_dbmmonitordropmonitoring
sp_dbmmonitorhelpalert
sp_dbmmonitorhelpmonitoring
sp_dbmmonitorresults
sp_dbmmonitorupdate
sp_dbremove
sp_delete_backuphistory
sp_delete_database_backuphistory
sp_depends
sp_describe_first_result_set
sp_describe_undeclared_parameters
sp_detach_db
sp_dropdevice
sp_dropextendedproc
sp_dropextendedproperty
sp_dropmessage
sp_droptype
sp_estimate_data_compression_savings
sp_estimated_rowsize_reduction_for_vardecimal
sp_execute_remote (Azure SQL Database)
sp_executesql
sp_execute_external_script
sp_getbindtoken
sp_getapplock
sp_get_query_template
sp_help
sp_helpconstraint
sp_helpdb
sp_helpdevice
sp_helpextendedproc
sp_helpfile
sp_helpfilegroup
sp_helpindex
sp_helplanguage
sp_helpserver
sp_helpsort
sp_helpstats
sp_helptext
sp_helptrigger
sp_indexoption
sp_invalidate_textptr
sp_lock
sp_monitor
sp_procoption
sp_recompile
sp_refreshsqlmodule
sp_refreshview
sp_releaseapplock
sp_rename
sp_renamedb
sp_resetstatus
sp_rxpredict
sp_sequence_get_range
sp_server_diagnostics
sp_set_session_context
sp_setnetname
sp_settriggerorder
sp_spaceused
sp_tableoption
sp_unbindefault
sp_unbindrule
sp_updateextendedproperty
sp_updatestats
sp_validname
sp_who
sys.sp_flush_log
sys.sp_xtp_bind_db_resource_pool
sys.sp_xtp_checkpoint_force_garbage_collection
sys.sp_xtp_control_proc_exec_stats
sys.sp_xtp_control_query_exec_stats
sys.sp_xtp_merge_checkpoint_files
sys.sp_xtp_unbind_db_resource_pool
Database Mail
sp_send_dbmail
sysmail_add_account_sp
sysmail_add_principalprofile_sp
sysmail_add_profile_sp
sysmail_add_profileaccount_sp
sysmail_configure_sp
sysmail_delete_account_sp
sysmail_delete_log_sp
sysmail_delete_mailitems_sp
sysmail_delete_principalprofile_sp
sysmail_delete_profile_sp
sysmail_delete_profileaccount_sp
sysmail_help_account_sp
sysmail_help_configure_sp
sysmail_help_principalprofile_sp
sysmail_help_profile_sp
sysmail_help_profileaccount_sp
sysmail_help_queue_sp
sysmail_help_status_sp
sysmail_start_sp
sysmail_stop_sp
sysmail_update_account_sp
sysmail_update_principalprofile_sp
sysmail_update_profile_sp
sysmail_update_profileaccount_sp
Database Maintenance Plan
sp_add_maintenance_plan
sp_add_maintenance_plan_db
sp_add_maintenance_plan_job
sp_delete_maintenance_plan
sp_delete_maintenance_plan_db
sp_delete_maintenance_plan_job
sp_help_maintenance_plan
Distributed Queries
sp_addlinkedserver
sp_addlinkedsrvlogin
sp_catalogs
sp_column_privileges_ex
sp_columns_ex
sp_droplinkedsrvlogin
sp_foreignkeys
sp_indexes
sp_linkedservers
sp_primarykeys
sp_serveroption
sp_table_privileges_ex
sp_tables_ex
sp_testlinkedserver
Firewall Rules (Azure SQL Database)
sp_set_firewall_rule (Azure SQL Database)
sp_set_database_firewall_rule (Azure SQL Database)
sp_delete_firewall_rule (Azure SQL Database)
sp_delete_database_firewall_rule (Azure SQL Database)
Full-Text Search and Semantic Search
sp_fulltext_catalog
sp_fulltext_column
sp_fulltext_database
sp_fulltext_keymappings
sp_fulltext_load_thesaurus_file
sp_fulltext_pendingchanges
sp_fulltext_semantic_register_language_statistics_db
sp_fulltext_semantic_unregister_language_statistics_db
sp_fulltext_service
sp_fulltext_table
sp_help_fulltext_catalogs
sp_help_fulltext_catalog_components
sp_help_fulltext_catalogs_cursor
sp_help_fulltext_columns
sp_help_fulltext_columns_cursor
sp_help_fulltext_system_components
sp_help_fulltext_tables
sp_help_fulltext_tables_cursor
General Extended
xp_cmdshell
xp_enumgroups
xp_grantlogin
xp_logevent
xp_loginconfig
xp_logininfo
xp_msver
xp_revokelogin
xp_sprintf
xp_sqlmaint
xp_sscanf
Log Shipping
sp_add_log_shipping_primary_database
sp_add_log_shipping_primary_secondary
sp_add_log_shipping_secondary_database
sp_add_log_shipping_secondary_primary
sp_add_log_shipping_alert_job
sp_can_tlog_be_applied
sp_change_log_shipping_primary_database
sp_change_log_shipping_secondary_database
sp_change_log_shipping_secondary_primary
sp_cleanup_log_shipping_history
sp_delete_log_shipping_secondary_primary
sp_delete_log_shipping_secondary_database
sp_delete_log_shipping_primary_secondary
sp_delete_log_shipping_primary_database
sp_delete_log_shipping_alert_job
sp_help_log_shipping_alert_job
sp_help_log_shipping_monitor
sp_help_log_shipping_monitor_primary
sp_help_log_shipping_monitor_secondary
sp_help_log_shipping_primary_database
sp_help_log_shipping_primary_secondary
sp_help_log_shipping_secondary_database
sp_help_log_shipping_secondary_primary
sp_refresh_log_shipping_monitor
sp_upgrade_log_shipping
Managed Backup
managed_backup.sp_backup_config_basic
managed_backup.sp_backup_config_advanced
managed_backup.sp_backup_config_schedule
managed_backup.sp_ backup_master_switch
managed_backup.sp_set_parameter
managed_backup.sp_get_backup_diagnostics
managed_backup.sp_backup_on_demand
Management Data Warehouse
core.sp_create_snapshot
core.sp_update_data_source
core.sp_add_collector_type
core.sp_remove_collector_type
core.sp_purge_data
OLE Automation
Object Hierarchy Syntax
sp_OACreate
sp_OADestroy
sp_OAGetErrorInfo
sp_OAGetProperty
sp_OAMethod
sp_OASetProperty
sp_OAStop
Policy-Based Management
sp_syspolicy_add_policy_category
sp_syspolicy_add_policy_category_subscription
sp_syspolicy_configure
sp_syspolicy_delete_policy_category
sp_syspolicy_delete_policy_category_subscription
sp_syspolicy_delete_policy_execution_history
sp_syspolicy_purge_health_state
sp_syspolicy_purge_history
sp_syspolicy_rename_condition
sp_syspolicy_rename_policy
sp_syspolicy_rename_policy_category
sp_syspolicy_repair_policy_automation
sp_syspolicy_set_config_enabled
sp_syspolicy_set_config_history_retention
sp_syspolicy_set_log_on_success
sp_syspolicy_subscribe_to_policy_category
sp_syspolicy_unsubscribe_from_policy_category
sp_syspolicy_update_policy_category
sp_syspolicy_update_policy_category_subscription
Query Store
sp_query_store_flush_db
sp_query_store_force_plan
sp_query_store_remove_plan (Transct-SQL)
sp_query_store_remove_query
sp_query_store_reset_exec_stats
sp_query_store_unforce_plan
Security
sp_add_trusted_assembly
sp_addapprole
sp_addlogin
sp_addremotelogin
sp_addrole
sp_addrolemember
sp_addserver
sp_addsrvrolemember
sp_adduser
sp_approlepassword
sp_audit_write
sp_change_users_login
sp_changedbowner
sp_changeobjectowner
sp_control_dbmasterkey_password
sp_dbfixedrolepermission
sp_defaultdb
sp_defaultlanguage
sp_denylogin
sp_describe_parameter_encryption
sp_drop_trusted_assembly
sp_dropalias
sp_dropapprole
sp_droplogin
sp_dropremotelogin
sp_droprole
sp_droprolemember
sp_dropserver
sp_dropsrvrolemember
sp_dropuser
sp_grantdbaccess
sp_grantlogin
sp_helpdbfixedrole
sp_helplinkedsrvlogin
sp_helplogins
sp_helpntgroup
sp_helpremotelogin
sp_helprole
sp_helprolemember
sp_helprotect
sp_helpsrvrole
sp_helpsrvrolemember
sp_helpuser
sp_migrate_user_to_contained
sp_MShasdbaccess
sp_password
sp_refresh_parameter_encryption
sp_remoteoption
sp_revokelogin
sp_revokedbaccess
sp_setapprole
sp_srvrolepermission
sp_unsetapprole
sp_validatelogins
sp_xp_cmdshell_proxy_account
SQL Data Warehouse
sp_datatype_info_90
sp_pdw_add_network_credentials
sp_pdw_database_encryption
sp_pdw_database_encryption_regenerate_system_keys
sp_pdw_log_user_data_masking
sp_pdw_remove_network_credentials
sp_special_columns_100
SQL Server Agent
sp_add_alert
sp_add_category
sp_add_job
sp_add_jobschedule
sp_add_jobserver
sp_add_jobstep
sp_add_notification
sp_add_operator
sp_add_proxy
sp_add_schedule
sp_add_targetservergroup
sp_add_targetsvrgrp_member
sp_apply_job_to_targets
sp_attach_schedule
sp_cycle_agent_errorlog
sp_cycle_errorlog
sp_delete_alert
sp_delete_category
sp_delete_job
sp_delete_jobschedule
sp_delete_jobserver
sp_delete_jobstep
sp_delete_jobsteplog
sp_delete_notification
sp_delete_operator
sp_delete_proxy
sp_delete_schedule
sp_delete_targetserver
sp_delete_targetservergroup
sp_delete_targetsvrgrp_member
sp_detach_schedule
sp_enum_login_for_proxy
sp_enum_proxy_for_subsystem
sp_enum_sqlagent_subsystems
sp_grant_proxy_to_subsystem
sp_grant_login_to_proxy
sp_help_alert
sp_help_category
sp_help_downloadlist
sp_help_job
sp_help_jobactivity
sp_help_jobcount
sp_help_jobhistory
sp_help_jobs_in_schedule
sp_help_jobschedule
sp_help_jobserver
sp_help_jobstep
sp_help_jobsteplog
sp_help_notification
sp_help_operator
sp_help_proxy
sp_help_schedule
sp_help_targetserver
sp_help_targetservergroup
sp_manage_jobs_by_login
sp_msx_defect
sp_msx_enlist
sp_msx_get_account
sp_msx_set_account
sp_notify_operator
sp_post_msx_operation
sp_purge_jobhistory
sp_remove_job_from_targets
sp_resync_targetserver
sp_revoke_login_from_proxy
sp_revoke_proxy_from_subsystem
sp_start_job
sp_stop_job
sp_update_alert
sp_update_category
sp_update_job
sp_update_jobschedule
sp_update_jobstep
sp_update_notification
sp_update_operator
sp_update_proxy
sp_update_schedule
sp_update_targetservergroup
SQL Server Profiler
sp_trace_create
sp_trace_generateevent
sp_trace_setevent
sp_trace_setfilter
sp_trace_setstatus
Stretch Database Extended
sys.sp_rda_deauthorize_db
sys.sp_rda_get_rpo_duration
sys.sp_rda_reauthorize_db
sys.sp_rda_reconcile_batch
sys.sp_rda_reconcile_columns
sys.sp_rda_reconcile_indexes
sys.sp_rda_set_query_mode
sys.sp_rda_set_rpo_duration
sys.sp_rda_test_connection
XML
sp_xml_preparedocument
sp_xml_removedocument
sp_db_selective_xml_index
Replication
sp_add_agent_parameter
sp_add_agent_profile
sp_addarticle
sp_adddistpublisher
sp_adddistributiondb
sp_adddistributor
sp_adddynamicsnapshot_job
sp_addlogreader_agent
sp_addmergealternatepublisher
sp_addmergearticle
sp_addmergefilter
sp_addmergepartition
sp_addmergepublication
sp_addmergepullsubscription
sp_addmergepullsubscription_agent
sp_addmergepushsubscription_agent
sp_addmergesubscription
sp_addpublication
sp_addpublication_snapshot
sp_addpullsubscription
sp_addpullsubscription_agent
sp_addpushsubscription_agent
sp_addqreader_agent
sp_addqueued_artinfo
sp_addscriptexec
sp_addsubscriber
sp_addsubscriber_schedule
sp_addsubscription
sp_addsynctriggers
sp_addtabletocontents
sp_adjustpublisheridentityrange
sp_article_validation
sp_articlecolumn
sp_articlefilter
sp_articleview
sp_attachsubscription
sp_browsesnapshotfolder
sp_browsemergesnapshotfolder
sp_browsereplcmds
sp_change_agent_parameter
sp_change_agent_profile
sp_changearticle
sp_changearticlecolumndatatype
sp_changedistpublisher
sp_changedistributiondb
sp_changedistributor_password
sp_changedistributor_property
sp_changedynamicsnapshot_job
sp_changelogreader_agent
sp_changemergearticle
sp_changemergefilter
sp_changemergepublication
sp_changemergepullsubscription
sp_changemergesubscription
sp_changepublication
sp_changepublication_snapshot
sp_changeqreader_agent
sp_changereplicationserverpasswords
sp_changesubscriber
sp_changesubscriber_schedule
sp_changesubscriptiondtsinfo
sp_changesubscription
sp_changesubstatus
sp_change_subscription_properties
sp_check_dynamic_filters
sp_check_for_sync_trigger
sp_check_join_filter
sp_check_subset_filter
sp_configure_peerconflictdetection
sp_copymergesnapshot
sp_copysnapshot
sp_copysubscription
sp_deletemergeconflictrow
sp_deletepeerrequesthistory
sp_deletetracertokenhistory
sp_drop_agent_parameter
sp_drop_agent_profile
sp_dropanonymousagent
sp_droparticle
sp_dropdistpublisher
sp_dropdistributiondb
sp_dropdistributor
sp_dropdynamicsnapshot_job
sp_dropmergealternatepublisher
sp_dropmergearticle
sp_dropmergefilter
sp_dropmergepartition
sp_dropmergepublication
sp_dropmergepullsubscription
sp_dropmergesubscription
sp_droppublication
sp_droppullsubscription
sp_dropsubscriber
sp_dropsubscription
sp_dsninfo
sp_enumcustomresolvers
sp_enumeratependingschemachanges
sp_enumdsn
sp_expired_subscription_cleanup
sp_generatefilters
sp_get_distributor
sp_get_redirected_publisher
sp_getagentparameterlist
sp_getdefaultdatatypemapping
sp_getmergedeletetype
sp_getqueuedrows
sp_getsubscriptiondtspackagename
sp_gettopologyinfo
sp_grant_publication_access
sp_help_agent_default
sp_help_agent_parameter
sp_help_agent_profile
sp_help_peerconflictdetection
sp_help_publication_access
sp_helparticle
sp_helparticlecolumns
sp_helparticledts
sp_helpdatatypemap
sp_helpdistpublisher
sp_helpdistributiondb
sp_helpdistributor
sp_helpdistributor_properties
sp_helpdynamicsnapshot_job
sp_helplogreader_agent
sp_helpmergealternatepublisher
sp_helpmergearticle
sp_helpmergearticlecolumn
sp_helpmergearticleconflicts
sp_helpmergeconflictrows
sp_helpmergedeleteconflictrows
sp_helpmergefilter
sp_helpmergepartition
sp_helpmergepublication
sp_helpmergepullsubscription
sp_helpmergesubscription
sp_helppeerrequests
sp_helppeerresponses
sp_helppublication
sp_helppublication_snapshot
sp_helppullsubscription
sp_helpqreader_agent
sp_helpreplfailovermode
sp_helpreplicationdboption
sp_helpreplicationoption
sp_helpsubscriberinfo
sp_helpsubscription
sp_helpsubscription_properties
sp_helpsubscriptionerrors
sp_helptracertokens
sp_helptracertokenhistory
sp_helpxactsetjob
sp_ivindexhasnullcols
sp_link_publication
sp_lookupcustomresolver
sp_markpendingschemachange
sp_marksubscriptionvalidation
sp_mergearticlecolumn
sp_mergecleanupmetadata
sp_mergedummyupdate
sp_mergemetadataretentioncleanup
sp_mergesubscription_cleanup
sp_MSchange_distribution_agent_properties
sp_MSchange_merge_agent_properties
sp_MSchange_logreader_agent_properties
sp_MSchange_snapshot_agent_properties
sp_posttracertoken
sp_publication_validation
sp_publisherproperty
sp_redirect_publisher
sp_refreshsubscriptions
sp_register_custom_scripting
sp_registercustomresolver
sp_reinitmergepullsubscription
sp_reinitmergesubscription
sp_reinitpullsubscription
sp_reinitsubscription
sp_removedbreplication
sp_removedistpublisherdbreplication
sp_repladdcolumn
sp_replcmds
sp_replcounters
sp_repldone
sp_repldropcolumn
sp_replflush
sp_replication_agent_checkup
sp_replicationdboption
sp_replmonitorchangepublicationthreshold
sp_replmonitorhelpmergesession
sp_replmonitorhelpmergesessiondetail
sp_replmonitorhelppublication
sp_replmonitorhelppublicationthresholds
sp_replmonitorhelppublisher
sp_replmonitorhelpsubscription
sp_replmonitorsubscriptionpendingcmds
sp_replqueuemonitor
sp_replrestart
sp_replsetoriginator
sp_replshowcmds
sp_repltrans
sp_requestpeerresponse
sp_requestpeertopologyinfo
sp_resetsnapshotdeliveryprogress
sp_restoredbreplication
sp_restoremergeidentityrange
sp_resyncmergesubscription
sp_revoke_publication_access
sp_schemafilter
sp_script_synctran_commands
sp_scriptdynamicupdproc
sp_scriptpublicationcustomprocs
sp_scriptsubconflicttable
sp_setdefaultdatatypemapping
sp_setreplfailovermode
sp_setsubscriptionxactseqno
sp_showpendingchanges
sp_showrowreplicainfo
sp_startpublication_snapshot
sp_subscription_cleanup
sp_table_validation
sp_unregister_custom_scripting
sp_unregistercustomresolver
sp_update_agent_profile
sp_validate_redirected_publisher
sp_validate_replica_hosts_as_publishers
sp_validatemergepublication
sp_validatemergesubscription
sp_vupgrade_mergeobjects
sp_vupgrade_replication
System Stored Procedures
(Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016)


Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
In SQL Server 2017, many administrative and informational
activities can be performed by using system stored procedures.
The system stored procedures are grouped into the categories
shown in the following table.

In This Section
CATEGORY DESCRIPTION

Active Geo-Replication Stored Used to manage to manage


Procedures Active Geo-Replication
configurations in Azure SQL
Database

Catalog Stored Procedures Used to implement ODBC data


dictionary functions and isolate
ODBC applications from changes
to underlying system tables.

Change Data Capture Stored Used to enable, disable, or report


Procedures on change data capture objects.

Cursor Stored Procedures Used to implements cursor


variable functionality.

Data Collector Stored Procedures Used to work with the data


collector and the following
components: collection sets,
collection items, and collection
types.

Database Engine Stored Used for general maintenance of


Procedures the SQL Server Database Engine.

Database Mail Stored Procedures Used to perform e-mail


(Transact-SQL) operations from within an
instance of SQL Server.

Database Maintenance Plan Used to set up core maintenance


Stored Procedures tasks that are required to
manage database performance.

Distributed Queries Stored Used to implement and manage


Procedures distributed queries.
CATEGORY DESCRIPTION

Filestream and FileTable Stored Used to configure and manage


Procedures (Transact-SQL) the FILESTREAM and FileTable
features.

Firewall Rules Stored Procedures Used to configure the Azure SQL


(Azure SQL Database) Database firewall.

Full-Text Search Stored Used to implement and query


Procedures full-text indexes.

General Extended Stored Used to provide an interface


Procedures from an instance of SQL Server
to external programs for various
maintenance activities.

Log Shipping Stored Procedures Used to configure, modify, and


monitor log shipping
configurations.

Management Data Warehouse Used to configure the


Stored Procedures (Transact- management data warehouse.
SQL)

OLE Automation Stored Used to enable standard


Procedures Automation objects for use
within a standard Transact-SQL
batch.

Policy-Based Management Used for Policy-Based


Stored Procedures Management.

PolyBase stored procedures Add or remove a computer from


a PolyBase scale-out group.

Query Store Stored Procedures Used to tune performance.


(Transact-SQL)

Replication Stored Procedures Used to manage replication.

Security Stored Procedures Used to manage security.

Snapshot Backup Stored Used to delete the


Procedures FILE_SNAPSHOT backup along
with all of its snapshots or to
delete an individual backup file
snapshot.

Spatial Index Stored Procedures Used to analyze and improve the


indexing performance of spatial
indexes.

SQL Server Agent Stored Used by SQL Server Profiler to


Procedures monitor performance and
activity.
CATEGORY DESCRIPTION

SQL Server Profiler Stored Used by SQL Server Agent to


Procedures manage scheduled and event-
driven activities.

Stretch Database Stored Used to manage stretch


Procedures databases.

Temporal Tables Stored Use for temporal tables


Procedures

XML Stored Procedures Used for XML text management.

NOTE
Unless specifically documented otherwise, all system stored
procedures return a value of 0 to indicate success. To indicate
failure, a nonzero value is returned.

API System Stored Procedures


Users that run SQL Server Profiler against ADO, OLE DB, and
ODBC applications may notice these applications using system
stored procedures that are not covered in the Transact-SQL
Reference. These stored procedures are used by the Microsoft
SQL Server Native Client OLE DB Provider and the SQL Server
Native Client ODBC driver to implement the functionality of a
database API. These stored procedures are just the mechanism
the provider or driver uses to communicate user requests to an
instance of SQL Server. They are intended only for the internal
use of the provider or the driver. Calling them explicitly from a
SQL Server-based application is not supported.
The sp_createorphan and sp_droporphans stored procedures
are used for ODBC ntext, text, and image processing.
The sp_reset_connection stored procedure is used by SQL
Server to support remote stored procedure calls in a
transaction. This stored procedure also causes Audit Login and
Audit Logout events to fire when a connection is reused from a
connection pool.
The system stored procedures in the following tables are used
only within an instance of SQL Server or through client APIs
and are not intended for general customer use. They are
subject to change and compatibility is not guaranteed.
The following stored procedures are documented in SQL
Server Books Online:

sp_catalogs sp_column_privileges
sp_column_privileges_ex sp_columns

sp_columns_ex sp_databases

sp_cursor sp_cursorclose

sp_cursorexecute sp_cursorfetch

sp_cursoroption sp_cursoropen

sp_cursorprepare sp_cursorprepexec

sp_cursorunprepare sp_execute

sp_datatype_info sp_fkeys

sp_foreignkeys sp_indexes

sp_pkeys sp_primarykeys

sp_prepare sp_prepexec

sp_prepexecrpc sp_unprepare

sp_server_info sp_special_columns

sp_sproc_columns sp_statistics

sp_table_privileges sp_table_privileges_ex

sp_tables sp_tables_ex

The following stored procedures are not documented:

sp_assemblies_rowset sp_assemblies_rowset_rmt

sp_assemblies_rowset2 sp_assembly_dependencies_rows
et

sp_assembly_dependencies_rows sp_assembly_dependencies_rows
et_rmt et2

sp_bcp_dbcmptlevel sp_catalogs_rowset

sp_catalogs_rowset;2 sp_catalogs_rowset;5

sp_catalogs_rowset_rmt sp_catalogs_rowset2

sp_check_constbytable_rowset sp_check_constbytable_rowset;2
sp_check_constbytable_rowset2 sp_check_constraints_rowset

sp_check_constraints_rowset;2 sp_check_constraints_rowset2

sp_column_privileges_rowset sp_column_privileges_rowset;2

sp_column_privileges_rowset;5 sp_column_privileges_rowset_rmt

sp_column_privileges_rowset2 sp_columns_90

sp_columns_90_rowset sp_columns_90_rowset_rmt

sp_columns_90_rowset2 sp_columns_ex_90

sp_columns_rowset sp_columns_rowset;2

sp_columns_rowset;5 sp_columns_rowset_rmt

sp_columns_rowset2 sp_constr_col_usage_rowset

sp_datatype_info_90 sp_ddopen;1

sp_ddopen;10 sp_ddopen;11

sp_ddopen;12 sp_ddopen;13

sp_ddopen;2 sp_ddopen;3

sp_ddopen;4 sp_ddopen;5

sp_ddopen;6 sp_ddopen;7

sp_ddopen;8 sp_ddopen;9

sp_foreign_keys_rowset sp_foreign_keys_rowset;2

sp_foreign_keys_rowset;3 sp_foreign_keys_rowset;5

sp_foreign_keys_rowset_rmt sp_foreign_keys_rowset2

sp_foreign_keys_rowset3 sp_indexes_90_rowset

sp_indexes_90_rowset_rmt sp_indexes_90_rowset2

sp_indexes_rowset sp_indexes_rowset;2

sp_indexes_rowset;5 sp_indexes_rowset_rmt

sp_indexes_rowset2 sp_linkedservers_rowset

sp_linkedservers_rowset;2 sp_linkedservers_rowset2
sp_oledb_database sp_oledb_defdb

sp_oledb_deflang sp_oledb_language

sp_oledb_ro_usrname sp_primary_keys_rowset

sp_primary_keys_rowset;2 sp_primary_keys_rowset;3

sp_primary_keys_rowset;5 sp_primary_keys_rowset_rmt

sp_primary_keys_rowset2 sp_procedure_params_90_rowset

sp_procedure_params_90_rowset sp_procedure_params_rowset
2

sp_procedure_params_rowset;2 sp_procedure_params_rowset2

sp_procedures_rowset sp_procedures_rowset;2

sp_procedures_rowset2 sp_provider_types_90_rowset

sp_provider_types_rowset sp_schemata_rowset

sp_schemata_rowset;3 sp_special_columns_90

sp_sproc_columns_90 sp_statistics_rowset

sp_statistics_rowset;2 sp_statistics_rowset2

sp_stored_procedures sp_table_constraints_rowset

sp_table_constraints_rowset;2 sp_table_constraints_rowset2

sp_table_privileges_rowset sp_table_privileges_rowset;2

sp_table_privileges_rowset;5 sp_table_privileges_rowset_rmt

sp_table_privileges_rowset2 sp_table_statistics_rowset

sp_table_statistics_rowset;2 sp_table_statistics2_rowset

sp_tablecollations sp_tablecollations_90

sp_tables_info_90_rowset sp_tables_info_90_rowset_64

sp_tables_info_90_rowset2 sp_tables_info_90_rowset2_64

sp_tables_info_rowset sp_tables_info_rowset;2

sp_tables_info_rowset_64 sp_tables_info_rowset_64;2
sp_tables_info_rowset2 sp_tables_info_rowset2_64

sp_tables_rowset;2 sp_tables_rowset;5

sp_tables_rowset_rmt sp_tables_rowset2

sp_usertypes_rowset sp_usertypes_rowset_rmt

sp_usertypes_rowset2 sp_views_rowset

sp_views_rowset2 sp_xml_schema_rowset

sp_xml_schema_rowset2

See Also
CREATE PROCEDURE (Transact-SQL)
Stored Procedures (Database Engine)
Running Stored Procedures (OLE DB)
Running Stored Procedures
Database Engine Stored Procedures (Transact-SQL)
Running Stored Procedures
Spatial Index Stored Procedures - Arguments and
Properties
11/21/2017 • 10 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
This topic documents the arguments and properties for spatial index stored procedures.
Transact-SQL Syntax Conventions

Syntax
For the syntax of specific spatial index stored procedures, see the following topics:
sp_help_spatial_geometry_index (Transact-SQL)
sp_help_spatial_geometry_index_xml (Transact-SQL)
sp_help_spatial_geography_index (Transact-SQL)
sp_help_spatial_geography_index_xml (Transact-SQL)

Arguments
[ @tabname =] 'tabname'
Is the qualified or nonqualified name of the table for which the spatial index has been specified.
Quotation marks are required only if a qualified table is specified. If a fully qualified name, including a database
name, is provided, the database name must be the name of the current database. tabname is nvarchar(776), with
no default.
[ @indexname = ] 'indexname'
Is the name of the spatial index specified. indexname is sysname with no default.
[ @verboseoutput = ] 'verboseoutput'
Is the range of property names and values to be returned.
0 = core properties
>0 = all properties
verboseoutput is tinyint with no default.
[ @query_sample = ] 'query_sample'
Is a representative query sample that can be used to test the usefulness of the index. It may be a representative
object or a query window. query_sample is geometry with no default.
[ @xml_output = ] 'xml_output'
Is an output parameter that returns the result set in an XML fragment. xml_output is xml with no default.

Properties
Set @verboseoutput =0 to return core properties as shown in the table below; @verboseoutput > 0 to return
all properties of the spatial index.
Base_Table_Rows
Number of rows in the base table. Value is bigint.
Bounding_Box_xmin
X-minimum bounding box properties of the spatial index for geometry type. This property value is NULL for
geographytype. Value is float.
Bounding_Box_ymin
Y-minimum bounding box properties of the spatial index for geometry type. This property value is NULL for
geography type. Value is float.
Bounding_Box_xmax
X-maximum bounding box properties of the spatial index for geometry type. This property value is NULL for
geography type. Value is float.
Bounding_Box_ymax
Y-maximum bounding box properties of the spatial index for geometry type. This property value is NULL for
geography type. Value is float.
Grid_Size_Level_1
Level 1 grid density of the spatial index:
16 for LOW
64 for MEDIUM
256 for HIGH
Value is int.
Grid_Size_Level_2
Level 2 grid density of the spatial index:
16 for LOW
64 for MEDIUM
256 for HIGH
Value is int.
Grid_Size_Level_3
Level 3 grid density of the spatial index:
16 for LOW
64 for MEDIUM
256 for HIGH
Value is int.
Grid_Size_Level_4
Level 4 grid density of the spatial index:
16 for LOW
64 for MEDIUM
256 for HIGH
Value is int.
Cells_Per_Object
Number of cells per object (index property). Value is int.
Total_Primary_Index_Rows
Number of rows in the index. Value is bigint.
Total_Primary_Index_Pages
Number of pages in the index. Value is bigint.
Average_Number_Of_Index_Rows_Per_Base_Row
Number of index rows / number base table rows. Value is bigint.
Total_Number_Of_ObjectCells_In_Level0_For_QuerySample
Indicates whether the representative query sample falls outside of the bounding box of the geometry index and
into the root cell (level 0 cell). This is either 0 (not in level 0 cell) or 1. If it is in the level 0 cell, the investigated index
is not an appropriate index for the query sample. This is a core property. Value is bigint.
Total_Number_Of_ObjectCells_In_Level0_In_Index
Number of cell instances of indexed objects that are tessellated in level 0 (root cell, outside the bounding box for
geometry). This is a core property. Value is bigint.
For geometry indexes, this will occur if the bounding box of the index is smaller than the data domain. A high
number of objects in level 0 may require secondary filters if the query window falls partially outside the bounding
box and will decrease the index performance (for example,
Total_Number_Of_ObjectCells_In_Level0_For_QuerySample is 1). If the query window falls inside the
bounding box, a high number of objects in level 0 may actually improve the performance of the index.
NULL and empty instances are counted at level 0 but will not impact performance. Level 0 will have as many cells
as NULL and empty instances at the base table. For geography indexes, level 0 will have as many cells as NULL
and empty instances +1 cell, because the query sample is counted as 1.
Total_Number_Of_ObjectCells_In_Level1_In_Index
Number of cell instances of indexed objects that are tessellated with level 1 precision. This is a core property.
Value is bigint.
Total_Number_Of_ObjectCells_In_Level2_In_Index
Number of cell instances of indexed objects that are tessellated with level 2 precision. This is a core property.
Value is bigint.
Total_Number_Of_ObjectCells_In_Level3_In_Index
Number of cell instances of indexed objects that are tessellated with level 3 precision. This is a core property.
Value is bigint.
Total_Number_Of_ObjectCells_In_Level4_In_Index
Number of cell instances of indexed objects that are tessellated with level 4 precision. This is a core property.
Value is bigint.
Total_Number_Of_interior_ObjectCells_In_Level1_In_Index
Number of cells that are completely covered by an object at tessellation level 1 and thus are interior to the object.
(Cell_attributevalue is 2.) This is a core property. Value is bigint.
Total_Number_Of_interior_ObjectCells_In_Level2_In_Index
Number of cells that are completely covered by an object at tessellation level 2 and thus are interior to the object.
(Cell_attribute value is 2.) This is a core property. Value is bigint.
Total_Number_Of_interior_ObjectCells_In_Level3_In_Index
Number of cells that are completely covered by an object at tessellation level 3 and thus are interior to the object.
(Cell_attribute value is 2.) This is a core property. Value is bigint.
Total_Number_Of_interior_ObjectCells_In_Level4_In_Index
Number of cells that are completely covered by an object at tessellation level 4 and thus are interior to the object.
(Cell_attribute value is 2.) This is a core property. Value is bigint.
Total_Number_Of_intersecting_ObjectCells_In_Level1_In_Index
Number of cells that are intersected by an object at tessellation level 1. (Cell_attribute value is 1.) This is a core
property. Value is bigint.
Total_Number_Of_intersecting_ObjectCells_In_Level2_In_Index
Number of cells that are intersected by an object at tessellation level 2. (Cell_attribute value is 1.) This is a core
property. Value is bigint.
Total_Number_Of_intersecting_ObjectCells_In_Level3_In_Index
Number of cells that are intersected by an object at tessellation level 3. (Cell_attribute value is 1.) This is a core
property. Value is bigint.
Total_Number_Of_intersecting_ObjectCells_In_Level4_In_Index
Number of cells that are intersected by an object at tessellation level 4. (Cell_attribute value is 1.) This is a core
property. Value is bigint.
Total_Number_Of_Border_ObjectCells_In_Level0_For_QuerySample
Indicates whether the query sample is in the root cell 0 outside the bounding box, but touching it. This is a core
property. Value is bigint.

NOTE
This information is only useful in determining whether there are objects that the bounding box may have closely missed.

Total_Number_Of_Border_ObjectCells_In_Level0_In_Index
Number of objects in level 0 that touch the bounding box. (Cell_attribute value is 0.) Value is bigint.
Total_Number_Of_Border_ObjectCells_In_Level1_In_Index
Number of object cells that touch a grid cell boundary at the tessellation level 1. (Cell_attribute value is 0.) This is a
core property. Value is bigint.
Total_Number_Of_Border_ObjectCells_In_Level2_In_Index
Number of object cells that touch a grid cell boundary at the tessellation level 2. (Cell_attribute value is 0.) This is a
core property. Value is bigint.
Total_Number_Of_Border_ObjectCells_In_Level3_In_Index
Number of object cells that touch a grid cell boundary at the tessellation level 3. (Cell_attribute value is 0.) This is a
core property. Value is bigint.
Total_Number_Of_Border_ObjectCells_In_Level4_In_Index
Number of object cells that touch a grid cell boundary at the tessellation level 4. (Cell_attribute value is 0.) This is a
core property. Value is bigint.
Interior_To_Total_Cells_Normalized_To_Leaf_Grid_Percentage
Percentage of the total area (total leaf cells) of the grid that contain leaf cells covered by an object.
For example, an object is tessellated into 10 cells at the 4 different grid levels covering an area that is equivalent to
100 leaf cells in total. Suppose there are 3 interior cells that are completely covered by the object. The area
covered by the 3 interior cells is equivalent to 42 leaf cells. Thus, the percentage of covered area is 42 percent. This
is a good measure of how well the objects in the index are shredded.
Value is float.
Intersecting_To_Total_Cells_Normalized_To_Leaf_Grid_Percentage
Same as Interior_To_Total_Cells_Normalized_To_Leaf_Grid_Percentage, except that these are partially
covered cells. Value is float.
Border_To_Total_Cells_Normalized_To_Leaf_Grid_Percentage
Same as Interior_To_Total_Cells_Normalized_To_Leaf_Grid_Percentage except that these are border cells.
Value is float.
Average_Cells_Per_Object_Normalized_To_Leaf_Grid
Average cells per object normalized to the leaf grid. This gives us an indication of the spatial size of the object, or
how big the objects are. Value is float.
Average_Objects_PerLeaf_GridCell
Sparseness of the index. Average number of objects per leaf cell. Value is float.
Number_Of_SRIDs_Found
The number of unique SRIDs in the index and column. Value is int.
Because a column can contain more than one SRID and objects of different SRIDs never intersect, the number of
SRIDs indicates the selectivity of the index.
Width_Of_Cell_In_Level1
Width property of cell in the indexing grid. The unit of measurement is provided by the index and depends on the
SRID of the indexed data. Value is float.
Width_Of_Cell_In_Level2
Width property of cell in the indexing grid. The unit of measurement is provided by the index and depends on the
SRID of the indexed data. Value is float.
Width_Of_Cell_In_Level3
Width property of cell in the indexing grid. The unit of measurement is provided by the index and depends on the
SRID of the indexed data. Value is float.
Width_Of_Cell_In_Level4
Width property of cell in the indexing grid. The unit of measurement is provided by the index and is dependent on
the SRID of the indexed data. Value is float.
Height_Of_Cell_In_Level1
Height property of cell in the indexing grid. The unit of measurement is provided by the index and depends on the
SRID of the indexed data. Value is float.
Height_Of_Cell_In_Level2
Height property of cell in the indexing grid. The unit of measurement is provided by the index and depends on the
SRID of the indexed data. Value is float.
Height_Of_Cell_In_Level3
Height property of cell in the indexing grid. The unit of measurement is provided by the index and depends on the
SRID of the indexed data. Value is float.
Height_Of_Cell_In_Level4
Height property of cell in the indexing grid. The unit of measurement is provided by the index and depends on the
SRID of the indexed data. Value is float.
Area_Of_Cell_In_Level1
Area property of cell in the indexing grid. The unit of measurement is provided by the index and depends on the
SRID of the indexed data. Value is float.
Area_Of_Cell_In_Level2
Area property of cell in the indexing grid. The unit of measurement is provided by the index and depends on the
SRID of the indexed data. Value is float.
Area_Of_Cell_In_Level3
Area property of cell in the indexing grid. The unit of measurement is provided by the index and depends on the
SRID of the indexed data. Value is float.
Area_Of_Cell_In_Level4
Area property of cell in the indexing grid. The unit of measurement is provided by the index and depends on the
SRID of the indexed data. Value is float.
CellArea_To_BoundingBoxArea_Percentage_In_Level1
The percentage of coverage of the bounding box by a level 1 cell. Value is float.
CellArea_To_BoundingBoxArea_Percentage_In_Level2
The percentage of coverage of the bounding box by a level 2 cell. Value is float.
CellArea_To_BoundingBoxArea_Percentage_In_Level3
The percentage of coverage of the bounding box by a level 3 cell. Value is float.
CellArea_To_BoundingBoxArea_Percentage_In_Level4
The percentage of coverage of the bounding box by a level 4 cell. Value is float.
Number_Of_Rows_Selected_By_Primary_Filter
Number of rows selected by the primary filter. This is a core property. Value is bigint.
Number_Of_Rows_Selected_By_Internal_Filter
Number of rows selected by the internal filter. The secondary filter is not called for these rows. This is a core
property. Value is bigint.
The returned number is only applicable for STintersects.
Number_Of_Times_Secondary_Filter_Is_Called
Number of times the secondary filter is called. This is a core property. Value is bigint.
Percentage_Of_Rows_NotSelected_By_Primary_Filter
If there are N rows in the base table, and P are selected by the primary filter, this returns (N-P)/N as percentage.
This is a core property. Value is float.
Percentage_Of_Primary_Filter_Rows_Selected_By_internal_Filter
If P rows are selected by the primary filter and S rows are selected by the internal filter, this returns S/P as a
percentage. The higher the percentage, the better the index is in avoiding the more performance-expensive
secondary filter. This is a core property. Value is float.
Number_Of_Rows_Output
Number of rows output by the query. This is a core property. Value is bigint.
Internal_Filter_Efficiency
If O is the number of rows output, this returns S/O as a percentage. This is a core property. Value is float.
Primary_Filter_Efficiency
If P rows are selected by the primary filter and O is the number of rows output, this returnsO/P as a percentage.
The higher the efficiency of the primary filter, the fewer false positives that the secondary filter has to process. This
is a core property. Value is float.

Permissions
User must be a member of the public role. Requires READ ACCESS permission on the server and the object. This
applies to all spatial index stored procedures.
Remarks
Properties containing NULL values are not included in the return set.

Examples
For examples, see the following topics:
sp_help_spatial_geometry_index (Transact-SQL)
sp_help_spatial_geometry_index_xml (Transact-SQL)
sp_help_spatial_geography_index (Transact-SQL)
sp_help_spatial_geography_index_xml (Transact-SQL)

Requirements
See Also
Spatial Index Stored Procedures (Transact-SQL)
sp_help_spatial_geometry_index (Transact-SQL)
Spatial Indexes Overview
XQuery Basics
XQuery Language Reference (SQL Server)
sp_help_spatial_geometry_index (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the names and values for a specified set of properties about a geometry spatial index. The result is
returned in a table format. You can choose to return a core set of properties or all properties of the index.
Transact-SQL Syntax Conventions

Syntax
sp_help_spatial_geometry_index [ @tabname =] 'tabname'
[ , [ @indexname = ] 'indexname' ]
[ , [ @verboseoutput = ] 'verboseoutput'
[ , [ @query_sample = ] 'query_sample']

Arguments
See Arguments and Properties of Spatial Index Stored Procedures.

Property Value/Return Value


See Arguments and Properties of Spatial Index Stored Procedures.

Permissions
User must be assigned a PUBLIC role to access the procedure. Requires READ ACCESS permission on the server
and the object.

Remarks
Properties containing NULL values are not included in the return set.

Example
The following example uses sp_help_spatial_geometry_index to investigate the spatial index
SIndx_SpatialTable_geometry_col2 defined on table geometry_col for the given query sample in @qs. This
example returns only the core properties of the specified index.

declare @qs geometry


='POLYGON((-90.0 -180.0, -90.0 180.0, 90.0 180.0, 90.0 -180.0, -90.0 -180.0))';
exec sp_help_spatial_geometry_index 'geometry_col', 'SIndx_SpatialTable_geometry_col2', 0, @qs;

See Also
Spatial Index Stored Procedures
sp_help_spatial_geometry_index_xml
Spatial Indexes Overview
Spatial Data (SQL Server)
sp_help_spatial_geometry_index_xml (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the names and values for a specified set of properties about a geometry spatial index. You can choose to
return a core set of properties or all properties of the index.
Results are returned in an XML fragment that displays the name and value of the properties selected.
Transact-SQL Syntax Conventions

Syntax
sp_help_spatial_geometry_index [ @tabname =] 'tabname'
[ , [ @indexname = ] 'indexname' ]
[ , [ @verboseoutput = ]'{ 0 | 1 }]
[ , [ @query_sample = ] 'query_sample' ]
[ ,.[ @xml_output = ] 'xml_output' ]

Arguments
See Arguments and Properties of Spatial Index Stored Procedures.

Properties
See Arguments and Properties of Spatial Index Stored Procedures.

Permissions
User must be a member of the public role. Requires READ ACCESS permission on the server and the object.

Remarks
Properties containing NULL values are not included in the XML return set.

Example
The following example uses sp_help_spatial_geometry_index_xml to investigate the spatial index
SIndx_SpatialTable_geometry_col2 defined on table geometry_col for the given query sample in @qs. This
example returns the core properties of the specified index in an XML fragment that displays the name and value of
the properties selected.
An XQuery is then run on the result set, returning a specific property.
DECLARE @qs geometry
='POLYGON((-90.0 -180.0, -90.0 180.0, 90.0 180.0, 90.0 -180.0, -90.0 -180.0))';
DECLARE @x xml;
EXEC sp_help_spatial_geometry_index_xml 'geometry_col', 'SIndx_SpatialTable_geometry_col2', 0, @qs, @x output;
SELECT @x.value('(/Primary_Filter_Efficiency/text())[1]', 'float');

Similar to sp_help_spatial_geometry_index, this stored procedure provides simpler programmatic access to the
properties of a spatial index and reports the result set in XML.

Requirements
See Also
Arguments and Properties of Spatial Index Stored Procedures
Spatial Index Stored Procedures
sp_help_spatial_geometry_index
Spatial Indexes Overview
Spatial Data (SQL Server)
XQuery Basics
XQuery Language Reference
sp_help_spatial_geography_index (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the names and values for a specified set of properties about a geography spatial index. The result is
returned in a table format. You can choose to return a core set of properties or all properties of the index.
Transact-SQL Syntax Conventions

Syntax
sp_help_spatial_geography_index [ @tabname =] 'tabname'
[ , [ @indexname = ] 'indexname' ]
[ , [ @verboseoutput = ] 'verboseoutput' ]
[ , [ @query_sample = ] 'query_sample' ]

Arguments
See Arguments and Properties of Spatial Index Stored Procedures.

Properties
See Arguments and Properties of Spatial Index Stored Procedures.

Permissions
User must be assigned a PUBLIC role to access the procedure. Requires READ ACCESS permission on the server
and the object.

Remarks
Example
The following example uses sp_help_spatial_geography_index to investigate the geography spatial index
SIndx_SpatialTable_geography_col2 defined on table geography_col for the given query sample in @qs. This
example returns only the core properties of the specified index.

declare @qs geography


='POLYGON((-90.0 -180, -90 180.0, 90 180.0, 90 -180, -90 -180.0))';
exec sp_help_spatial_geography_index 'geography_col', 'SIndx_SpatialTable_geography_col2', 0, @qs;

The bounding box of a geography instance is the whole earth.

Requirements
See Also
Spatial Index Stored Procedures
sp_help_spatial_geography_index
Spatial Indexes Overview
Spatial Data (SQL Server)
sp_help_spatial_geography_index_xml (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the name and value for a specified set of properties about a geography spatial index. You can choose to
return a core set of properties or all properties of the index.
Results are returned in an XML fragment that displays the name and value of the properties selected.
Transact-SQL Syntax Conventions

Syntax
sp_help_spatial_geography_index_xml [ @tabname =] 'tabname'
[ , [ @indexname = ] 'indexname' ]
[ , [ @verboseoutput = ] 'verboseoutput' ]
[ , [ @query_sample = ] 'query_sample' ]
[ ,.[ @xml_output = ] 'xml_output' ]

Arguments
See Arguments and Properties of Spatial Index Stored Procedures.

Properties
See Arguments and Properties of Spatial Index Stored Procedures.

Permissions
User must be assigned a PUBLIC role to access the procedure. Requires READ ACCESS permission on the server
and the object.

Remarks
Properties containing NULL values are not included in the return set.

Example
The following example uses sp_help_spatial_geography_index_xml to investigate the spatial index
SIndx_SpatialTable_geography_col2 defined on table geography_col for the given query sample in @qs. This
example returns the core properties of the specified index in an XML fragment that displays the name and value of
the properties selected.
An XQuery is then run on the result set, returning a specific property.
declare @qs geography
='POLYGON((-90.0 -180, -90 180.0, 90 180.0, 90 -180, -90 -180.0))';
declare @x xml;
exec sp_help_spatial_geography_index_xml 'geography_col', 'SIndx_SpatialTable_geography_col2', 0, @qs, @x
output;
select @x.value('(/Primary_Filter_Efficiency/text())[1]', 'float');

Similar to sp_help_spatial_geography_index, this stored procedure provides simpler programmatic access to the
properties of a geography spatial index and reports the result set in XML.
The bounding box of a geography is the whole earth.

Requirements
See Also
Spatial Index Stored Procedures
sp_help_spatial_geography_index
Spatial Indexes Overview
Spatial Data (SQL Server)
XQuery Basics
XQuery Language Reference
sp_help_spatial_geometry_histogram (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Facilitates the keying of bounding box and grid parameters for a spatial index.

Syntax
sp_help_spatial_geometry_histogram [ @tabname =] 'tabname'
[ , [ @colname = ] 'columnname' ]
[ , [ @resolution = ] 'resolution' ]
[ , [ @xmin = ] 'minx' ]
[ , [ @ymin = ] 'miny' ]
[ ,.[ @xmax = ] 'maxx' ]
[ , [ @ymax = ] 'maxy' ]
[ , [ @sample = ] 'sample' ]

Arguments
[ @tabname =] 'tabname'
Is the qualified or nonqualified name of the table for which the spatial index has been specified.
Quotation marks are required only if a qualified table is specified. If a fully qualified name, including a database
name, is provided, the database name must be the name of the current database. tabname is sysname, with no
default.
[ @colname = ] 'colname'
Is the name of the spatial column specified. colname is a sysname, with no default.
[ @resolution = ] 'resolution'
Is the resolution of the bounding box. Valid values are from 10 to 5000. resolution is a tinyint, with no default.
[ @xmin = ] 'xmin'
Is the X-minimum bounding box property. xmin is a float, with no default.
[ @ymin = ] 'ymin'
Is the Y-minimum bounding box property. ymin is a float, with no default.
[ @xmax = ] 'xmax'
Is the X-maximum bounding box property. xmax is a float, with no default.
[ @ymax = ] 'ymax'
Is the Y-maximum bounding box property. ymax is a float, with no default.
[ @sample = ] 'sample'
Is the percentage of the table that is used. Valid values are from 0 to 100. sample is a float. Default value is 100.

Property Value/Return Value


A table value is returned. The following grid describes the column contents of the table.
COLUMN NAME DATA TYPE DESCRIPTION

cellid int Represents the unique ID of each cell,


counting starts from 1.

cell geometry Is a rectangular polygon that represents


each cell. Cell shape is identical to the
cell shape used for the spatial indexing.

row_count bigint Indicates the number of spatial objects


that are touching or containing the cell.

Permissions
User must be a member of the public role. Requires READ ACCESS permission on the server and the object.

Remarks
SSMS spatial tab shows a graphical representation of the results. You can query the results against the spatial
window to get an approximate number of result items. Objects in the table may cover more than one cell, so the
sum of cells may be larger than the number of actual objects.
An additional row may be added to the result set that holds the number of objects that are outside of the bounding
box or touching the border of the bounding box. The cellid of this row is 0 and the cell of this row contains a
LineString that represents the bounding box. This row represents the entire space outside the bounding box.

Examples
The following example creates a sample table and then calls sp_help_spatial_geometry_histogram on the table.
USE AdventureWorksDW2012

GO

-- Set database compatibility for circular arc segments

ALTER DATABASE AdventureWorksDW2012

SET COMPATIBILITY_LEVEL = 110;

GO

-- Create table to execute sp_help_spatial_geometry_histogram on

CREATE TABLE TownSites

Location geometry NULL,

SiteName nvarchar(50) NULL

GO

-- Insert site data into table

DECLARE @g geometry;
SET @g = geometry::Parse('POINT(0 0)');

INSERT INTO TownSites(Location, SiteName)

SELECT @g, N'Booth Map';

SET @g = geometry::Parse('POLYGON((1 1, 1 2, 2 2, 2 1, 1 1))');

INSERT INTO TownSites(Location, SiteName)

SELECT @g, N'Town Hall';

SET @g = geometry::Parse('CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING(-1 0, 0 -1, 1 0),(1 0, 1 2, -1 0)))');

INSERT INTO TownSites(Location, SiteName)

SELECT @g, N'Main Park';

SET @g = geometry::Parse('CIRCULARSTRING(1 5, 2 2, 5 1)');

INSERT INTO TownSites(Location, SiteName)

SELECT @g, N'Main Road';

-- Call proc to see data within bounding box

EXEC sp_help_spatial_geometry_histogram @tabname = TownSites, @colname = Location, @resolution = 64, @xmin = -2,
@ymin = -2, @xmax = 3, @ymax = 3, @sample = 100;

GO

DROP TABLE TownSites;

GO

See Also
Spatial Index Stored Procedures (Transact-SQL)
sp_help_spatial_geography_histogram (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Facilitates the keying of grid parameters for a spatial index.

Syntax
sp_help_spatial_geography_histogram [ @tabname =] 'tabname'
[ , [ @colname = ] 'columnname' ]
[ , [ @resolution = ] 'resolution' ]
[ , [ @sample = ] 'tablesample' ]

Arguments
[ @tabname =] 'tabname'
Is the qualified or nonqualified name of the table for which the spatial index has been specified.
Quotation marks are required only if a qualified table is specified. If a fully qualified name, including a database
name, is provided, the database name must be the name of the current database. tabname is sysname, with no
default.
[ @colname = ] 'columnname'
Is the name of the spatial column specified. columnname is a sysname, with no default.
[ @resolution = ] 'resolution'
Is the resolution of the bounding box. Valid values are from 10 to 5000. resolution is a tinyint, with no default.
[ @sample = ] 'sample'
Is the percentage of the table that is used. Valid values are from 0 to 100. tablesample is a float. Default value is
100.

Property Value/Return Value


A table value is returned. The following grid describes the column contents of the table.

COLUMN NAME DATA TYPE DESCRIPTION

cellid int Represents the Unique ID of each cell,


with a starting count of 1.

cell geography Is a rectangular polygon that represents


each cell. Cell shape is identical to the
cell shape used for the spatial indexing.

row_count bigint Indicates the number of spatial objects


that are touching or containing the cell.
Permissions
User must be a member of the public role. Requires READ ACCESS permission on the server and the object.

Remarks
SSMS spatial tab shows a graphical representation of the results. You can query the results against the spatial
window to get an approximate number of result items.

NOTE
Objects in the table may cover more than one cell, so the sum of the cells in the table may be larger than the number of
actual objects.

The bounding box for the geography type is the entire globe.

Examples
The following example calls sp_help_spatial_geography_histogram on the Person.Address table in the
AdventureWorks2012 database.

EXEC sp_help_spatial_geography_histogram @tabname = Person.Address, @colname = SpatialLocation, @resolution =


64, @sample = 30;

See Also
Spatial Index Stored Procedures (Transact-SQL)
Temporal Table - sys.sp_cleanup_temporal_history
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
Transact-SQL Syntax Conventions
Removes all rows from temporal history table that match configured HISTORY_RETENTION PERIOD within a single
transaction.

Syntax
sp_cleanup_temporal_history [@schema_name = ] schema_name, [@table_name = ] table_name [, [@row_count=]
@row_count_var [OUTPUT]]

Arguments
@table_name
The name of the temporal table for which retention cleanup is invoked.
schema_name
The name of the schema which current temporal table belongs to
row_count_var [OUTPUT]
The output parameter that returns number of deleted rows. If the history table has clustered columnstore index, this
parameter will return always 0.

Remarks
This stored procedure can be used only with temporal tables that have finite retention period specified. Use this
stored procedure only if you need to immediately clean all aged rows from the history table. You should know that
it can have significant impact on the database log and I/O subsystem as it deletes all eligible rows within the same
transaction.
It is always recommended to rely on an internal background task for cleanup that removes aged rows with the
minimal impact on the regular workloads and database in general.

Permissions
Requires db_owner permissions.

Example
declare @rowcnt int
EXEC sys.sp_cleanup_temporal_history 'dbo', 'Department', @rowcnt output
select @rowcnt
See also
Temporal tables retention policy
Temporal Table - sp_xtp_flush_temporal_history
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Invokes the data flush task to move all committed rows from in-memory staging table to the disk-based history
table.
Transact-SQL Syntax Conventions

Syntax
sys.sp_xtp_flush_temporal_history @schema_name, @object_name

Arguments
@schema_name
The schema name for the current or temporal table
@object_name
The name of the current or temporal table

Return Code Values


0 (success) or >0 (failure)

Permissions
Requires db_owner permissions.

See Also
Performance Considerations with Memory-Optimized System-Versioned Temporal Tables
Snapshot Backup - sp_delete_backup_file_snapshot
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes a specified backup snapshot from the specified database. Use this system stored procedure in conjunction
with the sys.fn_db_backup_file_snapshots system function to identify and delete orphaned backup snapshots.
For more information, see File-Snapshot Backups for Database Files in Azure.
Transact-SQL Syntax Conventions

Syntax
sys.sp_delete_backup_file_snapshot
[ @db_name = ] N’<database_name>
, [ @snapshot_url = ] N’<snapshot_url>

Arguments
[ @db_name = ] database_name
The name of the database containing the snapshot to be deleted, provided as a Unicode string.
[ @snapshot_url = ] snapshot_url
The URL of the snapshot to be deleted, provided as a Unicode string.

Permissions
Requires ALTER ANY DATABASE permission.

See Also
sys.fn_db_backup_file_snapshots (Transact-SQL)
sp_delete_backup (Transact-SQL)
Snapshot Backup - sp_delete_backup
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes all snapshots and the backup file that comprise a snapshot backup set from the specified database. This
system stored procedure is the only recommended method for managing snapshot backup sets. For more
information, see File-Snapshot Backups for Database Files in Azure.
Transact-SQL Syntax Conventions

Syntax
sys.sp_delete_backup
[ @backup_url = ] backup_metadata_file_url
,[ [ @db_name = ] database_name | NULL ]

Arguments
[ @backup_url = ] backup_meta_file_url
The URL of the backup to be deleted, which deletes all snapshots comprising the specified backup set including the
backup file itself.
[ @db_name = ] database_name
The name of the database containing the snapshot to be deleted. When a database name is provided, the system
verifies that the backup URL provided is a backup URL for the specified database and uses
sp_delete_backup_file_snapshot (Transact-SQL) to delete each snapshot. If no database name is provided, this
database check is not performed.

Permissions
Requires ALTER ANY DATABASE permission or ALTER permission on the specified database.

See Also
sys.fn_db_backup_file_snapshots (Transact-SQL)
sp_delete_backup_file_snapshot (Transact-SQL)
PolyBase stored procedures - sp_polybase_join_group
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a SQL Server instance as a compute node to a PolyBase group for scale-out computation.
The SQL Server instance must have the PolyBase feature installed. PolyBase enables the integration of non-SQL
Server data sources, such as Hadoop and Azure blob storage. See also sp_polybase_leave_group (Transact-SQL).
Transact-SQL Syntax Conventions

Syntax
sp_polybase_join_group (@head_node_address = N'head_node_address',
@dms_control_channel_port = dms_control_channel_port,
@head_node_sql_server_instance_name = head_node_sql_server_instance_name)
[ ; ]

Arguments
@head_node_address = N'head_node_address'
The name of the machine that hosts the SQL Server head node of the PolyBase scale-out group.
@head_node_address is nvarchar(255).
@dms_control_channel_port = dms_control_channel_port
The port where the control channel for the head node PolyBase Data Movement Service is running.
@dms_control_channel_port is an unsigned __int16. The default is 16450.
@head_node_sql_server_instance_name = head_node_sql_server_instance_name
The name of the head node SQL Server instance in the PolyBase scale-out group.
@head_node_sql_server_instance_name is nvarchar(16).

Return Code Values


0 (success) or 1 (failure)

Permissions
Requires CONTROL SERVER permission.

Remarks
After running the stored procedure, shut down the PolyBase engine, and restart the PolyBase Data Movement
Service on the machine. To verify run the following DMV on the head node: sys.dm_exec_compute_nodes.

Example
The example joins the current machine as a compute node to a PolyBase group. The name of the head node is
HST01 and the name of the SQL Server instance on the head node is MSSQLSERVER.
EXEC sp_polybase_join_group N'HST01', 16450, N'MSSQLSERVER'

See Also
Get started with PolyBase
System Stored Procedures (Transact-SQL)
PolyBase stored procedures -
sp_polybase_leave_group
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a SQL Server instance from a PolyBase group for scale-out computation.
The SQL Server instance must have the PolyBase Guide feature installed. PolyBase enables the integration of non-
SQL Server data sources, such as Hadoop and Azure blob storage. See also sp_polybase_join_group.
Transact-SQL Syntax Conventions

Syntax
sp_polybase_leave_group;

Return Code Values


0 (success) or 1 (failure)

Permissions
Requires CONTROL SERVER permission.

Remarks
You can only remove a compute node from a group.
After running the stored procedure, restart the PolyBase engine and PolyBase Data Movement Service on the
machine. To verify run the following DMV on the head node: sys.dm_exec_compute_nodes.

Example
The example removes the current machine from a PolyBase group.

EXEC sp_polybase_leave_group ;

See Also
Get started with PolyBase
System Stored Procedures (Transact-SQL)
Filestream and FileTable -
sp_filestream_force_garbage_collection
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Forces the FILESTREAM garbage collector to run, deleting any unneeded FILESTREAM files.
A FILESTREAM container cannot be removed until all the deleted files within it have been cleaned up by the
garbage collector. The FILESTREAM garbage collector runs automatically. However, if you need to remove a
container before the garbage collector has run, you can use sp_filestream_force_garbage_collection to run the
garbage collector manually.

Syntax
sp_filestream_force_garbage_collection
[ @dbname = ] 'database_name',
[ @filename = ] 'logical_file_name' ]

Arguments
@dbname = database_name'
Signifies the name of the database to run the garbage collector on.

NOTE
dbname is sysname. If not specified, current database is assumed.

@filename = logical_file_name
Specifies the logical name of the FILESTREAM container to run the garbage collector on. @filename is optional. If
no logical filename is specified, the garbage collector cleans all FILESTREAM containers in the specified database.

Return Code Values

Value Description

0 Operation success

1 Operation failure

Result Sets
VALUE DESCRIPTION

file_name Indicates the FILESTREAM container name


VALUE DESCRIPTION

num_collected_items Indicates the number of FILESTREAM items (files/directories)


that have been garbage collected (deleted) in this container.

num_marked_for_collection_items Indicates the number of FILESTREAM items (files/directories)


that have been marked for garbage collection in this container.
These items have not been deleted yet, but may be eligible for
deletion following the garbage collection phase.

num_unprocessed_items Indicates the number of eligible FILESTREAM items (files or


directories) that were not processed for garbage collection in
this FILESTREAM container. Items may be unprocessed for
various reasons, including the following:

Files that need to be pinned down because Log backup or


CheckPoint has not been taken.

Files in the FULL or BULK_LOGGED recovery model.

There is a long-running active transaction.

The replication log reader job has not run. See the white paper
FILESTREAM Storage in SQL Server 2008 for more
information.

last_collected_xact_seqno Returns the last corresponding log sequence number (LSN) up


to which the files have been garbage collected for the specified
FILESTREAM container.

Remarks
Explicitly runs FILESTREAM Garbage Collector task to completion on the requested database (and FILESTREAM
container). Files that are no longer needed are removed by the garbage collection process. The time needed for this
operation to complete depends on the size of the FILESTREAM data in that database or container as well as the
amount of DML activity that has recently occurred on the FILESTREAM data. Though this operation can be run with
the database online, this may affect the performance of the database during its run due to various I/O activities
done by the garbage collection process.

NOTE
It is recommended that this operation be run only when necessary and outside usual operation hours.

Multiple invocations of this stored procedure can be run simultaneously only on separate containers or separate
databases.
Due to 2-phase operations, the stored procedure should be run twice to actually delete underlying Filestream files.
Garbage Collection (GC) relies on log truncation. Therefore, if files were deleted recently on a database using Full
Recovery model, they are GC-ed only after a log backup of those transaction log portions is taken and the log
portion is marked inactive. On a database using Simple recovery model, a log truncation occurs after a CHECKPOINT
has been issued against the database.

Permissions
Requires membership in the db_owner database role.
Examples
The following examples run the garbage collector for FILESTREAM containers in the FSDB database.
A. Specifying no container

USE FSDB;
GO
EXEC sp_filestream_force_garbage_collection @dbname = N'FSDB';

B. Specifying a container

USE FSDB;
GO
EXEC sp_filestream_force_garbage_collection @dbname = N'FSDB',
@filename = N'FSContainer';

See Also
FILESTREAM Storage in SQL Server 2008
Filestream and FileTable -
sp_kill_filestream_non_transacted_handles
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Closes non-transactional file handles to FileTable data.

Syntax
sp_kill_filestream_non_transacted_handles [[ @table_name = ] ‘table_name’, [[ @handle_id = ] @handle_id]]

Arguments
table_name
The name of the table in which to close non-transactional handles.
You can pass table_name without handle_id to close all open non-transactional handles for the FileTable.
You can pass NULL for the value of table_name to close all open non-transactional handles for all FileTables in the
current database. NULL is the default value.
handle_id
The optional ID of the individual handle to be closed. You can get the handle_id from the
sys.dm_filestream_non_transacted_handles (Transact-SQL) dynamic management view. Each ID is unique in a SQL
Server instance. If you specify handle_id, then you also have to provide a value for table_name.
You can pass NULL for the value of handle_id to close all open non-transactional handles for the FileTable specified
by table_name. NULL is the default value.

Return Code Value


0 (success) or 1 (failure)

Result Set
None.

General Remarks
The handle_id required by sp_kill_filestream_non_transacted_handles is not related to the session_id or unit of
work that is used in other kill commands.
For more information, see Manage FileTables.

Metadata

For information about open non-transactional file handles, query the dynamic management view
sys.dm_filestream_non_transacted_handles (Transact-SQL).

Security
Permissions
You must have VIEW DATABASE STATE permission to get file handles from the
sys.dm_FILESTREAM_non_transacted_handles dynamic management view and to run
sp_kill_filestream_non_transacted_handles.

Examples
The following examples show how to call sp_kill_filestream_non_transacted_handles to close non-transactional
file handles for FileTable data.

-- Close all open handles in the current database.


sp_kill_filestream_non_transacted_handles

-- Close all open handles in myFileTable.


sp_kill_filestream_non_transacted_handles @table_name = ’myFileTable’

-- Close a specific handle in myFileTable.


sp_kill_filestream_non_transacted_handles @table_name = ’myFileTable’, @handle_id = 0xFFFAAADD

The following example shows how to use a script to get a handle_id and close it.

DECLARE @handle_id varbinary(16);


DECLARE @table_name sysname;

SELECT TOP 1 @handle_id = handle_id, @table_name = Object_name(table_id)


FROM sys.dm_FILESTREAM_non_transacted_handles;

EXEC sp_kill_filestream_non_transacted_handles @dbname, @table_name, @handle_id;


GO

See Also
Manage FileTables
Active Geo-Replication -
sp_wait_for_database_copy_sync
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
This procedure is scoped to an Active Geo-Replication relationship between a primary and secondary. Calling the
sp_wait_for_database_copy_sync causes the application to wait until all committed transactions are replicated
and acknowledged by the active secondary database. Run sp_wait_for_database_copy_sync on only the primary
database.
||
|-|
|Applies to: Azure SQL Database.|

Syntax
sp_wait_for_database_copy_sync [ @target_server = ] 'server_name'
, [ @target_database = ] 'database_name'

Arguments
[ @target_server = ] 'server_name'
The name of the SQL Database server that hosts the active secondary database. server_name is sysname, with no
default.
[ @target_database = ] 'database_name'
The name of the active secondary database. database_name is sysname, with no default.

Return Code Values


Returns 0 for success or an error number for failure.
The most likely error conditions are as follows:
The server name or database name is missing.
The link cannot be found to the specified server name or database.
Interlink connectivity is lost. sp_wait_for_database_copy_sync will return after the connection timeout.

Permissions
Any user in the primary database can call this system stored procedure. The login must be a user in both the
primary and active secondary databases.

Remarks
All transactions committed before a sp_wait_for_database_copy_sync call are sent to the active secondary
database.
Examples
The following example invokes sp_wait_for_database_copy_sync to ensure that all transactions are committed to
the primary database, db0, get sent to its active secondary database on the target server ubfyu5ssyt.

USE db0;
GO
EXEC sys.sp_wait_for_database_copy_sync @target_server = N'ubfyu5ssyt1', @target_database = N'db0';
GO

See Also
sys.dm_continuous_copy_status (Azure SQL Database)
Geo-Replication Dynamic Management Views and Functions (Azure SQL Database)
Catalog Stored Procedures (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
SQL Server supports the following system stored procedures that implement ODBC data dictionary functions and
isolate ODBC applications from changes to underlying system tables.

sp_column_privileges sp_special_columns

sp_columns sp_sproc_columns

sp_databases sp_statistics

sp_fkeys sp_stored_procedures

sp_pkeys sp_table_privileges

sp_server_info sp_tables

See Also
System Stored Procedures (Transact-SQL)
sp_column_privileges (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns column privilege information for a single table in the current environment.
Transact-SQL Syntax Conventions

Syntax
sp_column_privileges [ @table_name = ] 'table_name'
[ , [ @table_owner = ] 'table_owner' ]
[ , [ @table_qualifier = ] 'table_qualifier' ]
[ , [ @column_name = ] 'column' ]

Arguments
[ @table_name= ] 'table_name'
Is the table used to return catalog information. table_name is sysname, with no default. Wildcard pattern
matching is not supported.
[ @table_owner= ] 'table_owner'
Is the owner of the table used to return catalog information. table_owner is sysname, with a default of NULL.
Wildcard pattern matching is not supported. If table_owner is not specified, the default table visibility rules of the
underlying database management system (DBMS) apply.
If the current user owns a table with the specified name, that table's columns are returned. If table_owner is not
specified and the current user does not own a table with the specified table_name, sp_column privileges looks for
a table with the specified table_name owned by the database owner. If one exists, that table's columns are
returned.
[ @table_qualifier= ] 'table_qualifier'
Is the name of the table qualifier. table_qualifier is sysname, with a default of NULL. Various DBMS products
support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database
name. In some products, it represents the server name of the table's database environment.
[ @column_name= ] 'column'
Is a single column used when only one column of catalog information is being obtained. column is
nvarchar(384), with a default of NULL. If column is not specified, all columns are returned. In SQL Server, column
represents the column name as listed in the sys.columns table. column can include wildcard characters using
wildcard matching patterns of the underlying DBMS. For maximum interoperability, the gateway client should
assume only ISO standard pattern matching (the % and _ wildcard characters).

Result Sets
sp_column_privileges is equivalent to SQLColumnPrivileges in ODBC. The results returned are ordered by
TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, COLUMN_NAME, and PRIVILEGE.
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_QUALIFIER sysname Table qualifier name. This field can be


NULL.

TABLE_OWNER sysname Table owner name. This field always


returns a value.

TABLE_NAME sysname Table name. This field always returns a


value.

COLUMN_NAME sysname Column name, for each column of the


TABLE_NAME returned. This field always
returns a value.

GRANTOR sysname Database user name that has granted


permissions on this COLUMN_NAME to
the listed GRANTEE. In SQL Server, this
column is always the same as the
TABLE_OWNER. This field always
returns a value.

The GRANTOR column can be either


the database owner (TABLE_OWNER) or
a user to whom the database owner
granted permissions by using the WITH
GRANT OPTION clause in the GRANT
statement.

GRANTEE sysname Database user name that has been


granted permissions on this
COLUMN_NAME by the listed
GRANTOR. In SQL Server, this column
always includes a database user from
the sysusers table. This field always
returns a value.

PRIVILEGE varchar(32) One of the available column


permissions. Column permissions can
be one of the following values (or other
values supported by the data source
when implementation is defined):

SELECT = GRANTEE can retrieve data


for the columns.

INSERT = GRANTEE can provide data


for this column when new rows are
inserted (by the GRANTEE) into the
table.

UPDATE = GRANTEE can modify


existing data in the column.

REFERENCES = GRANTEE can reference


a column in a foreign table in a primary
key/foreign key relationship. Primary
key/foreign key relationships are
defined by using table constraints.
COLUMN NAME DATA TYPE DESCRIPTION

IS_GRANTABLE varchar(3) Indicates whether the GRANTEE is


permitted to grant permissions to other
users (often referred to as "grant with
grant" permission). Can be YES, NO, or
NULL. An unknown, or NULL, value
refers to a data source for which "grant
with grant" is not applicable.

Remarks
With SQL Server, permissions are granted with the GRANT statement and taken away by the REVOKE statement.

Permissions
Requires SELECT permission on the schema.

Examples
The following example returns column privilege information for a specific column.

USE AdventureWorks2012;
GO
EXEC sp_column_privileges @table_name = 'Employee'
,@table_owner = 'HumanResources'
,@table_qualifier = 'AdventureWorks2012'
,@column_name = 'SalariedFlag';

See Also
GRANT (Transact-SQL)
REVOKE (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_columns (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns column information for the specified objects that can be queried in the current environment.
Transact-SQL Syntax Conventions

Syntax
-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse

sp_columns [ @table_name = ] object


[ , [ @table_owner = ] owner ]
[ , [ @table_qualifier = ] qualifier ]
[ , [ @column_name = ] column ]
[ , [ @ODBCVer = ] ODBCVer ]

Arguments
[ @table_name=] object
Is the name of the object that is used to return catalog information. object can be a table, view, or other object that
has columns such as table-valued functions. object is nvarchar(384), with no default. Wildcard pattern matching is
supported.
[ @table_owner=] owner
Is the object owner of the object that is used to return catalog information. owner is nvarchar(384), with a default
of NULL. Wildcard pattern matching is supported. If owner is not specified, the default object visibility rules of the
underlying DBMS apply.
If the current user owns an object with the specified name, the columns of that object are returned. If owner is not
specified and the current user does not own an object with the specified object, sp_columns looks for an object
with the specified object owned by the database owner. If one exists, that object's columns are returned.
[ @table_qualifier=] qualifier
Is the name of the object qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support
three-part naming for objects (qualifier.owner.name). In SQL Server, this column represents the database name. In
some products, it represents the server name of the object's database environment.
[ @column_name=] column
Is a single column and is used when only one column of catalog information is wanted. column is nvarchar(384),
with a default of NULL. If column is not specified, all columns are returned. In SQL Server, column represents the
column name as listed in the syscolumns table. Wildcard pattern matching is supported. For maximum
interoperability, the gateway client should assume only SQL-92 standard pattern matching (the % and _ wildcard
characters).
[ @ODBCVer=] ODBCVer
Is the version of ODBC that is being used. ODBCVer is int, with a default of 2. This indicates ODBC Version 2. Valid
values are 2 or 3. For the behavior differences between versions 2 and 3, see the ODBC SQLColumns specification.
Return Code Values
None

Result Sets
The sp_columns catalog stored procedure is equivalent to SQLColumns in ODBC. The results returned are
ordered by TABLE_QUALIFIER, TABLE_OWNER, and TABLE_NAME.

COLUMN NAME DATA TYPE DESCRIPTION

TABLE_QUALIFIER sysname Object qualifier name. This field can be


NULL.

TABLE_OWNER sysname Object owner name. This field always


returns a value.

TABLE_NAME sysname Object name. This field always returns a


value.

COLUMN_NAME sysname Column name, for each column of the


TABLE_NAME returned. This field
always returns a value.

DATA_TYPE smallint Integer code for ODBC data type. If this


is a data type that cannot be mapped
to an ODBC type, it is NULL. The native
data type name is returned in the
TYPE_NAME column.

TYPE_NAME sysname String representing a data type. The


underlying DBMS presents this data
type name.

PRECISION int Number of significant digits. The return


value for the PRECISION column is in
base 10.

LENGTH int Transfer size of the data.1

SCALE smallint Number of digits to the right of the


decimal point.

RADIX smallint Base for numeric data types.

NULLABLE smallint Specifies nullability.

1 = NULL is possible.

0 = NOT NULL.

REMARKS varchar(254) This field always returns NULL.

COLUMN_DEF nvarchar(4000) Default value of the column.


COLUMN NAME DATA TYPE DESCRIPTION

SQL_DATA_TYPE smallint Value of the SQL data type as it appears


in the TYPE field of the descriptor. This
column is the same as the DATA_TYPE
column, except for the datetime and
SQL-92 interval data types. This
column always returns a value.

SQL_DATETIME_SUB smallint Subtype code for datetime and SQL-92


interval data types. For other data
types, this column returns NULL.

CHAR_OCTET_LENGTH int Maximum length in bytes of a character


or integer data type column. For all
other data types, this column returns
NULL.

ORDINAL_POSITION int Ordinal position of the column in the


object. The first column in the object is
1. This column always returns a value.

IS_NULLABLE varchar(254) Nullability of the column in the object.


ISO rules are followed to determine
nullability. An ISO SQL-compliant DBMS
cannot return an empty string.

YES = Column can include NULLS.

NO = Column cannot include NULLS.

This column returns a zero-length string


if nullability is unknown.

The value returned for this column is


different from the value returned for the
NULLABLE column.

SS_DATA_TYPE tinyint SQL Server data type used by extended


stored procedures. For more
information, see Data Types (Transact-
SQL).

1 For more information, see the Microsoft ODBC documentation.

Permissions
Requires SELECT and VIEW DEFINITION permissions on the schema.

Remarks
sp_columns follows the requirements for delimited identifiers. For more information, see Database Identifiers.

Examples
The following example returns column information for a specified table.
USE AdventureWorks2012;
GO
EXEC sp_columns @table_name = N'Department',
@table_owner = N'HumanResources';

Examples: Azure SQL Data Warehouse and Parallel Data Warehouse


The following example returns column information for a specified table.

-- Uses AdventureWorks

EXEC sp_columns @table_name = N'DimEmployee',


@table_owner = N'dbo';

See Also
sp_tables (Transact-SQL)
Catalog Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_databases (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Lists databases that either reside in an instance of the SQL Server or are accessible through a database gateway.
Transact-SQL Syntax Conventions

Syntax
sp_databases

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

DATABASE_NAME sysname Name of the database. In the Database


Engine, this column represents the
database name as stored in the
sys.databases catalog view.

DATABASE_SIZE int Size of database, in kilobytes.

REMARKS varchar(254) For the Database Engine, this field


always returns NULL.

Remarks
Database names that are returned can be used as parameters in the USE statement to change the current database
context.
sp_databases has no equivalent in Open Database Connectivity (ODBC).

Permissions
Requires CREATE DATABASE, or ALTER ANY DATABASE, or VIEW ANY DEFINITION permission, and must have
access permission to the database. Cannot be denied VIEW ANY DEFINITION permission.

Examples
The following example shows executing sp_databases .
USE master;
GO
EXEC sp_databases;

See Also
sys.databases (Transact-SQL)
HAS_DBACCESS (Transact-SQL)
sp_fkeys (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns logical foreign key information for the current environment. This procedure shows foreign key
relationships including disabled foreign keys.
Transact-SQL Syntax Conventions

Syntax
sp_fkeys [ @pktable_name = ] 'pktable_name'
[ , [ @pktable_owner = ] 'pktable_owner' ]
[ , [ @pktable_qualifier = ] 'pktable_qualifier' ]
{ , [ @fktable_name = ] 'fktable_name' }
[ , [ @fktable_owner = ] 'fktable_owner' ]
[ , [ @fktable_qualifier = ] 'fktable_qualifier' ]

Arguments
[ @pktable_name=] 'pktable_name'
Is the name of the table, with the primary key, used to return catalog information. pktable_name is sysname, with
a default of NULL. Wildcard pattern matching is not supported. This parameter or the fktable_name parameter, or
both, must be supplied.
[ @pktable_owner=] 'pktable_owner'
Is the name of the owner of the table (with the primary key) used to return catalog information. pktable_owner is
sysname, with a default of NULL. Wildcard pattern matching is not supported. If pktable_owner is not specified,
the default table visibility rules of the underlying DBMS apply.
In SQL Server, if the current user owns a table with the specified name, that table's columns are returned. If
pktable_owner is not specified and the current user does not own a table with the specified pktable_name, the
procedure looks for a table with the specified pktable_name owned by the database owner. If one exists, that
table's columns are returned.
[ @pktable_qualifier =] 'pktable_qualifier'
Is the name of the table (with the primary key) qualifier. pktable_qualifier is sysname, with a default of NULL.
Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, the qualifier
represents the database name. In some products, it represents the server name of the table's database
environment.
[ @fktable_name=] 'fktable_name'
Is the name of the table (with a foreign key) used to return catalog information. fktable_name is sysname, with a
default of NULL. Wildcard pattern matching is not supported. This parameter or the pktable_name parameter, or
both, must be supplied.
[ @fktable_owner =] 'fktable_owner'
Is the name of the owner of the table (with a foreign key) used to return catalog information. fktable_owner is
sysname, with a default of NULL. Wildcard pattern matching is not supported. If fktable_owner is not specified, the
default table visibility rules of the underlying DBMS apply.
In SQL Server, if the current user owns a table with the specified name, that table's columns are returned. If
fktable_owner is not specified and the current user does not own a table with the specified fktable_name, the
procedure looks for a table with the specified fktable_name owned by the database owner. If one exists, that table's
columns are returned.
[ @fktable_qualifier= ] 'fktable_qualifier'
Is the name of the table (with a foreign key) qualifier. fktable_qualifier is sysname, with a default of NULL. In SQL
Server, the qualifier represents the database name. In some products, it represents the server name of the table's
database environment.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

PKTABLE_QUALIFIER sysname Name of the table (with the primary


key) qualifier. This field can be NULL.

PKTABLE_OWNER sysname Name of the table (with the primary


key) owner. This field always returns a
value.

PKTABLE_NAME sysname Name of the table (with the primary


key). This field always returns a value.

PKCOLUMN_NAME sysname Name of the primary key columns, for


each column of the TABLE_NAME
returned. This field always returns a
value.

FKTABLE_QUALIFIER sysname Name of the table (with a foreign key)


qualifier. This field can be NULL.

FKTABLE_OWNER sysname Name of the table (with a foreign key)


owner. This field always returns a value.

FKTABLE_NAME sysname Name of the table (with a foreign key).


This field always returns a value.

FKCOLUMN_NAME sysname Name of the foreign key column, for


each column of the TABLE_NAME
returned. This field always returns a
value.

KEY_SEQ smallint Sequence number of the column in a


multicolumn primary key. This field
always returns a value.
COLUMN NAME DATA TYPE DESCRIPTION

UPDATE_RULE smallint Action applied to the foreign key when


the SQL operation is an update.
Possible values:
0=CASCADE changes to foreign key.
1=NO ACTION changes if foreign key is
present.
2 = set null
3 = set default

DELETE_RULE smallint Action applied to the foreign key when


the SQL operation is a deletion. Possible
values:
0=CASCADE changes to foreign key.
1=NO ACTION changes if foreign key is
present.
2 = set null
3 = set default

FK_NAME sysname Foreign key identifier. It is NULL if not


applicable to the data source. SQL
Server returns the FOREIGN KEY
constraint name.

PK_NAME sysname Primary key identifier. It is NULL if not


applicable to the data source. SQL
Server returns the PRIMARY KEY
constraint name.

The results returned are ordered by FKTABLE_QUALIFIER, FKTABLE_OWNER, FKTABLE_NAME, and KEY_SEQ.

Remarks
Application coding that includes tables with disabled foreign keys can be implemented by the following:
Temporarily disabling constraint checking (ALTER TABLE NOCHECK or CREATE TABLE NOT FOR
REPLICATION) while working with the tables, and then enabling it again later.
Using triggers or application code to enforce relationships.
If the primary key table name is supplied and the foreign key table name is NULL, sp_fkeys returns all tables that
include a foreign key to the given table. If the foreign key table name is supplied and the primary key table name is
NULL, sp_fkeys returns all tables related by a primary key/foreign key relationship to foreign keys in the foreign
key table.
The sp_fkeys stored procedure is equivalent to SQLForeignKeys in ODBC.

Permissions
Requires SELECT permission on the schema.

Examples
The following example retrieves a list of foreign keys for the HumanResources.Department table in the
AdventureWorks2012 database.
USE AdventureWorks2012;
GO
EXEC sp_fkeys @pktable_name = N'Department'
,@pktable_owner = N'HumanResources';

Examples: Azure SQL Data Warehouse and Parallel Data Warehouse


The following example retrieves a list of foreign keys for the DimDate table in the AdventureWorksPDW2012 database.
No rows are returned because SQL Data Warehouse does not support foreign keys.

EXEC sp_fkeys @pktable_name = N'DimDate;

See Also
Catalog Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_pkeys (Transact-SQL)
sp_pkeys (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns primary key information for a single table in the current environment.
Transact-SQL Syntax Conventions

Syntax
-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse

sp_pkeys [ @table_name = ] 'name'


[ , [ @table_owner = ] 'owner' ]
[ , [ @table_qualifier = ] 'qualifier' ]

Arguments
[ @table_name= ] 'name'
Is the table for which to return information. name is sysname, with no default. Wildcard pattern matching is not
supported.
[ @table_owner= ] 'owner'
Specifies the table owner of the specified table. owner is sysname, with a default of NULL. Wildcard pattern
matching is not supported. If owner is not specified, the default table visibility rules of the underlying DBMS apply.
In SQL Server, if the current user owns a table with the specified name, the columns of that table are returned. If
the owner is not specified and the current user does not own a table with the specified name, this procedure looks
for a table with the specified name owned by the database owner. If one exists, the columns of that table are
returned.
[ @table_qualifier= ] 'qualifier'
Is the table qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support three-part
naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In some
products, it represents the server name of the database environment of the table.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_QUALIFIER sysname Name of the table qualifier. This field


can be NULL.

TABLE_OWNER sysname Name of the table owner. This field


always returns a value.
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_NAME sysname Name of the table. In SQL Server, this


column represents the table name as
listed in the sysobjects table. This field
always returns a value.

COLUMN_NAME sysname Name of the column, for each column


of the TABLE_NAME returned. In SQL
Server, this column represents the
column name as listed in the
sys.columns table. This field always
returns a value.

KEY_SEQ smallint Sequence number of the column in a


multicolumn primary key.

PK_NAME sysname Primary key identifier. Returns NULL if


not applicable to the data source.

Remarks
sp_pkeys returns information about columns explicitly defined with a PRIMARY KEY constraint. Because not all
systems support explicitly named primary keys, the gateway implementer determines what constitutes a primary
key. Note that the term primary key refers to a logical primary key for a table. It is expected that every key listed as
being a logical primary key has a unique index defined on it. This unique index is also returned in sp_statistics.
The sp_pkeys stored procedure is equivalent to SQLPrimaryKeys in ODBC. The results returned are ordered by
TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, and KEY_SEQ.

Permissions
Requires SELECT permission on the schema.

Examples
The following example retrieves the primary key for the HumanResources.Department table in the
AdventureWorks2012 database.

USE AdventureWorks2012;
GO
EXEC sp_pkeys @table_name = N'Department'
,@table_owner = N'HumanResources';

Examples: Azure SQL Data Warehouse and Parallel Data Warehouse


The following example retrieves the primary key for the DimAccount table in the AdventureWorksPDW2012 database.
It returns zero rows indicating that the table does not have a primary key.

-- Uses AdventureWorks

EXEC sp_pkeys @table_name = N'DimAccount;


See Also
Catalog Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_server_info (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a list of attribute names and matching values for SQL Server, the database gateway, or the underlying data
source.
Transact-SQL Syntax Conventions

Syntax
sp_server_info [[@attribute_id = ] 'attribute_id']

Arguments
[ @attribute_id = ] 'attribute_id'
Is the integer ID of the attribute. attribute_id is int, with a default of NULL.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

ATTRIBUTE_ID int ID number of the attribute.

ATTRIBUTE_NAME varchar(60) Attribute name.

ATTRIBUTE_VALUE varchar(255) Current setting of the attribute.

The following table lists the attributes. Microsoft ODBC client libraries currently use attributes 1, 2, 18, 22, and 500
at connection time.

ATTRIBUTE_ID ATTRIBUTE_NAME DESCRIPTION ATTRIBUTE_VALUE

1 DBMS_NAME SQL Server

2 DBMS_VER SQL Server 2017 - x.xx.xxxx

10 OWNER_TERM owner

11 TABLE_TERM table

12 MAX_OWNER_NAME_LENGTH 128
ATTRIBUTE_ID ATTRIBUTE_NAME DESCRIPTION ATTRIBUTE_VALUE

13 TABLE_LENGTH 128

Specifies the maximum number of


characters for a table name.

14 MAX_QUAL_LENGTH 128

Specifies the maximum length of the


name for a table qualifier (the first part
of a three-part table name).

15 COLUMN_LENGTH 128

Specifies the maximum number of


characters for a column name.

16 IDENTIFIER_CASE SENSITIVE

Specifies the user-defined names (table


names, column names, stored
procedure names) in the database (the
case of the objects in the system
catalogs).

17 TX_ISOLATION 2

Specifies the initial transaction isolation


level the server assumes, which
corresponds to an isolation level
defined in SQL-92.

18 COLLATION_SEQ charset=iso_1 sort_order=dictionary_iso


charset_num=1 sort_order_num=51
Specifies the ordering of the character
set for this server.

19 SAVEPOINT_SUPPORT Y

Specifies whether the underlying DBMS


supports named savepoints.

20 MULTI_RESULT_SETS Y

Specifies whether the underlying


database or the gateway itself supports
multiple result sets (multiple statements
can be sent through the gateway with
multiple result sets returned to the
client).

22 ACCESSIBLE_TABLES Y

Specifies whether in sp_tables, the


gateway returns only tables, views, and
so on, accessible by the current user
(that is, the user who has at least
SELECT permissions for the table).
ATTRIBUTE_ID ATTRIBUTE_NAME DESCRIPTION ATTRIBUTE_VALUE

100 USERID_LENGTH 128

Specifies the maximum number of


characters for a username.

101 QUALIFIER_TERM database

Specifies the DBMS vendor term for a


table qualifier (the first part of a three-
part name).

102 NAMED_TRANSACTIONS Y

Specifies whether the underlying DBMS


supports named transactions.

103 SPROC_AS_LANGUAGE Y

Specifies whether stored procedures can


be executed as language events.

104 ACCESSIBLE_SPROC Y

Specifies whether in
sp_stored_procedures, the gateway
returns only stored procedures that are
executable by the current user.

105 MAX_INDEX_COLS 16

Specifies the maximum number of


columns in an index for the DBMS.

106 RENAME_TABLE Y

Specifies whether tables can be


renamed.

107 RENAME_COLUMN Y

Specifies whether columns can be


renamed.

108 DROP_COLUMN Y

Specifies whether columns can be


dropped.

109 INCREASE_COLUMN_LENGTH Y

Specifies whether column size can be


increased.

110 DDL_IN_TRANSACTION Y

Specifies whether DDL statements can


appear in transactions.
ATTRIBUTE_ID ATTRIBUTE_NAME DESCRIPTION ATTRIBUTE_VALUE

111 DESCENDING_INDEXES Y

Specifies whether descending indexes


are supported.

112 SP_RENAME Y

Specifies whether a stored procedure


can be renamed.

113 REMOTE_SPROC Y

Specifies whether stored procedures can


be executed through the remote stored
procedure functions in DB-Library.

500 SYS_SPROC_VERSION Current version number

Specifies the version of the catalog


stored procedures currently
implemented.

Remarks
sp_server_info returns a subset of the information provided by SQLGetInfo in ODBC.

Permissions
Requires SELECT permission on the schema.

See Also
Catalog Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_special_columns (Transact-SQL)
1/2/2018 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the optimal set of columns that uniquely identify a row in the table. Also returns columns automatically
updated when any value in the row is updated by a transaction.
Transact-SQL Syntax Conventions

Syntax
sp_special_columns [ @table_name = ] 'table_name'
[ , [ @table_owner = ] 'table_owner' ]
[ , [ @qualifier = ] 'qualifier' ]
[ , [ @col_type = ] 'col_type' ]
[ , [ @scope = ] 'scope' ]
[ , [ @nullable = ] 'nullable' ]
[ , [ @ODBCVer = ] 'ODBCVer' ]
[ ; ]

Arguments
[ @table_name=] 'table_name'
Is the name of the table used to return catalog information. name is sysname, with no default. Wildcard pattern
matching is not supported.
[ @table_owner=] 'table_owner'
Is the table owner of the table used to return catalog information. owner is sysname, with a default of NULL.
Wildcard pattern matching is not supported. If owner is not specified, the default table visibility rules of the
underlying DBMS apply.
In SQL Server, if the current user owns a table with the specified name, the columns of that table are returned. If
owner is not specified and the current user does not own a table of the specified name, this procedure looks for a
table of the specified name owned by the database owner. If the table exists, its columns are returned.
[ @qualifier=] 'qualifier'
Is the name of the table qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support
three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In
some products, it represents the server name of the database environment of the table.
[ @col_type=] 'col_type'
Is the column type. col_type is char(1), with a default of R. Type R returns the optimal column or set of columns
that, by retrieving values from the column or columns, allows for any row in the specified table to be uniquely
identified. A column can be either a pseudocolumn specifically designed for this purpose, or the column or
columns of any unique index for the table. Type V returns the column or columns in the specified table, if any, that
are automatically updated by the data source when any value in the row is updated by any transaction.
[ @scope=] 'scope'
Is the minimum required scope of the ROWID. scope is char(1), with a default of T. Scope C specifies that the
ROWID is valid only when positioned on that row. Scope T specifies that the ROWID is valid for the transaction.
[ @nullable=] 'nullable'
Is whether the special columns can accept a null value. nullable is char(1), with a default of U. O specifies special
columns that do not allow null values. U specifies columns that are partially nullable.
[ @ODBCVer=] 'ODBCVer'
Is the ODBC version being used. ODBCVer is int(4), with a default of 2. This indicates ODBC version 2.0. For more
information about the difference between ODBC version 2.0 and ODBC version 3.0, see the ODBC
SQLSpecialColumns specification for ODBC version 3.0.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

SCOPE smallint Actual scope of the row ID. Can be 0, 1,


or 2. SQL Server always returns 0. This
field always returns a value.

0 = SQL_SCOPE_CURROW. The row ID


is guaranteed to be valid only while
positioned on that row. A later reselect
using the row ID may not return a row
if the row was updated or deleted by
another transaction.

1 = SQL_SCOPE_TRANSACTION. The
row ID is guaranteed to be valid for the
duration of the current transaction.

2 = SQL_SCOPE_SESSION. The row ID is


guaranteed to be valid for the duration
of the session (across transaction
boundaries).

COLUMN_NAME sysname Column name for each column of the


tablereturned. This field always returns
a value.

DATA_TYPE smallint ODBC SQL data type.

TYPE_NAME sysname Data source-dependent data type


name; for example, char, varchar,
money, or text.

PRECISION Int Precision of the column on the data


source. This field always returns a value.

LENGTH Int Length, in bytes, required for the data


type in its binary form in the data
source, for example, 10 for char(10), 4
for integer, and 2 for smallint.

SCALE smallint Scale of the column on the data source.


NULL is returned for data types for
which scale is not applicable.
COLUMN NAME DATA TYPE DESCRIPTION

PSEUDO_COLUMN smallint Indicates whether the column is a


pseudocolumn. SQL Server always
returns 1:

0 = SQL_PC_UNKNOWN

1 = SQL_PC_NOT_PSEUDO

2 = SQL_PC_PSEUDO

Remarks
sp_special_columns is equivalent to SQLSpecialColumns in ODBC. The results returned are ordered by SCOPE.

Permissions
Requires SELECT permission on the schema.

Examples
The following example returns information about the column that uniquely identifies rows in the
HumanResources.Department table.

USE AdventureWorks2012;
GO
EXEC sp_special_columns @table_name = 'Department'
,@table_owner = 'HumanResources';

See Also
Catalog Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_sproc_columns (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns column information for a single stored procedure or user-defined function in the current environment.
Transact-SQL Syntax Conventions

Syntax
-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse

sp_sproc_columns [[@procedure_name = ] 'name']


[ , [@procedure_owner = ] 'owner']
[ , [@procedure_qualifier = ] 'qualifier']
[ , [@column_name = ] 'column_name']
[ , [@ODBCVer = ] 'ODBCVer']
[ , [@fUsePattern = ] 'fUsePattern']

Arguments
[ @procedure_name = ] 'name'
Is the name of the procedure used to return catalog information. name is nvarchar(390), with a default of %,
which means all tables in the current database. Wildcard pattern matching is supported.
[ @procedure_owner =] 'owner'
Is the name of the owner of the procedure. owneris nvarchar(384), with a default of NULL. Wildcard pattern
matching is supported. If owner is not specified, the default procedure visibility rules of the underlying DBMS
apply.
If the current user owns a procedure with the specified name, information about that procedure is returned. If
owneris not specified and the current user does not own a procedure with the specified name, sp_sproc_columns
looks for a procedure with the specified name that is owned by the database owner. If the procedure exists,
information about its columns is returned.
[ @procedure_qualifier =] 'qualifier'
Is the name of the procedure qualifier. qualifier is sysname, with a default of NULL. Various DBMS products
support three-part naming for tables (qualifier.owner.name). In SQL Server, this parameter represents the database
name. In some products, it represents the server name of the table's database environment.
[ @column_name =] 'column_name'
Is a single column and is used when only one column of catalog information is desired. column_name is
nvarchar(384), with a default of NULL. If column_name is omitted, all columns are returned. Wildcard pattern
matching is supported. For maximum interoperability, the gateway client should assume only ISO standard pattern
matching (the % and _ wildcard characters).
[ @ODBCVer =] 'ODBCVer'
Is the version of ODBC being used. ODBCVer is int, with a default of 2, which indicates ODBC version 2.0. For more
information about the difference between ODBC version 2.0 and ODBC version 3.0, refer to the ODBC
SQLProcedureColumns specification for ODBC version 3.0
[ @fUsePattern =] 'fUsePattern'
Determines whether the underscore (_), percent (%), and bracket ([ ]) characters are interpreted as wildcard
characters. Valid values are 0 (pattern matching is off) and 1 (pattern matching is on). fUsePattern is bit, with a
default of 1.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

PROCEDURE_QUALIFIER sysname Procedure qualifier name. This column


can be NULL.

PROCEDURE_OWNER sysname Procedure owner name. This column


always returns a value.

PROCEDURE_NAME nvarchar(134) Procedure name. This column always


returns a value.

COLUMN_NAME sysname Column name for each column of the


TABLE_NAME returned. This column
always returns a value.

COLUMN_TYPE smallint This field always returns a value:

0 = SQL_PARAM_TYPE_UNKNOWN

1 = SQL_PARAM_TYPE_INPUT

2 = SQL_PARAM_TYPE_OUTPUT

3 = SQL_RESULT_COL

4 = SQL_PARAM_OUTPUT

5 = SQL_RETURN_VALUE

DATA_TYPE smallint Integer code for an ODBC data type. If


this data type cannot be mapped to an
ISO type, the value is NULL. The native
data type name is returned in the
TYPE_NAME column.

TYPE_NAME sysname String representation of the data type.


This is the data type name as presented
by the underlying DBMS.

PRECISION int Number of significant digits. The return


value for the PRECISION column is in
base 10.

LENGTH int Transfer size of the data.


COLUMN NAME DATA TYPE DESCRIPTION

SCALE smallint Number of digits to the right of the


decimal point.

RADIX smallint Is the base for numeric types.

NULLABLE smallint Specifies nullability:

1 = Data type can be created allowing


null values.

0 = Null values are not allowed.

REMARKS varchar(254) Description of the procedure column.


SQL Server does not return a value for
this column.

COLUMN_DEF nvarchar(4000) Default value of the column.

SQL_DATA_TYPE smallint Value of the SQL data type as it appears


in the TYPE field of the descriptor. This
column is the same as the DATA_TYPE
column, except for the datetime and
ISO interval data types. This column
always returns a value.

SQL_DATETIME_SUB smallint The datetime ISO interval subcode if


the value of SQL_DATA_TYPE is
SQL_DATETIME or SQL_INTERVAL. For
data types other than datetime and
ISO interval, this field is NULL.

CHAR_OCTET_LENGTH int Maximum length in bytes of a


character or binary data type column.
For all other data types, this column
returns a NULL.

ORDINAL_POSITION int Ordinal position of the column in the


table. The first column in the table is 1.
This column always returns a value.

IS_NULLABLE varchar(254) Nullability of the column in the table.


ISO rules are followed to determine
nullability. An ISO compliant DBMS
cannot return an empty string.

Displays YES if the column can include


NULLS and NO if the column cannot
include NULLS.

This column returns a zero-length string


if nullability is unknown.

The value returned for this column is


different from the value returned for the
NULLABLE column.
COLUMN NAME DATA TYPE DESCRIPTION

SS_DATA_TYPE tinyint SQL Server data type used by extended


stored procedures. For more
information, see Data Types (Transact-
SQL).

Remarks
sp_sproc_columns is equivalent to SQLProcedureColumns in ODBC. The results returned are ordered by
PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME, and the order that the parameters
appear in the procedure definition.

Permissions
Requires SELECT permission on the schema.

See Also
Catalog Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_statistics (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns a list of all indexes and statistics on a specified table or indexed view.
Transact-SQL Syntax Conventions

Syntax
-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse

sp_statistics [ @table_name = ] 'table_name'


[ , [ @table_owner = ] 'owner' ]
[ , [ @table_qualifier = ] 'qualifier' ]
[ , [ @index_name = ] 'index_name' ]
[ , [ @is_unique = ] 'is_unique' ]
[ , [ @accuracy = ] 'accuracy' ]

Arguments
[ @table_name= ] 'table_name'
Specifies the table used to return catalog information. table_name is sysname, with no default. Wildcard pattern
matching is not supported.
[ @table_owner= ] 'owner'
Is the name of the table owner of the table used to return catalog information. table_owner is sysname, with a
default of NULL. Wildcard pattern matching is not supported. If owner is not specified, the default table visibility
rules of the underlying DBMS apply.
In SQL Server, if the current user owns a table with the specified name, the indexes of that table are returned. If
owner is not specified and the current user does not own a table with the specified name, this procedure looks for
a table with the specified name owned by the database owner. If one exists, the indexes of that table are returned.
[ @table_qualifier= ] 'qualifier'
Is the name of the table qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support
three-part naming for tables (qualifier.owner.name). In SQL Server, this parameter represents the database name.
In some products, it represents the server name of the table's database environment.
[ @index_name= ] 'index_name'
Is the index name. index_name is sysname, with a default of %. Wildcard pattern matching is supported.
[ @is_unique= ] 'is_unique'
Is whether only unique indexes (if Y) are to be returned. is_unique is char(1), with a default of N.
[ @accuracy= ] 'accuracy'
Is the level of cardinality and page accuracy for statistics. accuracy is char(1), with a default of Q. Specify E to make
sure that statistics are updated so that cardinality and pages are accurate.
The value E (SQL_ENSURE) asks the driver to unconditionally retrieve the statistics.
The value Q (SQL_QUICK) asks the driver to retrieve the cardinality and pages only if they are readily available
from the server. In this case, the driver does not ensure that the values are current. Applications that are written to
the Open Group standard will always get SQL_QUICK behavior from ODBC 3.x-compliant drivers.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_QUALIFIER sysname Table qualifier name. This column can be


NULL.

TABLE_OWNER sysname Table owner name. This column always


returns a value.

TABLE_NAME sysname Table name. This column always returns


a value.

NON_UNIQUE smallint NOT NULL.

0 = Unique

1 = Not unique

INDEX_QUALIFIER sysname Index owner name. Some DBMS


products allow for users other than the
table owner to create indexes. In SQL
Server, this column is always the same
as TABLE_NAME.

INDEX_NAME sysname Is the name of the index. This column


always returns a value.

TYPE smallint This column always returns a value:

0 = Statistics for a table

1 = Clustered

2 = Hashed

3 = Nonclustered

SEQ_IN_INDEX smallint Position of the column within the index.

COLUMN_NAME sysname Column name for each column of the


TABLE_NAME returned. This column
always returns a value.

COLLATION char(1) Order used in collation. Can be:

A = Ascending

D = Descending

NULL = Not applicable

CARDINALITY int Number of rows in the table or unique


values in the index.
COLUMN NAME DATA TYPE DESCRIPTION

PAGES int Number of pages to store the index or


table.

FILTER_CONDITION varchar(128) SQL Server does not return a value.

Return Code Values


None

Remarks
The indexes in the result set appear in ascending order by the columns NON_UNIQUE, TYPE, INDEX_NAME, and
SEQ_IN_INDEX.
The index type clustered refers to an index in which table data is stored in the order of the index. This corresponds
to SQL Server clustered indexes.
The index type Hashed accepts exact match or range searches, but pattern matching searches do not use the index.
sp_statistics is equivalent to SQLStatistics in ODBC. The results returned are ordered by NON_UNIQUE, TYPE,
INDEX_QUALIFIER, INDEX_NAME, and SEQ_IN_INDEX. For more information, see the ODBC API Reference.

Permissions
Requires SELECT permission on the schema.

Example: Azure SQL Data Warehouse and Parallel Data Warehouse


The following example returns information about the DimEmployee table.

-- Uses AdventureWorks

EXEC sp_statistics DimEmployee;

See Also
Catalog Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_stored_procedures (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a list of stored procedures in the current environment.
Transact-SQL Syntax Conventions

Syntax
sp_stored_procedures [ [ @sp_name = ] 'name' ]
[ , [ @sp_owner = ] 'schema']
[ , [ @sp_qualifier = ] 'qualifier' ]
[ , [@fUsePattern = ] 'fUsePattern' ]

Arguments
[ @sp_name = ] 'name'
Is the name of the procedure used to return catalog information. name is nvarchar(390), with a default of NULL.
Wildcard pattern matching is supported.
[ @sp_owner = ] 'schema'
Is the name of the schema to which the procedure belongs. schema is nvarchar(384), with a default of NULL.
Wildcard pattern matching is supported. If owner is not specified, the default procedure visibility rules of the
underlying DBMS apply.
In SQL Server, if the current schema contains a procedure with the specified name, that procedure is returned. If a
nonqualified stored procedure is specified, the Database Engine searches for the procedure in the following order:
The sys schema of the current database.
The caller's default schema if executed in a batch or in dynamic SQL; or, if the non-qualified procedure name
appears inside the body of another procedure definition, the schema containing this other procedure is
searched next.
The dbo schema in the current database.
[ @qualifier = ] 'qualifier'
Is the name of the procedure qualifier. qualifier is sysname, with a default of NULL. Various DBMS products
support three-part naming for tables in the form (qualifier.schema.name. In SQL Server, qualifier represents
the database name. In some products, it represents the server name of the database environment of the
table.
[ @fUsePattern = ] 'fUsePattern'
Determines whether the underscore (_), percent (%), or brackets [ ]) are interpreted as wildcard characters.
fUsePattern is bit, with a default of 1.
0 = Pattern matching is off.
1 = Pattern matching is on.
Return Code Values
None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

PROCEDURE_QUALIFIER sysname Procedure qualifier name. This column


can be NULL.

PROCEDURE_OWNER sysname Procedure owner name. This column


always returns a value.

PROCEDURE_NAME nvarchar(134) Procedure name. This column always


returns a value.

NUM_INPUT_PARAMS int Reserved for future use.

NUM_OUTPUT_PARAMS int Reserved for future use.

NUM_RESULT_SETS int Reserved for future use.

REMARKS varchar(254) Description of the procedure. SQL


Server does not return a value for this
column.

PROCEDURE_TYPE smallint Procedure type. SQL Server always


returns 2.0. This value can be one of the
following:

0 = SQL_PT_UNKNOWN

1 = SQL_PT_PROCEDURE

2 = SQL_PT_FUNCTION

Remarks
For maximum interoperability, the gateway client should assume only SQL standard pattern matching (the percent
(%) and underscore (_) wildcard characters).
The permission information about execute access to a specific stored procedure for the current user is not
necessarily checked; therefore, access is not guaranteed. Note that only three-part naming is used. This means that
only local stored procedures, not remote stored procedures (which require four-part naming), are returned when
they are executed against SQL Server. If the server attribute ACCESSIBLE_SPROC is Y in the result set for
sp_server_info, only stored procedures that can be executed by the current user are returned.
sp_stored_procedures is equivalent to SQLProcedures in ODBC. The results returned are ordered by
PROCEDURE_QUALIFIER, PROCEDURE_OWNER, and PROCEDURE_NAME.

Permissions
Requires SELECT permission on the schema.
Examples
A. Returning all stored procedures in the current database
The following example returns all stored procedures in the AdventureWorks2012 database.

USE AdventureWorks2012;
GO
EXEC sp_stored_procedures;

B. Returning a single stored procedure


The following example returns a result set for the uspLogError stored procedure.

USE AdventureWorks2012;
GO
sp_stored_procedures N'uspLogError', N'dbo', N'AdventureWorks2012', 1;

See Also
Catalog Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_table_privileges (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns a list of table permissions (such as INSERT, DELETE, UPDATE, SELECT, REFERENCES) for the specified table
or tables.
Transact-SQL Syntax Conventions

Syntax
sp_table_privileges [ @table_name = ] 'table_name'
[ , [ @table_owner = ] 'table_owner' ]
[ , [ @table_qualifier = ] 'table_qualifier' ]
[ , [ @fUsePattern = ] 'fUsePattern' ]

Arguments
[ @table_name= ] 'table_name'
Is the table used to return catalog information. table_name is nvarchar(384), with no default. Wildcard pattern
matching is supported.
[ @table_owner= ] 'table_owner'
Is the table owner of the table used to return catalog information. table_owneris nvarchar(384), with a default of
NULL. Wildcard pattern matching is supported. If the owner is not specified, the default table visibility rules of the
underlying DBMS apply.
If the current user owns a table with the specified name, the columns of that table are returned. If owner is not
specified and the current user does not own a table with the specified name, this procedure looks for a table with
the specified table_name owned by the database owner. If one exists, the columns of that table are returned.
[ @table_qualifier= ] 'table_qualifier'
Is the name of the table qualifier. table_qualifier is sysname, with a default of NULL. Various DBMS products
support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database
name. In some products, it represents the server name of the table's database environment.
[ @fUsePattern= ] 'fUsePattern'
Determines whether the underscore (_), percent (%), and bracket ([ or ]) characters are interpreted as wildcard
characters. Valid values are 0 (pattern matching is off) and 1 (pattern matching is on). fUsePattern is bit, with a
default of 1.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_QUALIFIER sysname Table qualifier name. In SQL Server, this


column represents the database name.
This field can be NULL.

TABLE_OWNER sysname Table owner name. This field always


returns a value.

TABLE_NAME sysname Table name. This field always returns a


value.

GRANTOR sysname Database username that has granted


permissions on this TABLE_NAME to
the listed GRANTEE. In SQL Server, this
column is always the same as the
TABLE_OWNER. This field always
returns a value. Also, the GRANTOR
column may be either the database
owner (TABLE_OWNER) or a user to
whom the database owner granted
permission by using the WITH GRANT
OPTION clause in the GRANT
statement.

GRANTEE sysname Database username that has been


granted permissions on this
TABLE_NAME by the listed GRANTOR.
In SQL Server, this column always
includes a database user from the
sys.database_principalssystem view.
This field always returns a value.
COLUMN NAME DATA TYPE DESCRIPTION

PRIVILEGE sysname One of the available table permissions.


Table permissions can be one of the
following values (or other values
supported by the data source when
implementation is defined):

SELECT = GRANTEE can retrieve data


for one or more of the columns.

INSERT = GRANTEE can provide data


for new rows for one or more of the
columns.

UPDATE = GRANTEE can modify


existing data for one or more of the
columns.

DELETE = GRANTEE can remove rows


from the table.

REFERENCES = GRANTEE can reference


a column in a foreign table in a primary
key/foreign key relationship. In SQL
Server, primary key/foreign key
relationships are defined with table
constraints.

The scope of action given to the


GRANTEE by a given table privilege is
data source-dependent. For example,
the UPDATE privilege may permit the
GRANTEE to update all columns in a
table on one data source and only
those columns for which the GRANTOR
has UPDATE privilege on another data
source.

IS_GRANTABLE sysname Indicates whether or not the GRANTEE


is permitted to grant permissions to
other users (often referred to as "grant
with grant" permission). Can be YES,
NO, or NULL. An unknown (or NULL)
value refers to a data source for which
"grant with grant" is not applicable.

Remarks
The sp_table_privileges stored procedure is equivalent to SQLTablePrivileges in ODBC. The results returned are
ordered by TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, and PRIVILEGE.

Permissions
Requires SELECT permission on the schema.

Examples
The following example returns privilege information about all tables with names beginning with the word
Contact .
USE AdventureWorks2012;
GO
EXEC sp_table_privileges
@table_name = 'Contact%';

See Also
Catalog Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_tables (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns a list of objects that can be queried in the current environment. This means any table or view, except
synonym objects.

NOTE
To determine the name of the base object of a synonym, query the sys.synonyms catalog view.

Transact-SQL Syntax Conventions

Syntax
-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse

sp_tables [ [ @table_name = ] 'name' ]


[ , [ @table_owner = ] 'owner' ]
[ , [ @table_qualifier = ] 'qualifier' ]
[ , [ @table_type = ] "type" ]
[ , [@fUsePattern = ] 'fUsePattern'];

Arguments
[ @table_name= ] 'name'
Is the table used to return catalog information. name is nvarchar(384), with a default of NULL. Wildcard pattern
matching is supported.
[ @table_owner= ] 'owner'
Is the table owner of the table used to return catalog information. owner is nvarchar(384), with a default of NULL.
Wildcard pattern matching is supported. If the owner is not specified, the default table visibility rules of the
underlying DBMS apply.
In SQL Server, if the current user owns a table with the specified name, the columns of that table are returned. If
the owner is not specified and the current user does not own a table with the specified name, this procedure looks
for a table with the specified name owned by the database owner. If one exists, the columns of that table are
returned.
[ @table_qualifier= ] 'qualifier'
Is the name of the table qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support
three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In
some products, it represents the server name of the table's database environment.
[ , [ @table_type= ] "'type', 'type'" ]
Is a list of values, separated by commas, that gives information about all tables of the table types that are specified.
These include TABLE, SYSTEMTABLE, and VIEW. type is varchar(100), with a default of NULL.
NOTE
Single quotation marks must enclose each table type, and double quotation marks must enclose the whole parameter. Table
types must be uppercase. If SET QUOTED_IDENTIFIER is ON, each single quotation mark must be doubled and the whole
parameter must be enclosed in single quotation marks.

[ @fUsePattern = ] 'fUsePattern'
Determines whether the underscore ( _ ), percent ( % ), and bracket ( [ or ] ) characters are interpreted as wildcard
characters. Valid values are 0 (pattern matching is off) and 1 (pattern matching is on). fUsePattern is bit, with a
default of 1.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_QUALIFIER sysname Table qualifier name. In SQL Server, this


column represents the database name.
This field can be NULL.

TABLE_OWNER sysname Table owner name. In SQL Server, this


column represents the name of the
database user who created the table.
This field always returns a value.

TABLE_NAME sysname Table name. This field always returns a


value.

TABLE_TYPE varchar(32) Table, system table, or view.

REMARKS varchar(254) SQL Server does not return a value for


this column.

Remarks
For maximum interoperability, the gateway client should assume only SQL-92-standard SQL pattern matching (the
% and _ wildcard characters).
Privilege information about the current user's read or write access to a specific table is not always checked.
Therefore access is not guaranteed. This result set includes not only tables and views, but also synonyms and
aliases for gateways to DBMS products that support those types. If the server attribute ACCESSIBLE_TABLES is Y
in the result set for sp_server_info, only tables that can be accessed by the current user are returned.
sp_tables is equivalent to SQLTables in ODBC. The results returned are ordered by TABLE_TYPE,
TABLE_QUALIFIER, TABLE_OWNER, and TABLE_NAME.

Permissions
Requires SELECT permission on the schema.

Examples
A. Returning a list of objects that can be queried in the current environment
The following example returns a list of objects that can be queries in the current environment.

EXEC sp_tables ;

B. Returning information about the tables in a specified schema


The following example returns information about the tables that belong to the Person schema in the
AdventureWorks2012 database.

USE AdventureWorks2012;
GO
EXEC sp_tables
@table_name = '%',
@table_owner = 'Person',
@table_qualifier = 'AdventureWorks2012';

Examples: Azure SQL Data Warehouse and Parallel Data Warehouse


C. Returning a list of objects that can be queried in the current environment
The following example returns a list of objects that can be queries in the current environment.

EXEC sp_tables ;

D. Returning information about the tables in a specified schema


The following example returns information about the dimension tables in the AdventureWorksPDW201 database.

-- Uses AdventureWorks

EXEC sp_tables
@table_name = 'Dim%',
@table_owner = 'dbo',
@table_qualifier = 'AdventureWorksPDW2012';

See Also
sys.synonyms (Transact-SQL)
System Stored Procedures (Transact-SQL)
Change Data Capture Stored Procedures (Transact-
SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Change data capture makes available in a convenient relational format the historical record of Data Manipulation
Language (DML) activity that occurred on enabled tables. The following stored procedures are used to configure
change data capture, manage the change data capture Agent jobs, and supply current meta data to change data
consumers.

sys.sp_cdc_add_job (Transact-SQL) sys.sp_cdc_generate_wrapper_function (Transact-SQL)

sys.sp_cdc_change_job (Transact-SQL) sys.sp_cdc_get_captured_columns (Transact-SQL)

sys.sp_cdc_cleanup_change_table (Transact-SQL) sys.sp_cdc_get_ddl_history (Transact-SQL)

sys.sp_cdc_disable_db (Transact-SQL) sys.sp_cdc_help_change_data_capture (Transact-SQL)

sys.sp_cdc_disable_table (Transact-SQL) sys.sp_cdc_help_jobs (Transact-SQL)

sys.sp_cdc_drop_job (Transact-SQL) sys.sp_cdc_scan (Transact-SQL)

sys.sp_cdc_enable_db (Transact-SQL) sys.sp_cdc_start_job (Transact-SQL)

sys.sp_cdc_enable_table (Transact-SQL) sys.sp_cdc_stop_job (Transact-SQL)

See Also
Change Data Capture Tables (Transact-SQL)
sys.sp_cdc_add_job (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a change data capture cleanup or capture job in the current database.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_add_job [ @job_type = ] 'job_type'
[ , [ @start_job = ] start_job ]
[ , [ @maxtrans = ] max_trans ]
[ , [ @maxscans = ] max_scans ]
[ , [ @continuous = ] continuous ]
[ , [ @pollinginterval = ] polling_interval ]
[ , [ @retention ] = retention ]
[ , [ @threshold ] = 'delete_threshold' ]

Arguments
[ @job_type= ] 'job_type'
Type of job to add. job_type is nvarchar(20) and cannot be NULL. Valid inputs are 'capture' and 'cleanup'.
[ @start_job= ] start_job
Flag indicating whether the job should be started immediately after it is added. start_job is bit with a default of 1.
[ @maxtrans ] = max_trans
Maximum number of transactions to process in each scan cycle. max_trans is int with a default of 500. If specified,
the value must be a positive integer.
max_trans is valid only for capture jobs.
[ @maxscans ] =max_scans
Maximum number of scan cycles to execute in order to extract all rows from the log. max_scans is int with a
default of 10.
max_scan is valid only for capture jobs.
[ @continuous ] =continuous
Indicates whether the capture job is to run continuously (1), or run only once (0). continuous is bit with a default of
1.
When continuous = 1, the sp_cdc_scan job scans the log and processes up to (max_trans * max_scans)
transactions. It then waits the number of seconds specified in polling_interval before beginning the next log scan.
When continuous = 0, the sp_cdc_scan job executes up to max_scans scans of the log, processing up to max_trans
transaction during each scan, and then exits.
continuous is valid only for capture jobs.
[ @pollinginterval ] =polling_interval
Number of seconds between log scan cycles. polling_interval is bigint with a default of 5.
polling_interval is valid only for capture jobs when continuous is set to 1. If specified, the value cannot be negative
and cannot exceed 24 hours. If a value of 0 is specified, there is no wait between log scans.
[ @retention ] =retention
Number of minutes that change data rows are to be retained in change tables. retention is bigint with a default of
4320 (72 hours). The maximum value is 52494800 (100 years). If specified, the value must be a positive integer.
retention is valid only for cleanup jobs.
[ @threshold = ] 'delete_threshold'
Maximum number of delete entries that can be deleted by using a single statement on cleanup. delete_threshold is
bigint with a default of 5000.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
A cleanup job is created using the default values when the first table in the database is enabled for change data
capture. A capture job is created using the default values when the first table in the database is enabled for change
data capture and no transactional publications exist for the database. When a transactional publication exists, the
transactional log reader is used to drive the capture mechanism, and a separate capture job is neither required nor
allowed.
Because the cleanup and capture jobs are created by default, this stored procedure is necessary only when a job
has been explicitly dropped and must be recreated.
The name of the job is cdc.<database_name>_cleanup or cdc.<database_name>_capture, where
<database_name> is the name of the current database. If a job with the same name already exists, the name is
appended with a period (.) followed by a unique identifier, for example:
cdc.AdventureWorks_capture.A1ACBDED-13FC-428C-8302-10100EF74F52.
To view the current configuration of a cleanup or capture job, use sp_cdc_help_jobs. To change the configuration
of a job, use sp_cdc_change_job.

Permissions
Requires membership in the db_owner fixed database role.

Examples
A. Creating a capture job
The following example creates a capture job. This example assumes that the existing cleanup job was explicitly
dropped and must be recreated. The job is created using the default values.

USE AdventureWorks2012;
GO
EXEC sys.sp_cdc_add_job @job_type = N'capture';
GO
B. Creating a cleanup job
The following example creates a cleanup job in the AdventureWorks2012 database. The parameter @start_job is
set to 0 and @retention is set to 5760 minutes (96 hours). This example assumes that the existing cleanup job was
explicitly dropped and must be recreated.

USE AdventureWorks2012;
GO
EXEC sys.sp_cdc_add_job
@job_type = N'cleanup'
,@start_job = 0
,@retention = 5760;

See Also
dbo.cdc_jobs (Transact-SQL)
sys.sp_cdc_enable_table (Transact-SQL)
About Change Data Capture (SQL Server)
sys.sp_cdc_change_job (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Modifies the configuration of a change data capture cleanup or capture job in the current database. To view the
current configuration of a job, query the dbo.cdc_jobs table, or use sp_cdc_help_jobs.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_change_job [ [ @job_type = ] 'job_type' ]
[ , [ @maxtrans = ] max_trans ]
[ , [ @maxscans = ] max_scans ]
[ , [ @continuous = ] continuous ]
[ , [ @pollinginterval = ] polling_interval ]
[ , [ @retention ] = retention ]
[ @threshold = ] 'delete threshold'

Arguments
[ @job_type= ] 'job_type'
Type of job to modify. job_type is nvarchar(20) with a default of 'capture'. Valid inputs are 'capture' and 'cleanup'.
[ @maxtrans ] =max_trans
Maximum number of transactions to process in each scan cycle. max_trans is int with a default of NULL, which
indicates no change for this parameter. If specified, the value must be a positive integer.
max_trans is valid only for capture jobs.
[ @maxscans ] =max_scans
Maximum number of scan cycles to execute in order to extract all rows from the log. max_scans is int with a
default of NULL, which indicates no change for this parameter.
max_scan is valid only for capture jobs.
[ @continuous ] =continuous
Indicates whether the capture job is to run continuously (1), or run only once (0). continuous is bit with a default of
NULL, which indicates no change for this parameter.
When continuous = 1, the sp_cdc_scan job scans the log and processes up to (max_trans * max_scans)
transactions. It then waits the number of seconds specified in polling_interval before beginning the next log scan.
When continuous = 0, the sp_cdc_scan job executes up to max_scans scans of the log, processing up to max_trans
transactions during each scan, and then exits.
If @continuous is changed from 1 to 0, @pollinginterval is automatically set to 0. A value specified for
@pollinginterval other than 0 is ignored.
If @continuous is omitted or explicitly set to NULL and @pollinginterval is explicitly set to a value greater than
0, @continuous is automatically set to 1.
continuous is valid only for capture jobs.
[ @pollinginterval ] =polling_interval
Number of seconds between log scan cycles. polling_interval is bigint with a default of NULL, which indicates no
change for this parameter.
polling_interval is valid only for capture jobs when continuous is set to 1.
[ @retention ] =retention
Number of minutes that change rows are to be retained in change tables. retention is bigint with a default of
NULL, which indicates no change for this parameter. The maximum value is 52494800 (100 years). If specified, the
value must be a positive integer.
retention is valid only for cleanup jobs.
[ @threshold= ] 'delete threshold'
Maximum number of delete entries that can be deleted using a single statement on cleanup. delete threshold is
bigint with a default of NULL, which indicates no change for this parameter. delete threshold is valid only for
cleanup jobs.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
If a parameter is omitted, the associated value in the dbo.cdc_jobs table is not updated. A parameter set explicitly to
NULL is treated as though the parameter is omitted.
Specifying a parameter that is invalid for the job type will cause the statement to fail.
Changes to a job do not take effect until the job is stopped by using sp_cdc_stop_job and restarted by using
sp_cdc_start_job.

Permissions
Requires membership in the db_owner fixed database role.

Examples
A. Changing a capture job
The following example updates the @job_type , @maxscans , and @maxtrans parameters of a capture job in the
AdventureWorks2012 database. The other valid parameters for a capture job, @continuous and @pollinginterval ,
are omitted; their values are not modified.

USE AdventureWorks2012;
GO
EXECUTE sys.sp_cdc_change_job
@job_type = N'capture',
@maxscans = 1000,
@maxtrans = 15;
GO
B. Changing a cleanup job
The following example updates a cleanup job in the AdventureWorks2012 database. All valid parameters for this job
type, except @threshold, are specified. The value of @threshold is not modified.

USE AdventureWorks2012;
GO
EXECUTE sys.sp_cdc_change_job
@job_type = N'cleanup',
@retention = 2880;
GO

See Also
dbo.cdc_jobs (Transact-SQL)
sys.sp_cdc_enable_table (Transact-SQL)
sys.sp_cdc_add_job (Transact-SQL)
sys.sp_cdc_cleanup_change_table (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes rows from the change table in the current database based on the specified low_water_mark value. This
stored procedure is provided for users who want to directly manage the change table cleanup process. Caution
should be used, however, because the procedure affects all consumers of the data in the change table.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_cleanup_change_table
[ @capture_instance = ] 'capture_instance',
[ @low_water_mark = ] low_water_mark ,
[ @threshold = ]'delete threshold'

Arguments
[ @capture_instance = ] 'capture_instance'
Is the name of the capture instance associated with the change table. capture_instance is sysname, with no default,
and cannot be NULL.
capture_instance must name a capture instance that exists in the current database.
[ @low_water_mark = ] low_water_mark
Is a log sequence number (LSN) that is to be used as the new low watermark for the capture instance.
low_water_mark is binary(10), with no default.
If the value is nonnull, it must appear as the start_lsn value of a current entry in the cdc.lsn_time_mapping table. If
other entries in cdc.lsn_time_mapping share the same commit time as the entry identified by the new low
watermark, the smallest LSN associated with that group of entries is chosen as the low watermark.
If the value is explicitly set to NULL, the current low watermark for the capture instance is used to define the upper
bound for the cleanup operation.
[ @threshold= ] 'delete threshold'
Is the maximum number of delete entries that can be deleted by using a single statement on cleanup.
delete_threshold is bigint, with a default of 5000.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sys.sp_cdc_cleanup_change_table performs the following operations:
1. If the @low_water_mark parameter is not NULL, it sets the value of start_lsn for the capture instance to the
new low watermark.

NOTE
The new low watermark might not be the low watermark that is specified in the stored procedure call. If other entries
in the cdc.lsn_time_mapping table share the same commit time, the smallest start_lsn represented in the group of
entries is selected as the adjusted low watermark. If the @low_water_mark parameter is NULL or the current low
watermark is greater than the new lowwatermark, the start_lsn value for the capture instance is left unchanged.

2. Change table entries with __$start_lsn values less than the low watermark are then deleted. The delete
threshold is used to limit the number of rows deleted in a single transaction. A failure to successfully delete
entries is reported, but does not affect any change to the capture instance low watermark that might have
been made based on the call.
Use sys.sp_cdc_cleanup_change_table in the following circumstances:
The cleanup Agent job reports delete failures.
An administrator can run this stored procedure explicitly to retry a failed operation. To retry cleanup for a
given capture instance, execute sys.sp_cdc_cleanup_change_table, and specify NULL for the
@low_water_mark parameter.
The simple retention-based policy used by the cleanup Agent job is not adequate.
Because this stored procedure does cleanup for a single capture instance, it can be used to build a custom
cleanup strategy that tailors the rules for cleanup to the individual capture instance.

Permissions
Requires membership in the db_owner fixed database role.

See Also
cdc.fn_cdc_get_all_changes_<capture_instance> (Transact-SQL)
sys.fn_cdc_get_min_lsn (Transact-SQL)
sys.fn_cdc_increment_lsn (Transact-SQL)
sys.sp_cdc_disable_db (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Disables change data capture for the current database. Change data capture is not available in every edition of
Microsoft SQL Server. For a list of features that are supported by the editions of SQL Server, see Features
Supported by the Editions of SQL Server 2016.
Applies to: SQL Server ( SQL Server 2008 through current version).
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_disable_db

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sys.sp_cdc_disable_db disables change data capture for all tables in the database currently enabled. All system
objects related to change data capture, such as change tables, jobs, stored procedures and functions, are dropped.
The is_cdc_enabled column for the database entry in the sys.databases catalog view is set to 0.

NOTE
If there are many capture instances defined for the database at the time change data capture is disabled, a long running
transaction can cause the execution of sys.sp_cdc_disable_db to fail. This problem can be avoided by disabling the individual
capture instances by using sys.sp_cdc_disable_table before running sys.sp_cdc_disable_db.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example disables change data capture for the AdventureWorks2012 database.
USE AdventureWorks2012;
GO
EXECUTE sys.sp_cdc_disable_db;
GO

See Also
sys.sp_cdc_enable_db (Transact-SQL)
sys.sp_cdc_disable_table (Transact-SQL)
sys.sp_cdc_disable_table (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Disables change data capture for the specified source table and capture instance in the current database. Change
data capture is not available in every edition of Microsoft SQL Server. For a list of features that are supported by
the editions of SQL Server, see Features Supported by the Editions of SQL Server 2016.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_disable_table
[ @source_schema = ] 'source_schema' ,
[ @source_name = ] 'source_name'
[ , [ @capture_instance = ] 'capture_instance' | 'all' ]

Arguments
[ @source_schema= ] 'source_schema'
Is the name of the schema in which the source table is contained. source_schema is sysname, with no default, and
cannot be NULL.
source_schema must exist in the current database.
[ @source_name= ] 'source_name'
Is the name of the source table from which change data capture is to be disabled. source_name is sysname, with
no default, and cannot be NULL.
source_name must exist in the current database.
[ @capture_instance= ] 'capture_instance' | 'all'
Is the name of the capture instance to disable for the specified source table. capture_instance is sysname and
cannot be NULL.
When 'all' is specified, all capture instances defined for source_name are disabled.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sys.sp_cdc_disable_table drops the change data capture change table and system functions associated with the
specified source table and capture instance. It deletes any rows associated with the specified capture instance from
the change data capture system tables and sets the is_tracked_by_cdc column for the table entry in the sys.tables
catalog view to 0.

Permissions
Requires membership in the db_owner fixed database role.

Examples
The following example disables change data capture for the HumanResources.Employee table.

USE AdventureWorks2012;
GO
EXECUTE sys.sp_cdc_disable_table
@source_schema = N'HumanResources',
@source_name = N'Employee',
@capture_instance = N'HumanResources_Employee';

See Also
sys.sp_cdc_enable_table (Transact-SQL)
sys.sp_cdc_drop_job (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes a change data capture cleanup or capture job for the current database from msdb.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_drop_job [ [ @job_type = ] 'job_type' ]

Arguments
[ @job_type**=** ] 'job_type'
Type of job to remove. job_type is nvarchar(20) and cannot be NULL. Valid inputs are 'capture' and 'cleanup'.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Nones

Remarks
sp_cdc_drop_job is called internally by sys.sp_cdc_disable_db.

Permissions
Requires membership in the db_owner fixed database role.

Examples
The following example removes the cleanup job for the AdventureWorks2012 database.

USE AdventureWorks2012;
GO
EXEC sys.sp_cdc_drop_job @job_type = N'cleanup';

See Also
dbo.cdc_jobs (Transact-SQL)
sys.sp_cdc_disable_db (Transact-SQL)
sys.sp_cdc_add_job (Transact-SQL)
sys.sp_cdc_enable_db (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Enables change data capture for the current database. This procedure must be executed for a database before any
tables can be enabled for change data capture in that database. Change data capture records insert, update, and
delete activity applied to enabled tables, making the details of the changes available in an easily consumed
relational format. Column information that mirrors the column structure of a tracked source table is captured for
the modified rows, along with the metadata needed to apply the changes to a target environment.

IMPORTANT
Change data capture is not available in every edition of Microsoft SQL Server. For a list of features that are supported by the
editions of SQL Server, see Features Supported by the Editions of SQL Server 2016.

Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_enable_db

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Change data capture cannot be enabled on system databases or distribution databases.
sys.sp_cdc_enable_db creates the change data capture objects that have database wide scope, including meta data
tables and DDL triggers. It also creates the cdc schema and cdc database user and sets the is_cdc_enabled column
for the database entry in the sys.databases catalog view to 1.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example enables change data capture.
USE AdventureWorks2012;
GO
EXECUTE sys.sp_cdc_enable_db;
GO

See Also
sys.sp_cdc_disable_db (Transact-SQL)
sys.sp_cdc_enable_table (Transact-SQL)
11/27/2017 • 7 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Enables change data capture for the specified source table in the current database. When a table is enabled for
change data capture, a record of each data manipulation language (DML) operation applied to the table is written
to the transaction log. The change data capture process retrieves this information from the log and writes it to
change tables that are accessed by using a set of functions.
Change data capture is not available in every edition of Microsoft SQL Server. For a list of features that are
supported by the editions of SQL Server, see Features Supported by the Editions of SQL Server 2016.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_enable_table
[ @source_schema = ] 'source_schema',
[ @source_name = ] 'source_name' , [,[ @capture_instance = ] 'capture_instance' ]
[,[ @supports_net_changes = ] supports_net_changes ]
, [ @role_name = ] 'role_name'
[,[ @index_name = ] 'index_name' ]
[,[ @captured_column_list = ] 'captured_column_list' ]
[,[ @filegroup_name = ] 'filegroup_name' ]
[,[ @allow_partition_switch = ] 'allow_partition_switch' ]
[;]

Arguments
[ @source_schema = ] 'source_schema'
Is the name of the schema in which the source table belongs. source_schema is sysname, with no default, and
cannot be NULL.
[ @source_name = ] 'source_name'
Is the name of the source table on which to enable change data capture. source_name is sysname, with no default,
and cannot be NULL.
source_name must exist in the current database. Tables in the cdc schema cannot be enabled for change data
capture.
[ @role_name = ] 'role_name'
Is the name of the database role used to gate access to change data. role_name is sysname and must be specified.
If explicitly set to NULL, no gating role is used to limit access to the change data.
If the role currently exists, it is used. If the role does not exist, an attempt is made to create a database role with the
specified name. The role name is trimmed of white space at the right of the string before attempting to create the
role. If the caller is not authorized to create a role within the database, the stored procedure operation fails.
[ @capture_instance = ] 'capture_instance'
Is the name of the capture instance used to name instance-specific change data capture objects. capture_instance
is sysname and cannot be NULL.
If not specified, the name is derived from the source schema name plus the source table name in the format
schemaname_sourcename. capture_instance cannot exceed 100 characters and must be unique within the
database. Whether specified or derived, capture_instance is trimmed of any white space to the right of the string.
A source table can have a maximum of two capture instances. For more information see,
sys.sp_cdc_help_change_data_capture (Transact-SQL).
[ @supports_net_changes = ] supports_net_changes
Indicates whether support for querying for net changes is to be enabled for this capture instance.
supports_net_changes is bit with a default of 1 if the table has a primary key or the table has a unique index that
has been identified by using the @index_name parameter. Otherwise, the parameter defaults to 0.
If 0, only the support functions to query for all changes are generated.
If 1, the functions that are needed to query for net changes are also generated.
If supports_net_changes is set to 1, index_name must be specified, or the source table must have a defined primary
key.
[ @index_name = ] 'index_name'
The name of a unique index to use to uniquely identify rows in the source table. index_name is sysname and can
be NULL. If specified, index_name must be a valid unique index on the source table. If index_name is specified, the
identified index columns takes precedence over any defined primary key columns as the unique row identifier for
the table.
[ @captured_column_list = ] 'captured_column_list'
Identifies the source table columns that are to be included in the change table. captured_column_list is
nvarchar(max) and can be NULL. If NULL, all columns are included in the change table.
Column names must be valid columns in the source table. Columns defined in a primary key index, or columns
defined in an index referenced by index_name must be included.
captured_column_list is a comma-separated list of column names. Individual column names within the list can be
optionally quoted by using either double quotation marks ("") or square brackets ([]). If a column name contains
an embedded comma, the column name must be quoted.
captured_column_list cannot contain the following reserved column names: __$start_lsn, __$end_lsn, __$seqval,
__$operation, and __$update_mask.
[ @filegroup_name = ] 'filegroup_name'
Is the filegroup to be used for the change table created for the capture instance. filegroup_name is sysname and
can be NULL. If specified, filegroup_name must be defined for the current database. If NULL, the default filegroup
is used.
We recommend creating a separate filegroup for change data capture change tables.
[ @allow_partition_switch= ] 'allow_partition_switch'
Indicates whether the SWITCH PARTITION command of ALTER TABLE can be executed against a table that is
enabled for change data capture. allow_partition_switch is bit, with a default of 1.
For nonpartitioned tables, the switch setting is always 1, and the actual setting is ignored. If the switch is explicitly
set to 0 for a nonpartitioned table, warning 22857 is issued to indicate that the switch setting has been ignored. If
the switch is explicitly set to 0 for a partitioned table, the warning 22356 is issued to indicate that partition switch
operations on the source table will be disallowed. Finally, if the switch setting is either set explicitly to 1 or allowed
to default to 1 and the enabled table is partitioned, warning 22855 is issued to indicate that partition switches will
not be blocked. If any partition switches occur, change data capture will not track the changes resulting from the
switch. This will cause data inconsistencies when the change data is consumed.
IMPORTANT
SWITCH PARTITION is a metadata operation, but it causes data changes. The data changes that are associated with this
operation are not captured in the change data capture change tables. Consider a table that has three partitions, and
changes are made to this table. The capture process will track user insert, update, and delete operations that are executed
against the table. However, if a partition is switched out to another table (for example, to perform a bulk delete), the rows
that were moved as part of this operation will not be captured as deleted rows in the change table. Similarly, if a new
partition that has prepopulated rows is added to the table, these rows will not be reflected in the change table. This can
cause data inconsistency when the changes are consumed by an application and applied to a destination.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Before you can enable a table for change data capture, the database must be enabled. To determine whether the
database is enabled for change data capture, query the is_cdc_enabled column in the sys.databases catalog view.
To enable the database, use the sys.sp_cdc_enable_db stored procedure.
When change data capture is enabled for a table, a change table and one or two query functions are generated.
The change table serves as a repository for the source table changes extracted from the transaction log by the
capture process. The query functions are used to extract data from the change table. The names of these functions
are derived from the capture_instance parameter in the following ways:
All changes function: cdc.fn_cdc_get_all_changes_<capture_instance>
Net changes function: cdc.fn_cdc_get_net_changes_<capture_instance>
sys.sp_cdc_enable_table also creates the capture and cleanup jobs for the database if the source table is
the first table in the database to be enabled for change data capture and no transactional publications exist
for the database. It sets the is_tracked_by_cdc column in the sys.tables catalog view to 1.

NOTE
SQL Server Agent does not have to be running when change data capture is enabled for a table. However, the capture
process will not process the transaction log and write entries to the change table unless SQL Server Agent is running.

Permissions
Requires membership in the db_owner fixed database role.

Examples
A. Enabling change data capture by specifying only required parameters
The following example enables change data capture for the HumanResources.Employee table. Only the required
parameters are specified.
USE AdventureWorks2012;
GO
EXECUTE sys.sp_cdc_enable_table
@source_schema = N'HumanResources'
, @source_name = N'Employee'
, @role_name = N'cdc_Admin';
GO

B. Enabling change data capture by specifying additional optional parameters


The following example enables change data capture for the HumanResources.Department table. All parameters
except @allow_partition_switch are specified.

USE AdventureWorks2012;
GO
EXEC sys.sp_cdc_enable_table
@source_schema = N'HumanResources'
, @source_name = N'Department'
, @role_name = N'cdc_admin'
, @capture_instance = N'HR_Department'
, @supports_net_changes = 1
, @index_name = N'AK_Department_Name'
, @captured_column_list = N'DepartmentID, Name, GroupName'
, @filegroup_name = N'PRIMARY';
GO

See Also
sys.sp_cdc_disable_table (Transact-SQL)
sys.sp_cdc_help_change_data_capture (Transact-SQL)
cdc.fn_cdc_get_all_changes_<capture_instance> (Transact-SQL)
cdc.fn_cdc_get_net_changes_<capture_instance> (Transact-SQL)
sys.sp_cdc_help_jobs (Transact-SQL)
sys.sp_cdc_generate_wrapper_function (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Generates scripts to create wrapper functions for the change data capture query functions that are available in SQL
Server. The API that is supported in the generated wrappers enables the query interval to be specified as a datetime
interval. This makes the function good for use in many warehousing applications, including those that are
developed by Integration Services package designers who are using change data capture technology to determine
incremental load.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_generate_wrapper_function
[ [ @capture_instance sysname = ] 'capture_instance'
[ , [ @closed_high_end_point = ] closed_high_end_pt
[ , [ @column_list = ] 'column_list'

[ , [ @update_flag_list = ] 'update_flag_list'

Arguments
[ @capture_instance= ] 'capture_instance'
Is the capture instance that scripts are to be generated for. capture_instance is sysname and has a default value of
NULL. If a value is omitted or explicitly set to NULL, wrapper scripts are generated for all capture instances
[ @closed_high_end_point= ] high_end_pt_flag
Is the flag bit that indicates whether changes that have a commit time equal to the high endpoint are to be included
within the extraction interval by the generated procedure. high_end_pt_flag is bit and has a default value of 1,
which indicates that the endpoint should be included. A value of 0 indicates that all commit times will be strictly
less than the high endpoint.
[ @column_list= ] 'column_list'
Is a list of captured columns to be included in the result set that is returned by the wrapper function. column_list is
nvarchar(max) and has a default value of NULL. When NULL is specified, all captured columns are included.
[ @update_flag_list= ] 'update_flag_list'
Is a list of included columns for which an update flag is included in the result set that is returned by the wrapper
function. update_flag_list is nvarchar(max) and has a default value of NULL. When NULL is specified, no update
flags are included.

Return Code Values


0 (success) or 1 (failure)
Result Sets
COLUMN NAME COLUMN TYPE DESCRIPTION

function_name nvarchar(145) Name of the generated function.

create_script nvarchar(max) Is the script that creates the capture-


instance wrapper function.

Remarks
The script that creates the function to wrap the all-changes query for a capture instance is always generated. If the
capture instance supports net-changes queries, the script to generate a wrapper for this query is also generatedl.

Examples
The following example show how you can use sys.sp_cdc_generate_wrapper_function to create wrappers for all the
change data capture functions.

DECLARE @wrapper_functions TABLE (


function_name sysname,
create_script nvarchar(max));

INSERT INTO @wrapper_functions


EXEC sys.sp_cdc_generate_wrapper_function;

DECLARE @create_script nvarchar(max);


DECLARE #hfunctions CURSOR LOCAL fast_forward
FOR
SELECT create_script FROM @wrapper_functions;

OPEN #hfunctions;
FETCH #hfunctions INTO @create_script;
WHILE (@@fetch_status <> -1)
BEGIN
EXEC sp_executesql @create_script
FETCH #hfunctions INTO @create_script
END;

CLOSE #hfunctions;
DEALLOCATE #hfunctions;

See Also
Change Data Capture Stored Procedures (Transact-SQL)
Change Data Capture (SSIS)
sys.sp_cdc_get_captured_columns (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns change data capture metadata information for the captured source columns tracked by the specified
capture instance. Change data capture is not available in every edition of Microsoft SQL Server. For a list of features
that are supported by the editions of SQL Server, see Features Supported by the Editions of SQL Server 2016.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_get_captured_columns
[ @capture_instance = ] 'capture_instance'

Arguments
[ @capture_instance = ] 'capture_instance'
Is the name of the capture instance associated with a source table. capture_instance is sysname and cannot be
NULL.
To report on the capture instances for the table, run the sys.sp_cdc_help_change_data_capture stored procedure.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

source_schema sysname Name of the source table schema.

source_table sysname Name of the source table.

capture_instance sysname Name of the capture instance.

column_name sysname Name of the captured source column.

column_id int ID of the column in the source table.

ordinal_position int Position of the column within the


source table.

data_type sysname Column data type.


COLUMN NAME DATA TYPE DESCRIPTION

character_maximum_length int Maximum character length of the


character-based column; otherwise,
NULL.

numeric_precision tinyint Precision of the column if numeric-


based; otherwise, NULL.

numeric_precision_radix smallint Precision radix of the column if numeric-


based; otherwise, NULL.

numeric_scale int Scale of the column if numeric-based;


otherwise, NULL.

datetime_precision smallint Precision of the column if datetime-


based; otherwise, NULL.

Remarks
Use sys.sp_cdc_get_captured_columns to obtain column information about the captured columns returned by
querying the capture instance query functions cdc.fn_cdc_get_all_changes_<capture_instance> or
cdc.fn_cdc_get_net_changes_<capture_instance>. The column names, IDs, and position remain constant for the life
of the capture instance. Only the column data type changes when the data type of the underlying source column in
the tracked table changes. Columns that are added to or dropped from a source table have no impact on the
captured columns of existing capture instances.
Use sys.sp_cdc_get_ddl_history to obtain information about data definition language (DDL) statements applied to a
source table. Any DDL changes that modified the structure of a tracked source column is returned in the result set.

Permissions
Requires membership in the db_owner fixed database role. For all other users, requires SELECT permission on all
captured columns in the source table and, if a gating role for the capture instance was defined, membership in that
database role. When the caller does not have permission to view the source data, the function returns error 22981
(Object does not exist or access is denied.).

Examples
The following example returns information about the captured columns in the HumanResources_Employee capture
instance.

USE AdventureWorks2012;
GO
EXECUTE sys.sp_cdc_get_captured_columns
@capture_instance = N'HumanResources_Employee';
GO

See Also
sys.sp_cdc_help_change_data_capture (Transact-SQL)
sys.sp_cdc_get_ddl_history (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the data definition language (DDL) change history associated with the specified capture instance since
change data capture was enabled for that capture instance. Change data capture is not available in every edition of
Microsoft SQL Server. For a list of features that are supported by the editions of SQL Server, see Features
Supported by the Editions of SQL Server 2016.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_get_ddl_history [ @capture_instance = ] 'capture_instance'

Arguments
[ @capture_instance = ] 'capture_instance'
Is the name of the capture instance associated with a source table. capture_instance is sysname and cannot be
NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

source_schema sysname Name of the source table schema.

source_table sysname Name of the source table.

capture_instance sysname Name of the capture instance.

required_column_update bit Indicates the DDL change required a


column in the change table to be
altered to reflect a data type change
made to the source column.

ddl_command nvarchar(max) The DDL statement applied to the


source table.

ddl_lsn binary(10) Log sequence number (LSN) associated


with the DDL change.

ddl_time datetime Time associated with the DDL change.


Remarks
DDL modifications to the source table that change the source table column structure, such as adding or dropping a
column, or changing the data type of an existing column, are maintained in the cdc.ddl_history table. These
changes can be reported by using this stored procedure. Entries in cdc.ddl_history are made at the time the capture
process reads the DDL transaction in the log.

Permissions
Requires membership in the db_owner fixed database role to return rows for all capture instances in the database.
For all other users, requires SELECT permission on all captured columns in the source table and, if a gating role for
the capture instance was defined, membership in that database role.

Examples
The following example adds a column to the source table HumanResources.Employee and then runs the
sys.sp_cdc_get_ddl_history stored procedure to report the DDL changes that apply to the source table associated
with the capture instance HumanResources_Employee .

USE AdventureWorks2012;
GO
ALTER TABLE HumanResources.Employee
ADD Test_Column int NULL;
GO
-- Pause 10 seconds to allow the event to be logged.
WAITFOR DELAY '00:00:10';
GO
EXECUTE sys.sp_cdc_get_ddl_history
@capture_instance = 'HumanResources_Employee';
GO

See Also
sys.sp_cdc_help_change_data_capture (Transact-SQL)
sys.sp_cdc_help_change_data_capture (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the change data capture configuration for each table enabled for change data capture in the current
database. Up to two rows can be returned for each source table, one row for each capture instance. Change data
capture is not available in every edition of Microsoft SQL Server. For a list of features that are supported by the
editions of SQL Server, see Features Supported by the Editions of SQL Server 2016.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_help_change_data_capture
[ [ @source_schema = ] 'source_schema' ]
[, [ @source_name = ] 'source_name' ]

Arguments
[ @source_schema = ] 'source_schema'
Is the name of the schema in which the source table belongs. source_schema is sysname, with a default of NULL.
When source_schema is specified, source_name must also be specified.
If non-NULL, source_schema must exist in the current database.
If source_schema is non-NULL, source_name must also be non-NULL.
[ @source_name = ] 'source_name'
Is the name of the source table. source_name is sysname, with a default of NULL. When source_name is specified,
source_schema must also be specified.
If non-NULL, source_name must exist in the current database.
If source_name is non-NULL, source_schema must also be non-NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

source_schema sysname Name of the source table schema.

source_table sysname Name of the source table.

capture_instance sysname Name of the capture instance.


COLUMN NAME DATA TYPE DESCRIPTION

object_id int ID of the change table associated with


the source table.

source_object_id int ID of the source table.

start_lsn binary(10) Log sequence number (LSN)


representing the low endpoint for
querying the change table.

NULL = the low endpoint has not been


established.

end_lsn binary(10) LSN representing the high endpoint for


querying the change table. In SQL
Server 2012, this column is always
NULL.

supports_net_changes bit Net change support is enabled.

has_drop_pending bit Not used in SQL Server 2012.

role_name sysname Name of the database role used to


control access to the change data.

NULL = a role is not used.

index_name sysname Name of the index used to uniquely


identify rows in the source table.

filegroup_name sysname Name of the filegroup in which the


change table resides.

NULL = change table is in the default


filegroup of the database.

create_date datetime Date that the capture instance was


enabled.

index_column_list nvarchar(max) List of index columns used to uniquely


identify rows in the source table.

captured_column_list nvarchar(max) List of captured source columns.

Remarks
When both source_schema and source_name default to NULL, or are explicitly set the NULL, this stored procedure
returns information for all of the database capture instances that the caller has SELECT access to. When
source_schema and source_name are non-NULL, only information on the specific named enabled table is
returned.

Permissions
When source_schema and source_name are NULL, the caller's authorization determines which enabled tables are
included in the result set. Callers must have SELECT permission on all of the captured columns of the capture
instance and also membership in any defined gating roles for the table information to be included. Members of
the db_owner database role can view information about all defined capture instances. When information for a
specific enabled table is requested, the same SELECT and membership criteria are applied for the named table.

Examples
A. Returning change data capture configuration information for a specified table
The following example returns the change data capture configuration for the HumanResources.Employee table.

USE AdventureWorks2012;
GO
EXECUTE sys.sp_cdc_help_change_data_capture
@source_schema = N'HumanResources',
@source_name = N'Employee';
GO

B. Returning change data capture configuration information for all tables


The following example returns configuration information for all enabled tables in the database that contain
change data that the caller is authorized to access.

USE AdventureWorks2012;
GO
EXECUTE sys.sp_cdc_help_change_data_capture;
GO
sys.sp_cdc_help_jobs (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports information about all change data capture cleanup or capture jobs in the current database.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_help_jobs

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

job_id uniqueidentifier The ID of the job.

job_type nvarchar(20) The type of job.

maxtrans int The maximum number of transactions


to process in each scan cycle.

maxtrans is valid only for capture jobs.

maxscans int The maximum number of scan cycles to


execute in order to extract all rows from
the log.

maxscans is valid only for capture jobs.

continuous bit A flag indicating whether the capture


job is to run continuously (1), or run in
one-time mode (0). For more
information, see sys.sp_cdc_add_job
(Transact-SQL).

continuous is valid only for capture


jobs.

pollinginterval bigint The number of seconds between log


scan cycles.

pollinginterval is valid only for capture


jobs.
COLUMN NAME DATA TYPE DESCRIPTION

retention bigint The number of minutes that change


rows are to be retained in change
tables.

retention is valid only for cleanup jobs.

threshold bigint The maximum number of delete entries


that can be deleted using a single
statement on cleanup.

Permissions
Requires membership in the db_owner fixed database role.

Examples
The following example returns information about the defined capture and cleanup jobs for the
AdventureWorks2012 database.

USE AdventureWorks2012;
GO
EXEC sys.sp_cdc_help_jobs;
GO

See Also
dbo.cdc_jobs (Transact-SQL)
sys.sp_cdc_add_job (Transact-SQL)
sys.sp_cdc_scan (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Executes the change data capture log scan operation.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_scan [ [ @maxtrans = ] max_trans ]
[ , [ @maxscans = ] max_scans ]
[ , [ @continuous = ] continuous ]
[ , [ @pollinginterval = ] polling_interval ]

Arguments
[ @maxtrans= ] max_trans
Maximum number of transactions to process in each scan cycle. max_trans is int with a default of 500.
[ @maxscans= ] max_scans
Maximum number of scan cycles to execute in order to extract all rows from the log. max_scans is int with a
default of 10.
[ @continuous= ] continuous
Indicates whether the stored procedure should end after executing a single scan cycle (0) or run continuously,
pausing for the time specified by polling_interval before reexecuting the scan cycle (1). continuous is tinyint with
a default of 0.
[ @pollinginterval= ] polling_interval
Number of seconds between log scan cycles. polling_interval is bigint with a default of 0.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sys.sp_cdc_scan is called internally by sys.sp_MScdc_capture_job if the SQL Server Agent capture job is being used
by change data capture. The procedure cannot be executed explicitly when a change data capture log scan
operation is already active or when the database is enabled for transactional replication. This stored procedure
should be used by administrators who want to customize the behavior of the capture job that is automatically
configured.
Permissions
Requires membership in the db_owner fixed database role.

See Also
dbo.cdc_jobs (Transact-SQL)
sys.sp_cdc_start_job (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Starts a change data capture cleanup or capture job for the current database.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_start_job [ [ @job_type = ] 'job_type' ]

Arguments
[ [ @job_type= ] 'job_type' ]
Type of job to add. job_type is nvarchar(20) with a default of capture. Valid inputs are capture and cleanup.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sys.sp_cdc_start_job can be used by an administrator to explicitly start either the capture job or the cleanup job.

Permissions
Requires membership in the db_owner fixed database role.

Examples
A. Starting a capture job
The following example starts the capture job for the AdventureWorks2012 database. Specifying a value for job_type
is not required because the default job type is capture.

USE AdventureWorks2012;
GO
EXEC sys.sp_cdc_start_job;
GO

B. Starting a cleanup job


The following example starts a cleanup job for the AdventureWorks2012 database.
USE AdventureWorks2012;
GO
EXEC sys.sp_cdc_start_job @job_type = N'cleanup';

See Also
dbo.cdc_jobs (Transact-SQL)
sys.sp_cdc_stop_job (Transact-SQL)
sys.sp_cdc_stop_job (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Stops a change data capture cleanup or capture job for the current database.
Transact-SQL Syntax Conventions

Syntax
sys.sp_cdc_stop_job [ [ @job_type = ] 'job_type' ]

Arguments
[ [ @job_type= ] 'job_type' ]
Type of job to add. job_type is nvarchar(20) with a default of capture. Valid inputs are capture and cleanup.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sys.sp_cdc_stop_job can be used by an administrator to explicitly stop either the capture job or the cleanup job.

Permissions
Requires membership in the db_owner fixed database role.

Examples
The following example stops the cleanup job for the AdventureWorks2012 database.

USE AdventureWorks2012;
GO
EXEC sys.sp_cdc_stop_job @job_type = N'capture';
GO

See Also
dbo.cdc_jobs (Transact-SQL)
sys.sp_cdc_start_job (Transact-SQL)
Cursor Stored Procedures (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Microsoft SQL Server supports the following system stored procedures that implement cursor variable
functionality.

sp_cursor_list sp_cursorprepare

sp_cursor sp_cursorprepexec

sp_cursorclose sp_cursorunprepare

sp_cursorexecute sp_describe_cursor

sp_cursorfetch sp_describe_cursor_columns

sp_cursoropen sp_describe_cursor_tables

sp_cursoroption

See Also
System Stored Procedures (Transact-SQL)
sp_cursor_list (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports the attributes of server cursors currently open for the connection.
Transact-SQL Syntax Conventions

Syntax
sp_cursor_list [ @cursor_return = ] cursor_variable_name OUTPUT
, [ @cursor_scope = ] cursor_scope
[;]

Arguments
[ @cursor_return= ] cursor_variable_nameOUTPUT
Is the name of a declared cursor variable. cursor_variable_name is cursor, with no default. The cursor is a
scrollable, dynamic, read-only cursor.
[ @cursor_scope= ] cursor_scope
Specifies the level of cursors to report. cursor_scope is int, with no default, and can be one of these values.

VALUE DESCRIPTION

1 Report all local cursors.

2 Report all global cursors.

3 Report both local and global cursors.

Return Code Values


None

Cursors Returned
sp_cursor_list returns its report as a Transact-SQL cursor output parameter, not as a result set. This allows
Transact-SQL batches, stored procedures, and triggers to work with the output one row at a time. It also means the
procedure cannot be called directly from database API functions. The cursor output parameter must be bound to a
program variable, but the database APIs do not support binding cursor parameters or variables.
This is the format of the cursor returned by sp_cursor_list. The format of the cursor is the same as the format
returned by sp_describe_cursor.
COLUMN NAME DATA TYPE DESCRIPTION

reference_name sysname The name used to refer to the cursor. If


the reference to the cursor was through
the name given on a DECLARE CURSOR
statement, the reference name is the
same as cursor name. If the reference to
the cursor was through a variable, the
reference name is the name of the
cursor variable.

cursor_name sysname The name of the cursor from a


DECLARE CURSOR statement. In SQL
Server, if the cursor was created by
setting a cursor variable to a cursor,
cursor_name returns the name of the
cursor variable. In previous releases, this
output column returns a system-
generated name.

cursor_scope smallint 1 = LOCAL

2 = GLOBAL

status smallint The same values as reported by the


CURSOR_STATUS system function:

1 = The cursor referenced by the cursor


name or variable is open. If the cursor is
insensitive, static, or keyset, it has at
least one row. If the cursor is dynamic,
the result set has zero or more rows.

0 = The cursor referenced by the cursor


name or variable is open but has no
rows. Dynamic cursors never return this
value.

-1 = The cursor referenced by the


cursor name or variable is closed.

-2 = Applies only to cursor variables.


There is no cursor assigned to the
variable. Possibly, an OUTPUT
parameter assigned a cursor to the
variable, but the stored procedure
closed the cursor before returning.

-3 = A cursor or cursor variable with


the specified name does not exist, or
the cursor variable has not had a cursor
allocated to it.

model smallint 1 = Insensitive (or static)

2 = Keyset

3 = Dynamic

4 = Fast Forward
COLUMN NAME DATA TYPE DESCRIPTION

concurrency smallint 1 = Read-only

2 = Scroll locks

3 = Optimistic

scrollable smallint 0 = Forward-only

1 = Scrollable

open_status smallint 0 = Closed

1 = Open

cursor_rows int The number of qualifying rows in the


result set. For more information, see
@@CURSOR_ROWS.

fetch_status smallint The status of the last fetch on this


cursor. For more information, see
@@FETCH_STATUS:

0 = Fetch successful.

-1 = Fetch failed or is beyond the


bounds of the cursor.

-2 = The requested row is missing.

-9 = There has been no fetch on the


cursor.

column_count smallint The number of columns in the cursor


result set.

row_count smallint The number of rows affected by the last


operation on the cursor. For more
information, see @@ROWCOUNT.

last_operation smallint The last operation performed on the


cursor:

0 = No operations have been


performed on the cursor.

1 = OPEN

2 = FETCH

3 = INSERT

4 = UPDATE

5 = DELETE

6 = CLOSE

7 = DEALLOCATE
COLUMN NAME DATA TYPE DESCRIPTION

cursor_handle int A unique value that identifies the cursor


within the scope of the server.

Remarks
sp_cursor_list produces a list of the current server cursors opened by the connection and describes the attributes
global to each cursor, such as the scrollability and updatability of the cursor. The cursors listed by sp_cursor_list
include:
Transact-SQL server cursors.
API server cursors opened by an ODBC application that is then called SQLSetCursorName to name the
cursor.
Use sp_describe_cursor_columns for a description of the attributes of the result set returned by the cursor.
Use sp_describe_cursor_tables for a report of the base tables referenced by the cursor. sp_describe_cursor
reports the same information as sp_cursor_list, but only for a specified cursor.

Permissions
Execute permissions default to the public role.

Examples
The following example opens a global cursor and uses sp_cursor_list to report on the attributes of the cursor.
USE AdventureWorks2012;
GO
-- Declare and open a keyset-driven cursor.
DECLARE abc CURSOR KEYSET FOR
SELECT LastName
FROM Person.Person
WHERE LastName LIKE 'S%';
OPEN abc;

-- Declare a cursor variable to hold the cursor output variable


-- from sp_cursor_list.
DECLARE @Report CURSOR;

-- Execute sp_cursor_list into the cursor variable.


EXEC master.dbo.sp_cursor_list @cursor_return = @Report OUTPUT,
@cursor_scope = 2;

-- Fetch all the rows from the sp_cursor_list output cursor.


FETCH NEXT from @Report;
WHILE (@@FETCH_STATUS <> -1)
BEGIN
FETCH NEXT from @Report;
END

-- Close and deallocate the cursor from sp_cursor_list.


CLOSE @Report;
DEALLOCATE @Report;
GO

-- Close and deallocate the original cursor.


CLOSE abc;
DEALLOCATE abc;
GO

See Also
System Stored Procedures (Transact-SQL)
sp_cursor (Transact-SQL)
11/21/2017 • 7 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Requests positioned updates. This procedure performs operations on one or more rows within a cursor's fetch
buffer. sp_cursor is invoked by specifying ID = 1 in a tabular data stream (TDS) packet.
||
|-|
|Applies to: SQL Server ( SQL Server 2008 through current version).|
Transact-SQL Syntax Conventions

Syntax
sp_cursor cursor, optype, rownum, table
[ , value[...n]]]

Arguments
cursor
The cursor handle. cursor is a required parameter that calls for an int input value. cursor is the handle value
generated by SQL Server and returned by the sp_cursoropen procedure.
optype
Is a required parameter that designates what operation the cursor will perform. optype requires one of the
following int input values.

VALUE NAME DESCRIPTION

0X0001 UPDATE Is used to update one or more rows in


the fetch buffer. The rows specified in
rownum are re-accessed and updated.

0x0002 DELETE Is used to delete one or more rows in


the fetch buffer. The rows specified in
rownum are re-accessed and deleted.

0X0004 INSERT Inserts data without building an SQL


INSERT statement.

0X0008 REFRESH Is used to refill the buffer from


underlying tables and can be used to
refresh the row if an update or delete
fails due to optimistic concurrency
control, or after an UPDATE.
VALUE NAME DESCRIPTION

0X10 LOCK Causes a SQL Server U-Lock to be


acquired on the page containing the
specified row. This lock is compatible
with S-Locks but not with X-Locks or
other U-Locks. Can be used to
implement short-term locking.

0X20 SETPOSITION Is used only when the program is going


to issue a subsequent SQL Server
positioned DELETE or UPDATE
statement.

0X40 ABSOLUTE Can only be used in conjunction with


UPDATE or DELETE. ABSOLUTE is used
only with KEYSET cursors (is ignored for
DYNAMIC cursors and STATIC cursors
cannot be updated0.

Note: If ABSOLUTE is specified on a row


in the keyset that has not been fetched,
the operation may fail the concurrency
check and the return result cannot be
guaranteed.

rownum
Specifies which of the rows in the fetch buffer the cursor will operate on, update, or delete.

NOTE
This does not affect the starting point of any RELATIVE, NEXT, or PREVIOUS fetch operation, nor any updates or deletes
performed using sp_cursor.

rownum is a required parameter that calls for an int input value.


1
Signifies the first row in the fetch buffer.
2
Signifies second row in the fetch buffer.
3, 4, 5
Signifies the third row, and so forth.
n
Signifies the nth row in the fetch buffer.
0
Signifies all rows in the fetch buffer.

NOTE
Is only valid for use with UPDATE, DELETE, REFRESH, or LOCK optype values.

table
Table name that identifies the table that optype applies to when the cursor definition involves a join or ambiguous
column names are returned by the value parameter. If no specific table is designated, the default is the first table in
the FROM clause. table is an optional parameter that requires a String input value. The string can be specified as
any character or UNICODE data type. table can be a multi-part table name.
value
Used to insert or update values. The value string parameter is only used with UPDATE and INSERT optype values.
The string can be specified as any character or UNICODE data type.

NOTE
The parameter names for value can be assigned by the user.

Return Code Values


When using an RPC, a positioned DELETE or UPDATE operation with a buffer number 0 will return a DONE
message with a rowcount of 0 (failure) or 1 (success) for every row in the fetch buffer.

Remarks
optype Parameter
With the exception of the combinations of SETPOSITION with UPDATE, DELETE, REFRESH, or LOCK; or ABSOLUTE
with either UPDATE or DELETE, the optype values are mutually exclusive.
The SET clause of the UPDATE value is constructed from the value parameter.
One benefit of using the INSERT optype value is that you can avoid converting non-character data into character
format for inserts. The values are specified in the same way as UPDATE. If any required columns are not included,
the INSERT fails.
The SETPOSITION value does not affect the starting point of any RELATIVE, NEXT, or PREVIOUS fetch
operation, nor do any updates or deletes performed using the sp_cursor interface. Any number that does
not specify a row in the fetch buffer will result in the position being set to 1 with no error being returned.
Once SETPOSITION is executed, the position remains in effect until the next sp_cursorfetch operation, T-SQL
FETCH operation, or sp_cursor SETPOSITION operation through the same cursor. A subsequent
sp_cursorfetch operation will set the position of the cursor to the first row in the new fetch buffer while
other cursor calls will not affect the value of the position. SETPOSITION can be linked by an OR clause with
REFRESH, UPDATE, DELETE, or LOCK in order to set the value of the position to the last modified row.
If a row in the fetch buffer is not specified through the rownum parameter, the position will be set to 1, with
no error returned. Once the position is set, it remains in effect until the next sp_cursorfetch operation, T-SQL
FETCH operation, or sp_cursor SETPOSITION operation is performed on the same cursor.
SETPOSITION be linked by an OR clause with REFRESH, UPDATE, DELETE, or LOCK to set the cursor position
to the last modified row.

rownum Parameter
If specified, the rownum parameter can be interpreted as the row number within the keyset instead of the row
number within the fetch buffer. The user is responsible for ensuring that concurrency control is maintained. This
means that for SCROLL_LOCKS cursors, you must independently maintain a lock on the given row (this can be
done through a transaction). For OPTIMISTIC cursors, you must have previously fetched the row to perform this
operation.
table Parameter
If the optype value is UPDATE or INSERT and a full update or insert statement is submitted as the value parameter,
the value specified for table is ignored.

NOTE
Pertaining to views, only one table participating in the view may be modified. The value parameter column names must
reflect the column names in the view, but the table name can be that of the underlying base table (in which case sp_cursor
will substitute the view name).

value Parameter
There are two alternatives to the rules for using value as stated earlier in the Arguments section:
1. You can use a name that is '@' pre-pended to the name of the column in the select-list for any named value
parameters. One advantage of this alternative is that data conversion may not be necessary.
2. Use a parameter to either submit a complete UPDATE or INSERT statement or use multiple parameters to
submit portions of an UPDATE or INSERT statement which SQL Server will then build into a complete
statement. Examples of this can be found in the Examples section later in this topic.

Examples
Alternative value Parameter Uses
For UPDATE:
When a single parameter is used, an UPDATE statement may be submitted using the following syntax:
[ [ UPDATE <table name> ] SET ] {<column name> = expression} [,…n]

NOTE
If UPDATE <table name> is specified, any value specified for the table parameter will be ignored.

When multiple parameters are used, the first parameter must be a string in the following form:
[ SET ] <column name> = expression [,...n]

and the subsequent parameters must be in the form of:


<column name> = expression [,...n]

In this case, the <table name> in the constructed update statement is the one either specified or defaulted to by the
table parameter.
For INSERT:
When a single parameter is used, an INSERT statement may be submitted using the following syntax:
[ [ INSERT [INTO] <table name> ] VALUES ] ( <expression> [,...n] )

NOTE
If INSERT <table name> is specified, any value specified for the table parameter will be ignored.
When multiple parameters are used, the first parameter must be a string in the following form:
[ VALUES ( ] <expression> [,...n]

and the subsequent parameters must be in the form of:


expression [,...n]

except where VALUES was specified, in which case there must be a trailing ")" after the last expression. In this case,
the <table name> in the constructed UDPATE statement is the one either specified or defaulted to by the table
parameter.

NOTE
It is possible to submit one parameter as a named parameter, i.e. " @VALUES ". In this case no other named parameters may
be used.

See Also
sp_cursoropen (Transact-SQL)
sp_cursorfetch (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_cursorclose (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Closes and de-allocates the cursor, as well as releases all associated resources; that is, it drops the temporary table
used in support of KEYSET or STATIC cursor. sp_cursorclose is invoked by specifying ID = 9 in a tabular data
stream (TDS) packet.
Transact-SQL Syntax Conventions

Syntax
sp_cursorclose cursor

Arguments
cursor
Is a cursor handle value generated by SQL Server and returned by the sp_cursoropen procedure. cursor is a
required parameter that calls for an int input value.

NOTE
An input value of -1 will apply towards all cursors on the current connection.

Remarks
cursor will return error messages if the procedure was run after the cursor had been closed or if an invalid handle
is specified.
RPC status indicates overall success or failure.
DONE rowcount is always 0.

See Also
sp_cursoropen (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_cursorexecute (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates and populates a cursor based upon the execution plan created by sp_cursorprepare. This procedure,
coupled with sp_cursorprepare, has the same function as sp_cursoropen, but is split into two phases.
sp_cursorexecute is invoked by specifying ID =4 in a tabular data stream (TDS) packet.
Transact-SQL Syntax Conventions

Syntax
sp_cursorexecute prepared_handle, cursor
[ , scrollopt[ OUTPUT ]
[ , ccopt[ OUTPUT ]
[ ,rowcount OUTPUT [ ,bound param][,...n]]]]]

Arguments
prepared_handle
Is the prepared statement handle value returned by sp_cursorprepare. prepared_handle is a required parameter
that calls for an int input value.
cursor
Is the SQL Server-generated cursor identifier. cursor is a required parameter that must be supplied on all
subsequent procedures which act upon the cursor, such as sp_cursorfetch
scrollopt
Scroll option. scrollopt is an optional parameter that requires an int input value. The sp_cursorexecutescrollopt
parameter has the same value options as those for sp_cursoropen.

NOTE
The PARAMETERIZED_STMT value is not supported.

IMPORTANT
If a scrollopt value is not specified, the default value is KEYSET regardless of scrollopt value specified in sp_cursorprepare.

ccopt
Currency control option. ccopt is an optional parameter that requires an int input value. The sp_cursorexecuteccopt
parameter has the same value options as those for sp_cursoropen.

IMPORTANT
If a ccopt value is not specified, the default value is OPTIMISTIC regardless of ccopt value specified in sp_cursorprepare.
rowcount
Is an optional parameter that signifies the number of fetch buffer rows to use with AUTO_FETCH. The default is 20
rows. rowcount behaves differently when assigned as an input value versus a return value.

AS INPUT VALUE AS RETURN VALUE

When AUTO_FETCH is specified with FAST_FORWARD cursors Represents the number of rows in the result set. When the
rowcount represents the number of rows to place into the scrollopt AUTO_FETCH value is specified, rowcount returns
fetch buffer. the number of rows that were fetched into the fetch buffer.

bound_param
Signifies the optional use of additional parameters.

NOTE
Any parameters after the fifth are passed along to the statement plan as input parameters.

Code Return Value


rowcount may return the following values.

VALUE DESCRIPTION

-1 Number of rows unknown.

-n An asynchronous population is in effect.

Remarks
scrollopt and ccopt Parameters
scrollopt and ccopt are useful when the cached plans are preempted for the server cache, meaning that the
prepared handle identifying the statement must be recompiled. The scrollopt and ccopt parameter values must
match the values sent in the original request to sp_cursorprepare.

NOTE
PARAMETERIZED_STMT should not be assigned to scrollopt.

Failure to provide matching values will result in recompilation of the plans, negating the prepare and execute
operations.

RPC and TDS considerations


The RPC RETURN_METADATA input flag can be set to 1 to request that cursor select list metadata be returned in
the TDS stream.

See Also
sp_cursoropen (Transact-SQL)
sp_cursorfetch (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_cursorfetch (Transact-SQL)
11/27/2017 • 8 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Fetches a buffer of one or more rows from the database. The group of rows in this buffer is called the cursor's
fetch buffer. sp_cursorfetch is invoked by specifying ID = 7 in a tabular data stream (TDS) packet.
Transact-SQL Syntax Conventions

Syntax
sp_cursorfetch cursor
[ , fetchtype[ , rownum [ , nrows] ]]

Arguments
cursor
Is a handle value generated by SQL Server and returned by sp_cursoropen. cursor is a required parameter that
calls for an int input value. For more information, see the Remarks section later in this topic.
fetchtype
Specifies which cursor buffer to fetch. fetchtype is an optional parameter that requires one of the following integer
input values.

VALUE NAME DESCRIPTION

0x0001 FIRST Fetches the first buffer of nrows rows. If


nrows equals 0, the cursor is positioned
before the result set and no rows are
returned.

0x0002 NEXT Fetches the next buffer of nrows rows.

0x0004 PREV Fetches the previous buffer of nrows


rows.

Note: Using PREV for a


FORWARD_ONLY cursor returns an
error message because
FORWARD_ONLY only supports
scrolling in one direction.
VALUE NAME DESCRIPTION

0x0008 LAST Fetches the last buffer of nrows rows. If


nrows equals 0, the cursor is positioned
after the result set and no rows are
returned.

Note: Using LAST for a


FORWARD_ONLY cursor returns an
error message because
FORWARD_ONLY only supports
scrolling in one direction.

0x10 ABSOLUTE Fetches a buffer of nrows rows starting


with the rownum row.

Note: Using ABSOLUTE for either a


DYNAMIC cursor or a
FORWARD_ONLY cursor returns an
error message because
FORWARD_ONLY only supports
scrolling in one direction.

0x20 RELATIVE Fetches the buffer of nrows rows


starting with the row that is specified as
being the rownum value of rows from
the first row in the current block. In this
case rownum can be a negative
number.

Note: Using RELATIVE for a


FORWARD_ONLY cursor returns an
error message because
FORWARD_ONLY only supports
scrolling in one direction.

0x80 REFRESH Refills the buffer from underlying tables.

0x100 INFO Retrieves information about the cursor.


This information is returned by using
the rownum and nrows parameters.
Therefore, when INFO is specified,
rownum and nrows become output
parameters.

0x200 PREV_NOADJUST Is used like PREV. However, if the top of


the result set is encountered
prematurely, the results might vary.

0x400 SKIP_UPDT_CNCY Must be used with one of the other


fetchtype values, except for INFO.

NOTE
There is no support for the value 0x40.

For more information, see the Remarks section later in this topic.
rownum
Is an optional parameter that is used to specify the row position for the ABSOLUTE and INFO fetchtype values by
using only integer values for input or output, or both. rownum serves as the row offset for the fetchtype bit value
RELATIVE. rownum is ignored for all other values. For more information, see the Remarks section later in this
topic.
nrows
Is an optional parameter that is used to specify the number of rows to fetch. If nrows is not specified, the default
value is 20 rows. To set the position without returning data,specify a value of 0. When nrows is applied to the
fetchtype INFO query, it returns the total number of rows in that query.

NOTE
nrows is ignored by the REFRESH fetchtype bit value.
For more information, see the Remarks section later in this topic.

Return Code Values


When you specify the bit value INFO, the values that may be returned are shown in the following tables.

NOTE
: If no rows are returned, the buffer contents remain as they were.

<ROWNUM> SET TO

If not open 0

If positioned before the result set 0

If positioned after the result set -1

For KEYSET and STATIC cursors The absolute row number of the current position in the result
set

For DYNAMIC cursors 1

For ABSOLUTE -1 returns the last row in a set.

-2 returns the second to last row in a set, and so on.

Note: If more than one row is requested to be fetched in this


case, the last two rows of the result set are returned.

<NROWS> SET TO

If not open 0

For KEYSET and STATIC cursors Typically, the current keyset size.

–m if the cursor is in asynchronous creation with m rows


found to this point.

For DYNAMIC cursors -1


Remarks
cursor Parameter
Before there have been any fetch operations, the default position of a cursor is before the first row of the result set.

fetchtype Parameter
Except for SKIP_UPD_CNCY, the fetchtype values are mutually exclusive.
When SKIP_UPDT_CNCY is specified, the timestamp column values are not written to the keyset table when a row
is fetched or refreshed. If the keyset row is being updated, the values of the timestamp columns remain as the
previous value. If the keyset row is being inserted, the values for the timestamp columns are undefined.
For KEYSET cursors, this means that the keyset table has the values set during the last nonskip FETCH, if one was
performed. If not, it has the values set during population.
For DYNAMIC cursors, this means that if the skip is performed with a refresh, it produces the same results as
KEYSET. For any other fetch type, the keyset table is truncated. This means that the rows are being inserted and the
values for the timestamp column(s) are undefined. Therefore, when you run sp_cursorfetch for DYNAMIC cursors,
avoid using SKIP_UPDT_CNCY for any operation other than REFRESH.
If a fetch operation fails because the requested cursor position is beyond the result set, the cursor position is set
just after the last row. If a fetch operation fails because the requested cursor position is positioned before the
result set, the cursor position is set before the first row.

rownum Parameter
When you use rownum, the buffer is filled starting with the specified row.
The fetchtype value ABSOLUTE refers to the position of rownum within the whole result set. A negative number
with ABSOLUTE specifies that the operation counts rows from the end of the result set.
The fetchtype value RELATIVE refers to the position of rownum in relation to the position of the cursor at the start
of the current buffer. A negative number with RELATIVE specifies that the cursor go backward from the current
cursor position.

nrows Parameter
The fetchtype values REFRESH and INFO ignore this parameter.
When you specify a fetchtype value of FIRST that has an nrow value of 0, the cursor is positioned before the result
set that has no rows in the fetch buffer.
When you specify a fetchtype value of LAST that has an nrow value of 0, the cursor is positioned after the result
set that has no rows in the current fetch buffer.
For the fetchtype values of NEXT, PREV, ABSOLUTE, RELATIVE, and PREV_NOADJUST, an nrow value of 0 is not
valid.

RPC Considerations
The RPC return status indicates whether the keyset size parameter is final or not, that is if the keyset or temporary
table is being populated asynchronously.
The RPC status parameter is set to one of the values shown in the following table.
VALUE DESCRIPTION

0 Procedure executed successfully.

0x0001 Procedure failed.

0x0002 A fetch in a negative direction caused the cursor position to


be set to the beginning of the result set, when the fetch
would have logically been before the results.

0x10 A fast-forward cursor was automatically closed.

The rows are returned as a typical result set, that is: column format (0x2a), rows (0xd1), followed by done (0xfd).
Metadata tokens are sent in the same format as specified for sp_cursoropen, that is: 0x81, 0xa5 and 0xa4 for SQL
Server 7.0 users, and so on. The row status indicators are sent as hidden columns, similar to BROWSE mode, at the
end of each row with the column name rowstat and data type INT4. This rowstat column has one of the values
shown in the following table.

VALUE DESCRIPTION

0x0001 FETCH_SUCCEEDED

0x0002 FETCH_MISSING

Because the TDS protocol provides no way to send the trailing status column without sending the previous
columns, dummy data is sent for missing rows (nullable fields set to null, fixed length fields set to 0, blank, or the
default for that column, as appropriate).
The DONE rowcount will always be zero. The DONE message contains the actual result set rowcount, and error or
informational messages might appear between any TDS messages.
To request that metadata about the cursor's select list be returned in the TDS stream, set the RPC
RETURN_METADATA input flag to 1.

Examples
A. Using PREV to change a cursor position
Assume that a cursor h2 would produce a result set having the following contents with a current position as
shown:

row 1 contents
row 2 contents
row 3 contents
row 4 contents <-- current position
row 5 contents
row 6 contents

Next, an sp_cursorfetch PREV that has an nrows value of 5 would logically position the cursor two rows before the
first row of the result set. In these cases, the cursor is adjusted to start at the first row and return the number of
rows requested. This frequently means that it will return rows that were in the PRIOR fetch buffer.

NOTE
This is the exact case in which the RPC status parameter is set to 2.
B. Using PREV_NOADJUST to return fewer rows than PREV
PREV_NOADJUST never includes any of the rows at or after the current cursor position in the block of rows that it
returns. In cases where PREV returns rows after the current position, PREV_NOADJUST returns fewer rows than
requested in nrows. Given the current position in Example A earlier, when PREV is applied, sp_cursorfetch(h2, 4, 1,
5) fetches the following rows:

row1 contents
row2 contents
row3 contents
row4 contents
row5 contents

However, when PREV_NOADJUST is applied, sp_cursorfetch(h2, 512, 6, 5) fetches only the following rows:

row1 contents
row2 contents
row3 contents

See Also
sp_cursoropen (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_cursoropen (Transact-SQL)
11/30/2017 • 7 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Opens a cursor. sp_cursoropen defines the SQL statement associated with the cursor and cursor options, and
then populates the cursor. sp_cursoropen is equivalent to the combination of the Transact-SQL statements
DECLARE_CURSOR and OPEN. This procedure is invoked by specifying ID =2 in a tabular data stream (TDS)
packet.
Transact-SQL Syntax Conventions

Syntax
sp_cursoropen cursor OUTPUT, stmt
[, scrollopt[ OUTPUT ] [ , ccopt[ OUTPUT ]
[ ,rowcount OUTPUT [ ,boundparam][,...n]]] ]]

Arguments
cursor
A SQL Server-generated cursor identifier. cursor is a handle value that must be supplied on all subsequent
procedures involving the cursor, such as sp_cursorfetch. cursor is a required parameter with an int return value.
cursor allows multiple cursors to be active on a single database connection.
stmt
Is a required parameter that defines the cursor result set. Any valid query string (syntax and binding) of any string
type (regardless of Unicode, size, etc.) can serve as a valid stmt value type.
scrollopt
Scroll option. scrollopt is an optional parameter that requires one of the following int input values.

VALUE DESCRIPTION

0x0001 KEYSET

0x0002 DYNAMIC

0x0004 FORWARD_ONLY

0x0008 STATIC

0x10 FAST_FORWARD

0x1000 PARAMETERIZED_STMT

0x2000 AUTO_FETCH
VALUE DESCRIPTION

0x4000 AUTO_CLOSE

0x8000 CHECK_ACCEPTED_TYPES

0x10000 KEYSET_ACCEPTABLE

0x20000 DYNAMIC_ACCEPTABLE

0x40000 FORWARD_ONLY_ACCEPTABLE

0x80000 STATIC_ACCEPTABLE

0x100000 FAST_FORWARD_ACCEPTABLE

Because of the possibility that the requested value is not appropriate for the cursor defined by stmt, this
parameter serves as both input and output. In such cases, SQL Server assigns an appropriate value.
ccopt
Concurrency control option. ccopt is an optional parameter that requires one of the following int input values.

VALUE DESCRIPTION

0x0001 READ_ONLY

0x0002 SCROLL_LOCKS (previously known as LOCKCC)

0x0004 OPTIMISTIC (previously known as OPTCC)

0x0008 OPTIMISTIC (previously known as OPTCCVAL)

0x2000 ALLOW_DIRECT

0x4000 UPDT_IN_PLACE

0x8000 CHECK_ACCEPTED_OPTS

0x10000 READ_ONLY_ACCEPTABLE

0x20000 SCROLL_LOCKS_ACCEPTABLE

0x40000 OPTIMISTIC_ACCEPTABLE

0x80000 OPTIMISITC_ACCEPTABLE

As with scrollopt, SQL Server can override the requested ccopt values.
rowcount
The number of fetch buffer rows to use with AUTO_FETCH. The default is 20 rows. rowcount behaves differently
when assigned as an input value versus a return value.
AS INPUT VALUE AS RETURN VALUE

When the AUTO_FETCH scrollopt value is specified rowcount Represents the number of rows in the result set, except when
represents the number of rows to place into the fetch buffer. the scrollopt AUTO_FETCH value is specified.

Note: >0 is a valid value when AUTO_FETCH is specified, but


is otherwise ignored.

boundparam
Signifies the use of additional parameters. boundparam is an optional parameter that should be specified
if the scrollopt PARAMETERIZED_STMT value is set to ON.

Return Code Values


If no error is raised, sp_cursoropen returns one of the following values.
0
The procedure executed successfully.
0x0001
An error occurred during the execution (a minor error, not severe enough to raise an error in the operation).
0x0002
An asynchronous operation is in progress.
0x0002
A FETCH operation is in process.
A
This cursor has been deallocated by SQL Server and is unavailable.
When an error is raised, the return values may be inconsistent and the accuracy cannot be guaranteed.
When the rowcount parameter is specified as a return value, the following result set occurs.
-1
Returned if the number of rows is unknown or not applicable.
-n
Returned when an asynchronous population is in effect. Represents the number of rows that were placed into the
fetch buffer when the scrollopt AUTO_FETCH value is specified.
If RPC is in use, the return values are as follows.
0
Procedure is successful.
1
Procedure failed.
2
A keyset cursor is being asynchronously generated.
16
A fast-forward cursor has been automatically closed.
NOTE
If the sp_cursoropen procedure executes successfully, the RPC return parameters and a result set with TDS column format
information (0xa0 & 0xa1 messages) are sent. If unsuccessful, one or more TDS error messages are sent. In either case, no
row data will be returned and the done message count will be zero. If you are using a version of SQL Server earlier than 7.0,
0xa0, 0xa1 (standard for SELECT statements) are returned along with 0xa5 and 0xa4 token streams. If you are using SQL
Server 7.0, 0x81 is returned (standard for SELECT statements) along with the 0xa5 and 0xa4 token streams.

Remarks
stmt Parameter
If stmt specifies the execution of a stored procedure, the input parameters may either be defined as constants as
part of the stmt string, or specified as boundparam arguments. Declared variables can be passed as bound
parameters in this way.
The allowed contents of the stmt parameter depend upon whether or not the ccopt ALLOW_DIRECT return value
has been linked by OR to the rest of the ccopt values, i.e.:
If ALLOW_DIRECT is not specified, either a Transact-SQL SELECT or EXECUTE statement calling for a stored
procedure containing a single SELECT statement must be used. Furthermore, the SELECT statement must
qualify as a cursor; that is, it cannot contain the keywords SELECT INTO or FOR BROWSE.
If ALLOW_DIRECT is specified, this may result in one or more Transact-SQL statements, including those
that, in turn, execute other stored procedures with multiple statements. Non-SELECT statements or any
SELECT statement that contains the keywords SELECT INTO or FOR BROWSE will simply be executed and
will not result in the creation of a cursor. The same is true for any SELECT statement included in a batch of
multiple statements. In cases where a SELECT statement contains clauses that pertain only to cursors, those
clauses are ignored. For instance, when the value of ccopt is 0x2002, this is a request for:
A cursor with scroll locks, if there is only a single SELECT statement that qualifies as a cursor, or
A direct statement execution if there are multiple statements, a single non-SELECT statement, or a
SELECT statement that does not qualify as a cursor.

scrollopt Parameter
The first five scrollopt values (KEYSEY, DYNAMIC, FORWARD_ONLY, STATIC, and FAST_FORWARD) are mutually
exclusive.
PARAMETERIZED_STMT and CHECK_ACCEPTED_TYPES can be linked by OR to any of the first five values.
AUTO_FETCH and AUTO_CLOSE can be linked by OR to FAST_FORWARD.
If CHECK_ACCEPTED_TYPES is ON, at least one of the last five scrollopt values (KEYSET_ACCEPTABLE ,
DYNAMIC_ACCEPTABLE, FORWARD_ONLY_ACCEPTABLE, STATIC_ACCEPTABLE, or
FAST_FORWARD_ACCEPTABLE) must also be ON.
STATIC cursors are always opened as READ_ONLY. This means that the underlying table cannot be updated
through this cursor.

ccopt Parameter
The first four ccopt values (READ_ONLY, SCROLL_LOCKS, and both OPTIMISTIC values) are mutually exclusive.
NOTE
Choosing one of the first four ccopt values dictates whether the cursor is read-only, or if locking or optimistic methods are
used to prevent lost updates. If a ccopt value is not specified, the default value is OPTIMISTIC.

ALLOW_DIRECT and CHECK_ACCEPTED_TYPES can be linked by OR to any of the first four values.
UPDT_IN_PLACE can be linked by OR to READ_ONLY, SCROLL_LOCKS, or either of the OPTIMISTIC values.
If CHECK_ACCEPTED_TYPES is ON, at least one of the last four ccopt values (READ_ONLY_ACCEPTABLE,
SCROLL_LOCKS_ACCEPTABLE, and either of the OPTIMISTIC_ACCEPTABLE values) must also be ON.
Positioned UPDATE and DELETE functions may be performed only within the fetch buffer and only if the ccopt
value equals SCROLL_LOCKS or OPTIMISTIC. If SCROLL_LOCKS is the specified value, the operation is guaranteed
to succeed. If OPTIMISTIC is the specified value, the operation will fail if the row has changed since it was last
fetched.
The reason for this failure is that when OPTIMISTIC is the specified value, an optimistic currency control function
is performed by comparing timestamps or checksum values, as determined by SQL Server. If any of these rows
do not match, the operation will fail.
Specifying UPDT_IN_PLACE as the return value governs the following results:
If not set when performing a positioned update on a table with a unique index, the cursor deletes the row
from its work table and inserts it at the end of any of the key columns used by the cursor, thereby
changing those columns.
If set ON, the cursor will simply update the key columns in the work table's original row.

bound_param Parameter
The parameter name should be paramdef when PARAMETERIZED_STMT is specified, according to the error
message in the code. When PARAMETERIZED_STMT is not specified, no name is specified in the error message.

RPC Considerations
The RPC RETURN_METADATA input flag can be set to 0x0001 to request that cursor select list metadata be
returned in the TDS stream.

Examples
bound_param Parameter
Any parameters after the fifth are passed along to the statement plan as input parameters. The first such
parameter must be a string in the form of:
{ local variable name data type } [,…n]
Subsequent parameters are used to pass the values to be substituted for the local variable name in the
statement.

See Also
sp_cursorfetch (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_cursoroption (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Sets cursor options or returns cursor information created by the sp_cursoropen stored procedure. sp_cursoroption
is invoked by specifying ID =8 in a tabular data stream (TDS) packet.
Transact-SQL Syntax Conventions

Syntax
sp_cursoroption cursor, code, value

Arguments
cursor
Is a handle value that is generated by SQL Server and returned by the sp_cursoropen stored procedure. cursor
requires an int input value for execution.
code
Used to stipulate various factors of the cursor return values. code requires one of the following int input values:

VALUE NAME DESCRIPTION

0x0001 TEXTPTR_ONLY Returns the text pointer, and not the


actual data, for certain designated text
or image columns.

TEXTPTR_ONLY allows text pointers to


be used as handles to blob objects
which can later be selectively retrieved
or updated using Transact-SQL or
DBLIB facilities (e.g. Transact-SQL
READTEXT or DBLIB DBWRITETEXT).

If a "0" value is assigned, all of the text


and image columns in the select list will
return text pointers rather than data.
VALUE NAME DESCRIPTION

0x0002 CURSOR_NAME Assigns the name specified in value to


the cursor. This, in turn, allows ODBC to
use Transact-SQL positioned
UPDATE/DELETE statements on cursors
opened via sp_cursoropen.

The string can be specified as any


character or Unicode data type.

Since Transact-SQL positioned


UPDATE/DELETE statements operate, by
default, on the first row in a fat cursor,
sp_cursor SETPOSITION should be used
to position the cursor before issuing the
positioned UPDATE/DELETE statement.

0x0003 TEXTDATA Returns the actual data, not the text


pointer, for certain text or image
columns on subsequent fetches (i.e. this
undoes the effect of TEXTPTR_ONLY).

If TEXTDATA is enabled for a particular


column the row is re-fetched or
refreshed, and can then be set back to
TEXTPTR_ONLY. As with
TEXTPTR_ONLY, the value parameter is
an integer that specifies the column
number and a zero value returns all text
or image columns.

0x0004 SCROLLOPT Scroll option. See "Returned Code


Values" later in this topic for additional
information.

0x0005 CCOPT Concurrency control option. See


"Returned Code Values" later in this
topic for additional information.

0x0006 ROWCOUNT The number of rows currently in the


result set.

Note: The ROWCOUNT may have


changed since the value returned by
sp_cursoropen if asynchronous
population is being used. The value –1
is returned if the number of rows is
unknown.

value
Designates the value returned by code. value is a required parameter that calls for a 0x0001, 0x0002, or 0x0003
code input value.

NOTE
A code value of 2 is a string data type. Any other code value input or returned by value is an integer.

Return Code Values


The value parameter may return one of the following code values.

RETURN VALUE DESCRIPTION

0x0004 SCROLLOPT

0X0005 CCOPT

0X0006 ROWCOUNT

The value parameter returns one of the following SCROLLOPT values.

RETURN VALUE DESCRIPTION

0x0001 KEYSET

0x0002 DYNAMIC

0x0004 FORWARD_ONLY

0x0008 STATIC

The value parameter returns one of the following CCOPT values.

RETURN VALUE DESCRIPTION

0x0001 READ_ONLY

0x0002 SCROLL_LOCKS

0x0004 or 0x0008 OPTIMISTIC

See Also
System Stored Procedures (Transact-SQL)
sp_cursor (Transact-SQL)
sp_cursoropen (Transact-SQL)
sp_cursorprepare (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Compiles the cursor statement or batch into an execution plan, but does not create the cursor. The compiled
statement can later be used by sp_cursorexecute. This procedure, coupled with sp_cursorexecute, has the same
function as sp_cursoropen, but is split into two phases. sp_cursorprepare is invoked by specifying ID = 3 in a
tabular data stream (TDS) packet.
Transact-SQL Syntax Conventions

Syntax
sp_cursorprepare prepared_handle OUTPUT, params , stmt , options
[ , scrollopt[ , ccopt]]

Arguments
prepared_handle
A SQL Server-generated prepared handle identifier that returns an integer value.

NOTE
prepared_handle is subsequently supplied to a sp_cursorexecute procedure in order to open a cursor. Once a handle is
created, it exists until you log off or until you explicitly remove it through a sp_cursorunprepare procedure.

params
Identifies parameterized statements. The params definition of variables is substituted for parameter markers in the
statement. params is a required parameter that calls for an ntext, nchar, or nvarchar input value. Input a NULL
value if the statement is not parameterized.

NOTE
Use an ntext string as the input value when stmt is parameterized and the scrollopt PARAMETERIZED_STMT value is ON.

stmt
Defines the cursor result set. The stmt parameter is required and calls for an ntext, nchar or nvarchar input value.

NOTE
The rules for specifying the stmt value are the same as those for sp_cursoropen, with the exception that the stmt string data
type must be ntext.

options
An optional parameter that returns a description of the cursor result set columns. options requires the following
int input value.
VALUE DESCRIPTION

0x0001 RETURN_METADATA

scrollopt
Scroll Option. scrollopt is an optional parameter that requires one of the following int input values.

VALUE DESCRIPTION

0x0001 KEYSET

0x0002 DYNAMIC

0x0004 FORWARD_ONLY

0x0008 STATIC

0x10 FAST_FORWARD

0x1000 PARAMETERIZED_STMT

0x2000 AUTO_FETCH

0x4000 AUTO_CLOSE

0x8000 CHECK_ACCEPTED_TYPES

0x10000 KEYSET_ACCEPTABLE

0x20000 DYNAMIC_ACCEPTABLE

0x40000 FORWARD_ONLY_ACCEPTABLE

0x80000 STATIC_ACCEPTABLE

0x100000 FAST_FORWARD_ACCEPTABLE

Because the requested value might not be appropriate for the cursor defined by stmt, this parameter serves as
both input and output. In such cases, SQL Server assigns an appropriate value.
ccopt
Concurrency control option. ccopt is an optional parameter that requires one of the following int input values.

VALUE DESCRIPTION

0x0001 READ_ONLY

0x0002 SCROLL_LOCKS (previously known as LOCKCC)

0x0004 OPTIMISTIC (previously known as OPTCC)

0x0008 OPTIMISTIC (previously known as OPTCCVAL)


VALUE DESCRIPTION

0x2000 ALLOW_DIRECT

0x4000 UPDT_IN_PLACE

0x8000 CHECK_ACCEPTED_OPTS

0x10000 READ_ONLY_ACCEPTABLE

0x20000 SCROLL_LOCKS_ACCEPTABLE

0x40000 OPTIMISTIC_ACCEPTABLE

0x80000 OPTIMISITC_ACCEPTABLE

As with scrollpt, SQL Server can assign a different value from the one requested.

Remarks
The RPC status parameter is one of the following:

VALUE DESCRIPTION

0 Success

0x0001 Failure

1FF6 Could not return metadata.

Note: The reason for this is that the statement does not
produce a result set; for example, it is an INSERT or DDL
statement.

Examples
When stmt is parameterized and the scrollopt PARAMETERIZED_STMT value is ON, the format of the string is as
follows:
{ <local variable name><data type> } [ ,…n ]

See Also
sp_cursorexecute (Transact-SQL)
sp_cursoropen (Transact-SQL)
sp_cursorunprepare (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_cursorprepexec (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Compiles a plan for the submitted cursor statement or batch, then creates and populates the cursor.
sp_cursorprepexec combines the functions of sp_cursorprepare and sp_cursorexecute. This procedures is invoked
by specifying ID = 5 in a tabular data stream (TDS) packet.
Transact-SQL Syntax Conventions

Syntax
sp_cursorprepexec prepared handle OUTPUT, cursor OUTPUT, params , statement , options
[ , scrollopt [ , ccopt [ , rowcount ] ] ]

Arguments
prepared handle
Is a SQL Server generated prepared handle identifier. prepared handle is required and returns int.
cursor
Is the SQL Server generated cursor identifier. cursor is a required parameter that must be supplied on all
subsequent procedures which act upon this cursor, e.g. sp_cursorfetch.
params
Identifies parameterized statements. The params definition of variables is substituted for parameter markers in the
statement. params is a required parameter that calls for an ntext, nchar, or nvarchar input value.

NOTE
Use an ntext string as the input value when stmt is parameterized and the scrollopt PARAMETERIZED_STMT value is ON.

statement
Defines the cursor result set. The statement parameter is required and calls for an ntext, nchar or nvarchar input
value.

NOTE
The rules for specifying the stmt value are the same as those for sp_cursoropen, with the exception that the stmt string data
type must be ntext.

options
An optional parameter that returns a description of the cursor result set columns. options requires the following int
input value.
VALUE DESCRIPTION

0x0001 RETURN_METADATA

scrollopt
Scroll Option. scrollopt is an optional parameter that requires one of the following int input values.

VALUE DESCRIPTION

0x0001 KEYSET

0x0002 DYNAMIC

0x0004 FORWARD_ONLY

0x0008 STATIC

0x10 FAST_FORWARD

0x1000 PARAMETERIZED_STMT

0x2000 AUTO_FETCH

0x4000 AUTO_CLOSE

0x8000 CHECK_ACCEPTED_TYPES

0x10000 KEYSET_ACCEPTABLE

0x20000 DYNAMIC_ACCEPTABLE

0x40000 FORWARD_ONLY_ACCEPTABLE

0x80000 STATIC_ACCEPTABLE

0x100000 FAST_FORWARD_ACCEPTABLE

Because of the possibility that the requested option is not appropriate for the cursor defined by <stmt>, this
parameter serves as both input and output. In such cases, SQL Server assigns an appropriate type and modifies this
value.
ccopt
Concurrency control option. ccopt is an optional parameter that requires one of the following int input values.

VALUE DESCRIPTION

0x0001 READ_ONLY

0x0002 SCROLL_LOCKS (previously known as LOCKCC)

0x0004 OPTIMISTIC (previously known as OPTCC)

0x0008 OPTIMISTIC (previously known as OPTCCVAL)


VALUE DESCRIPTION

0x2000 ALLOW_DIRECT

0x4000 UPDT_IN_PLACE

0x8000 CHECK_ACCEPTED_OPTS

0x10000 READ_ONLY_ACCEPTABLE

0x20000 SCROLL_LOCKS_ACCEPTABLE

0x40000 OPTIMISTIC_ACCEPTABLE

0x80000 OPTIMISITC_ACCEPTABLE

As with scrollpt, SQL Server can assign a different value than the one requested.
rowcount
Is an optional parameter that signifies the number of fetch buffer rows to use with AUTO_FETCH. The default is 20
rows. rowcount behaves differently when assigned as an input value versus a return value.

AS INPUT VALUE AS RETURN VALUE

When AUTO_FETCH is specified with FAST_FORWARD cursors Represents the number of rows in the result set. When the
rowcount represents the number of rows to place into the scrollopt AUTO_FETCH value is specified, rowcount returns
fetch buffer. the number of rows that were fetched into the fetch buffer.

Return Code Values


If params returns a NULL value then the statement is not parameterized.

See Also
sp_cursoropen (Transact-SQL)
sp_cursorexecute (Transact-SQL)
sp_cursorprepare (Transact-SQL)
sp_cursorfetch (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_cursorunprepare (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Discards the execution plan developed in the sp_cursorprepare stored procedure. sp_cursorunprepare is invoked
by specifying ID = 6 in a tabular data stream (TDS) packet.
Transact-SQL Syntax Conventions

Syntax
sp_cursorunprepare handle

Arguments
handle
Is the handle value that is returned by sp_cursorprepare when the statement is prepared.

See Also
sp_cursorprepare (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_describe_cursor (Transact-SQL)
11/27/2017 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports the attributes of a server cursor.
Transact-SQL Syntax Conventions

Syntax
sp_describe_cursor [ @cursor_return = ] output_cursor_variable OUTPUT
{ [ , [ @cursor_source = ] N'local'
, [ @cursor_identity = ] N'local_cursor_name' ]
| [ , [ @cursor_source = ] N'global'
, [ @cursor_identity = ] N'global_cursor_name' ]
| [ , [ @cursor_source = ] N'variable'
, [ @cursor_identity = ] N'input_cursor_variable' ]
}
[;]

Arguments
[ @cursor_return= ] output_cursor_variable OUTPUT
Is the name of a declared cursor variable to receive the cursor output. output_cursor_variable is cursor, with no
default, and must not be associated with any cursors at the time sp_describe_cursor is called. The cursor returned
is a scrollable, dynamic, read-only cursor.
[ @cursor_source= ] { N'local' | N'global' | N'variable' }
Specifies whether the cursor being reported on is specified by using the name of a local cursor, a global cursor, or
a cursor variable. The parameter is nvarchar(30).
[ @cursor_identity= ] N'local_cursor_name' ]
Is the name of a cursor created by a DECLARE CURSOR statement that either has the LOCAL keyword or that
defaulted to LOCAL. local_cursor_name is nvarchar(128).
[ @cursor_identity= ] N'global_cursor_name' ]
Is the name of a cursor created by a DECLARE CURSOR statement that either has the GLOBAL keyword or that
defaulted to GLOBAL. global_cursor_name is nvarchar(128).
global_cursor_name can also be the name of an API server cursor that is opened by an ODBC application that then
named by calling SQLSetCursorName.
[ @cursor_identity= ] N'input_cursor_variable' ]
Is the name of a cursor variable associated with an open cursor. input_cursor_variable is nvarchar(128).

Return Code Values


None

Cursors Returned
sp_describe_cursor encapsulates its result set in a Transact-SQL cursor output parameter. This enables Transact-
SQL batches, stored procedures, and triggers to work with the output one row at a time. This also means that the
procedure cannot be called directly from database API functions. The cursor output parameter must be bound to a
program variable, but the database APIs do not support binding cursor parameters or variables.
The following table shows the format of the cursor that is returned by using sp_describe_cursor. The format of the
cursor is the same as the format returned by using sp_cursor_list.

COLUMN NAME DATA TYPE DESCRIPTION

reference_name sysname Name used to refer to the cursor. If the


reference to the cursor was through the
name specified on a DECLARE CURSOR
statement, the reference name is the
same as cursor name. If the reference to
the cursor was through a variable, the
reference name is the name of the
variable.

cursor_name sysname Name of the cursor from a DECLARE


CURSOR statement. In SQL Server, if
the cursor was created by setting a
cursor variable to a cursor, cursor_name
returns the name of the cursor variable.
In earlier versions of SQL Server, this
output column returns a system-
generated name.

cursor_scope tinyint 1 = LOCAL

2 = GLOBAL

status int Same values as reported by the


CURSOR_STATUS system function:

1 = The cursor referenced by the cursor


name or variable is open. If the cursor is
insensitive, static, or keyset, it has at
least one row. If the cursor is dynamic,
the result set has zero or more rows.

0 = The cursor referenced by the cursor


name or variable is open but has no
rows. Dynamic cursors never return this
value.

-1 = The cursor referenced by the


cursor name or variable is closed.

-2 = Applies only to cursor variables.


There is no cursor assigned to the
variable. Possibly, an OUTPUT
parameter assigned a cursor to the
variable, but the stored procedure
closed the cursor before returning.

-3 = A cursor or cursor variable with


the specified name does not exist, or
the cursor variable has not had a cursor
allocated to it.
COLUMN NAME DATA TYPE DESCRIPTION

model tinyint 1 = Insensitive (or static)

2 = Keyset

3 = Dynamic

4 = Fast Forward

concurrency tinyint 1 = Read-only

2 = Scroll locks

3 = Optimistic

scrollable tinyint 0 = Forward-only

1 = Scrollable

open_status tinyint 0 = Closed

1 = Open

cursor_rows decimal(10,0) Number of qualifying rows in the result


set. For more information, see
@@CURSOR_ROWS (Transact-SQL).

fetch_status smallint Status of the last fetch on this cursor.


For more information, see
@@FETCH_STATUS (Transact-SQL).

0 = Fetch successful.

-1 = Fetch failed or is beyond the


bounds of the cursor.

-2 = The requested row is missing.

-9 = There has been no fetch on the


cursor.

column_count smallint Number of columns in the cursor result


set.

row_count decimal(10,0) Number of rows affected by the last


operation on the cursor. For more
information, see @@ROWCOUNT
(Transact-SQL).
COLUMN NAME DATA TYPE DESCRIPTION

last_operation tinyint Last operation performed on the cursor:

0 = No operations have been


performed on the cursor.

1 = OPEN

2 = FETCH

3 = INSERT

4 = UPDATE

5 = DELETE

6 = CLOSE

7 = DEALLOCATE

cursor_handle int A unique value for the cursor within the


scope of the server.

Remarks
sp_describe_cursor describes the attributes that are global to a server cursor, such as the ability to scroll and
update. Use sp_describe_cursor_columns for a description of the attributes of the result set returned by the cursor.
Use sp_describe_cursor_tables for a report of the base tables referenced by the cursor. To obtain a report of the
Transact-SQL server cursors visible on the connection, use sp_cursor_list.
A DECLARE CURSOR statement may request a cursor type that SQL Server cannot support using the SELECT
statement that is contained in the DECLARE CURSOR. SQL Server implicitly converts the cursor to a type it can
support using the SELECT statement. If TYPE_WARNING is specified in the DECLARE CURSOR statement, SQL
Server sends the application an informational message that a conversion has been completed. sp_describe_cursor
can then be called to determine the type of cursor that has been implemented.

Permissions
Requires membership in the public role.

Examples
The following example opens a global cursor and uses sp_describe_cursor to report on the attributes of the
cursor.
USE AdventureWorks2012;
GO
-- Declare and open a global cursor.
DECLARE abc CURSOR STATIC FOR
SELECT LastName
FROM Person.Person;

OPEN abc;

-- Declare a cursor variable to hold the cursor output variable


-- from sp_describe_cursor.
DECLARE @Report CURSOR;

-- Execute sp_describe_cursor into the cursor variable.


EXEC master.dbo.sp_describe_cursor @cursor_return = @Report OUTPUT,
@cursor_source = N'global', @cursor_identity = N'abc';

-- Fetch all the rows from the sp_describe_cursor output cursor.


FETCH NEXT from @Report;
WHILE (@@FETCH_STATUS <> -1)
BEGIN
FETCH NEXT from @Report;
END

-- Close and deallocate the cursor from sp_describe_cursor.


CLOSE @Report;
DEALLOCATE @Report;
GO

-- Close and deallocate the original cursor.


CLOSE abc;
DEALLOCATE abc;
GO

See Also
Cursors
CURSOR_STATUS (Transact-SQL)
DECLARE CURSOR (Transact-SQL)
sp_cursor_list (Transact-SQL)
sp_describe_cursor_columns (Transact-SQL)
sp_describe_cursor_tables (Transact-SQL)
sp_describe_cursor_columns (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports the attributes of the columns in the result set of a server cursor.
Transact-SQL Syntax Conventions

Syntax
sp_describe_cursor_columns
[ @cursor_return = ] output_cursor_variable OUTPUT
{ [ , [ @cursor_source = ] N'local' ,
[ @cursor_identity = ] N'local_cursor_name' ]
| [ , [ @cursor_source = ] N'global' ,
[ @cursor_identity = ] N'global_cursor_name' ]
| [ , [ @cursor_source = ] N'variable' ,
[ @cursor_identity = ] N'input_cursor_variable' ]
}

Arguments
[ @cursor_return= ] output_cursor_variable OUTPUT
Is the name of a declared cursor variable to receive the cursor output. output_cursor_variable is cursor, with no
default, and must not be associated with any cursors at the time sp_describe_cursor_columns is called. The cursor
returned is a scrollable, dynamic, read-only cursor.
[ @cursor_source= ] { N'local' | N'global' | N'variable' }
Specifies whether the cursor being reported on is specified by using the name of a local cursor, a global cursor, or
a cursor variable. The parameter is nvarchar(30).
[ @cursor_identity= ] N'local_cursor_name'
Is the name of a cursor created by a DECLARE CURSOR statement that either has the LOCAL keyword or that
defaulted to LOCAL. local_cursor_name is nvarchar(128).
[ @cursor_identity= ] N'global_cursor_name'
Is the name of a cursor created by a DECLARE CURSOR statement that either has the GLOBAL keyword or that
defaulted to GLOBAL. global_cursor_name is nvarchar(128).
global_cursor_name can also be the name of an API server cursor that is opened by an ODBC application and then
named by calling SQLSetCursorName.
[ @cursor_identity= ] N'input_cursor_variable'
Is the name of a cursor variable associated with an open cursor. input_cursor_variable is nvarchar(128).

Return Code Values


None

Cursors Returned
sp_describe_cursor_columns encapsulates its report as a Transact-SQL cursor output parameter. This enables
Transact-SQL batches, stored procedures, and triggers to work with the output one row at a time. This also means
that the procedure cannot be called directly from database API functions. The cursor output parameter must be
bound to a program variable, but the database APIs do not support binding cursor parameters or variables.
The following table shows the format of the cursor returned by using sp_describe_cursor_columns.

COLUMN NAME DATA TYPE DESCRIPTION

column_name sysname (nullable) Name assigned to the result set


column. The column is NULL if the
column was specified without an
accompanying AS clause.

ordinal_position int Relative position of the column from


the leftmost column in the result set.
The first column is in position 0.

column_characteristics_flags int A bitmask that indicates the


information stored in
DBCOLUMNFLAGS in OLE DB. Can be
one or a combination of the following:

1 = Bookmark

2 = Fixed length

4 = Nullable

8 = Row versioning

16 = Updatable column (set for


projected columns of a cursor that has
no FOR UPDATE clause and, if there is
such a column, can be only one per
cursor).

When bit values are combined, the


characteristics of the combined bit
values apply. For example, if the bit
value is 6, the column is a fixed-length
(2), nullable (4) column.

column_size int Maximum possible size for a value in


this column.

data_type_sql smallint Number that indicates the SQL Server


data type of the column.

column_precision tinyint Maximum precision of the column as


per the bPrecision value in OLE DB.

column_scale tinyint Number of digits to the right of the


decimal point for the numeric or
decimal data types as per the bScale
value in OLE DB.
COLUMN NAME DATA TYPE DESCRIPTION

order_position int If the column participates in the


ordering of the result set, the position
of the column in the order key relative
to the leftmost column.

order_direction varchar(1)(nullable) A = The column is in the order key and


the ordering is ascending.

D = The column is in the order key and


the ordering is descending.

NULL = The column does not


participate in ordering.

hidden_column smallint 0 = this column appears in the select


list.

1 = Reserved for future use.

columnid int Column ID of the base column. If the


result set column was built from an
expression, columnid is -1.

objectid int Object ID of the object or base table


that is supplying the column. If the
result set column was built from an
expression, objectid is -1.

dbid int ID of the database that contains the


base table that is supplying the column.
If the result set column was built from
an expression, dbid is -1.

dbname sysname Name of the database that contains the


base table that is supplying the column.
(nullable) If the result set column was built from
an expression, dbname is NULL.

Remarks
sp_describe_cursor_columns describes the attributes of the columns in the result set of a server cursor, such as the
name and data type of each cursor. Use sp_describe_cursor for a description of the global attributes of the server
cursor. Use sp_describe_cursor_tables for a report of the base tables referenced by the cursor. To obtain a report of
the Transact-SQL server cursors visible on the connection, use sp_cursor_list.

Permissions
Requires membership in the public role.

Examples
The following example opens a global cursor and uses sp_describe_cursor_columns to report on the columns used
in the cursor.
USE AdventureWorks2012;
GO
-- Declare and open a global cursor.
DECLARE abc CURSOR KEYSET FOR
SELECT LastName
FROM Person.Person;
GO
OPEN abc;

-- Declare a cursor variable to hold the cursor output variable


-- from sp_describe_cursor_columns.
DECLARE @Report CURSOR;

-- Execute sp_describe_cursor_columns into the cursor variable.


EXEC master.dbo.sp_describe_cursor_columns
@cursor_return = @Report OUTPUT
,@cursor_source = N'global'
,@cursor_identity = N'abc';

-- Fetch all the rows from the sp_describe_cursor_columns output cursor.


FETCH NEXT from @Report;
WHILE (@@FETCH_STATUS <> -1)
BEGIN
FETCH NEXT from @Report;
END

-- Close and deallocate the cursor from sp_describe_cursor_columns.


CLOSE @Report;
DEALLOCATE @Report;
GO
-- Close and deallocate the original cursor.
CLOSE abc;
DEALLOCATE abc;
GO

See Also
Cursors
CURSOR_STATUS (Transact-SQL)
DECLARE CURSOR (Transact-SQL)
sp_describe_cursor (Transact-SQL)
sp_cursor_list (Transact-SQL)
sp_describe_cursor_tables (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_describe_cursor_tables (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports the objects or base tables referenced by a server cursor.
Transact-SQL Syntax Conventions

Syntax
sp_describe_cursor_tables
[ @cursor_return = ] output_cursor_variable OUTPUT
{ [ , [ @cursor_source = ] N'local'
, [ @cursor_identity = ] N'local_cursor_name' ]
| [ , [ @cursor_source = ] N'global'
, [ @cursor_identity = ] N'global_cursor_name' ]
| [ , [ @cursor_source = ] N'variable'
, [ @cursor_identity = ] N'input_cursor_variable' ]
}
[;]

Arguments
[ @cursor_return= ] output_cursor_variableOUTPUT
Is the name of a declared cursor variable to receive the cursor output. output_cursor_variable is cursor, with no
default, and must not be associated with any cursors at the time sp_describe_cursor_tables is called. The cursor
returned is a scrollable, dynamic, read-only cursor.
[ @cursor_source= ] { N'local' | N'global' | N'variable' }
Specifies whether the cursor being reported on is specified by using the name of a local cursor, a global cursor, or
a cursor variable. The parameter is nvarchar(30).
[ @cursor_identity= ] N'local_cursor_name'
Is the name of a cursor created by a DECLARE CURSOR statement either having the LOCAL keyword, or that
defaulted to LOCAL. local_cursor_name is nvarchar(128).
[ @cursor_identity= ] N'global_cursor_name'
Is the name of a cursor created by a DECLARE CURSOR statement either having the GLOBAL keyword, or that
defaulted to GLOBAL. global_cursor_name can also be the name of an API server cursor opened by an ODBC
application that then named the cursor by calling SQLSetCursorName.global_cursor_name is nvarchar(128).
[ @cursor_identity= ] N'input_cursor_variable'
Is the name of a cursor variable associated with an open cursor. input_cursor_variable is nvarchar(128).

Return Code Values


None

Cursors Returned
sp_describe_cursor_tables encapsulates its report as a Transact-SQL cursor output parameter. This enables
Transact-SQL batches, stored procedures, and triggers to work with the output one row at a time. This also means
that the procedure cannot be called directly from API functions. The cursor output parameter must be bound to a
program variable, but the APIs do not support bind cursor parameters or variables.
The following table shows the format of the cursor that is returned by sp_describe_cursor_tables.

COLUMN NAME DATA TYPE DESCRIPTION

table owner sysname User ID of the table owner.

Table_name sysname Name of the object or base table. In


SQL Server, server cursors always
return the user-specified object, not the
base tables.

Optimizer_hints smallint Bitmap that is made up of one or more


of the following:

1 = Row-level locking (ROWLOCK)

4 = Page-level locking (PAGELOCK)

8 = Table lock (TABLOCK)

16 = Exclusive table lock (TABLOCKX)

32 = Update lock (UPDLOCK)

64 = No lock (NOLOCK)

128 = Fast first-row option (FASTFIRST)

4096 = Read repeatable semantic when


used with DECLARE CURSOR
(HOLDLOCK)

When multiple options are supplied, the


system uses the most restrictive.
However, sp_describe_cursor_tables
shows the flags that are specified in the
query.

lock_type smallint Scroll-lock type requested either


explicitly or implicitly for each base table
that underlies this cursor. The value can
be one of the following:

0 = None

1 = Shared

3 = Update

server_name sysname, nullable Name of the linked server that the table
resides on. NULL when OPENQUERY or
OPENROWSET are used.
COLUMN NAME DATA TYPE DESCRIPTION

Objectid int Object ID of the table. 0 when


OPENQUERY or OPENROWSET are
used.

dbid int ID of the database that the table


resides in. 0 when OPENQUERY or
OPENROWSET are used.

dbname sysname, nullable Name of the database that the table


resides in. NULL when OPENQUERY or
OPENROWSET are used.

Remarks
sp_describe_cursor_tables describes the base tables that are referenced by a server cursor. For a description of the
attributes of the result set returned by the cursor, use sp_describe_cursor_columns. For a description of the global
characteristics of the cursor, such as its scrollability and updatability, use sp_describe_cursor. To obtain a report of
the Transact-SQL server cursors that are visible on the connection, use sp_cursor_list.

Permissions
Requires membership in the public role.

Examples
The following example opens a global cursor and uses sp_describe_cursor_tables to report on the tables that are
referenced by the cursor.
USE AdventureWorks2012;
GO
-- Declare and open a global cursor.
DECLARE abc CURSOR KEYSET FOR
SELECT LastName
FROM Person.Person
WHERE LastName LIKE 'S%';

OPEN abc;
GO
-- Declare a cursor variable to hold the cursor output variable
-- from sp_describe_cursor_tables.
DECLARE @Report CURSOR;

-- Execute sp_describe_cursor_tables into the cursor variable.


EXEC master.dbo.sp_describe_cursor_tables
@cursor_return = @Report OUTPUT,
@cursor_source = N'global', @cursor_identity = N'abc';

-- Fetch all the rows from the sp_describe_cursor_tables output cursor.


FETCH NEXT from @Report;
WHILE (@@FETCH_STATUS <> -1)
BEGIN
FETCH NEXT from @Report;
END

-- Close and deallocate the cursor from sp_describe_cursor_tables.


CLOSE @Report;
DEALLOCATE @Report;
GO

-- Close and deallocate the original cursor.


CLOSE abc;
DEALLOCATE abc;
GO

See Also
Cursors
CURSOR_STATUS (Transact-SQL)
DECLARE CURSOR (Transact-SQL)
sp_cursor_list (Transact-SQL)
sp_describe_cursor (Transact-SQL)
sp_describe_cursor_columns (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_execute (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Executes a prepared Transact-SQL statement using a specified handle and optional parameter value. sp_execute is
invoked by specifying ID =12 in a tabular data stream (TDS) packet.
Transact-SQL Syntax Conventions

Syntax
-- Syntax for SQL Server, Azure SQL Data Warehouse, Parallel Data Warehouse

sp_execute handle OUTPUT


[,bound_param ] [,...n ] ]

Arguments
handle
Is the handle value returned by sp_prepare. handle is a required parameter that calls for int input value.
bound_param
Signifies the use of additional parameters. bound_param is a required parameter that calls for input values of any
data type to signify additional parameters for the procedure.

NOTE
bound_param must match the declarations made by the sp_prepareparams value and can be in the form @name = value or
value.

See Also
System Stored Procedures (Transact-SQL)
sp_prepare (Transact SQL)
sp_prepare (Transact SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Prepares a parameterized Transact-SQL statement and returns a statement handle for execution. sp_prepare is
invoked by specifying ID = 11 in a tabular data stream (TDS) packet.
Transact-SQL Syntax Conventions

Syntax
-- Syntax for SQL Server, Azure SQL Data Warehouse, Parallel Data Warehouse

sp_prepare handle OUTPUT, params, stmt, options

Arguments
handle
Is a SQL Server-generated prepared handle identifier. handle is a required parameter with an int return value.
params
Identifies parameterized statements. The params definition of variables is substituted for parameter markers in the
statement. params is a required parameter that calls for an ntext, nchar, or nvarchar input value. Input a NULL
value if the statement is not parameterized.
stmt
Defines the cursor result set. The stmt parameter is required and calls for an ntext, nchar, or nvarchar input
value.
options
An optional parameter that returns a description of the cursor result set columns. options requires the following
int input value.

VALUE DESCRIPTION

0x0001 RETURN_METADATA

Examples
The following example prepares and executes a simple statement.

Declare @P1 int;


Exec sp_prepare @P1 output,
N'@P1 nvarchar(128), @P2 nvarchar(100)',
N'SELECT database_id, name FROM sys.databases WHERE name=@P1 AND state_desc = @P2';
Exec sp_execute @P1, N'tempdb', N'ONLINE';
EXEC sp_unprepare @P1;
Examples: Azure SQL Data Warehouse and Parallel Data Warehouse
The following example prepares and executes a simple statement.

Declare @P1 int;


Exec sp_prepare @P1 output,
N'@P1 nvarchar(128), @P2 nvarchar(100)',
N'SELECT database_id, name FROM sys.databases WHERE name=@P1 AND state_desc = @P2';
Exec sp_execute @P1, N'tempdb', N'ONLINE';
EXEC sp_unprepare @P1;

See Also
System Stored Procedures (Transact-SQL)
sp_prepexec (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Prepares and executes a parameterized Transact-SQL statement. sp_prepexec combines the functions of sp_prepare
and sp_execute. This is invoked by ID =13 in a tabular data stream (TDS) packet.
Transact-SQL Syntax Conventions

Syntax
sp_prepexec handle OUTPUT, params , stmt
[ , bound param ] [ ,...n]]

Arguments
handle
Is the SQL Server-generated handle identifier. handle is a required parameter with an int return value.
params
Identifies parameterized statements. The params definition of variables is substituted for parameter markers in the
statement. params is a required parameter that calls for an ntext, nchar, or nvarchar input value. Input a NULL
value if the statement is not parameterized.
stmt
Defines the cursor result set. The stmt parameter is required and calls for an ntext, nchar or nvarchar input value.
bound_param
Signifies the optional use of additional parameters. bound_param calls for an input value of any data type to
designate the additional parameters in use.

Examples
The following example prepares and executes a simple statement.

Declare @P1 int;


EXEC sp_prepexec @P1 output,
N'@P1 nvarchar(128), @P2 nvarchar(100)',
N'SELECT database_id, name
FROM sys.databases
WHERE name=@P1 AND state_desc = @P2',
@P1 = 'tempdb', @P2 = 'ONLINE';
EXEC sp_unprepare @P1;

See Also
sp_prepare (Transact SQL)
sp_execute (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_prepexecrpc (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Prepares and executes a parameterized stored procedure call that has been specified using an RPC identifier.
sp_prepexecrpc is invoked by ID = 14 in a tabular data stream (TDS) packet.
Transact-SQL Syntax Conventions

Syntax
sp_prepexecrpc handle OUTPUT, RPCCall
[ , bound_param ] [ ,...n]]

Arguments
handle
Is the SQL Server-generated prepared handle identifier. handle is a required parameter with an int return value.
RPCCall
Defines the stored procedure call using ODBC canonical syntax. RPCCall is a required parameter that calls for an
ntext string input value.
bound_param
Signifies the optional use of additional parameters. bound_param calls for an input value of any data type to
designate the additional parameters in use.

See Also
System Stored Procedures (Transact-SQL)
sp_unprepare (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Discards the execution plan created by the sp_prepare stored procedure. sp_unprepare is invoked by specifying ID
= 15 in a tabular data stream (TDS) packet.

Syntax
-- Syntax for SQL Server, Azure SQL Data Warehouse, Parallel Data Warehouse

sp_unprepare handle

Arguments
handle
Is the handle value returned by sp_prepare.

Examples
The following example prepares, executes, and unprepares a simple statement.

Declare @P1 int;


Exec sp_prepare @P1 output,
N'@P1 nvarchar(128), @P2 nvarchar(100)',
N'SELECT database_id, name FROM sys.databases WHERE name=@P1 AND state_desc = @P2';
Exec sp_execute @P1, N'tempdb', N'ONLINE';
EXEC sp_unprepare @P1;

Examples: Azure SQL Data Warehouse and Parallel Data Warehouse


The following example prepares, executes, and unprepares a simple statement.

Declare @P1 int;


Exec sp_prepare @P1 output,
N'@P1 nvarchar(128), @P2 nvarchar(100)',
N'SELECT database_id, name FROM sys.databases WHERE name=@P1 AND state_desc = @P2';
Exec sp_execute @P1, N'tempdb', N'ONLINE';
EXEC sp_unprepare @P1;

See Also
sp_prepare (Transact SQL)
Data Collector Stored Procedures (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
SQL Server supports the following system stored procedures that are used to work with the data collector and the
following components: collection sets, collection items, and collection types.

IMPORTANT
Unlike regular stored procedures, the parameters for data collector stored procedures are strictly typed and do not support
automatic data type conversion. If these parameters are not called with the correct input parameter data types, as specified
in the argument description, the stored procedure returns an error.

sp_syscollector_create_collection_item sp_syscollector_set_cache_window

sp_syscollector_create_collection_set sp_syscollector_set_warehouse_database_name

sp_syscollector_create_collector_type sp_syscollector_set_warehouse_instance_name

sp_syscollector_delete_collection_item sp_syscollector_start_collection_set

sp_syscollector_delete_collection_set sp_syscollector_stop_collection_set

sp_syscollector_delete_collector_type sp_syscollector_run_collection_set

sp_syscollector_delete_execution_log_tree sp_syscollector_update_collection_item

sp_syscollector_disable_collector sp_syscollector_update_collection_set

sp_syscollector_enable_collector sp_syscollector_update_collector_type

sp_syscollector_set_cache_directory sp_syscollector_upload_collection_set

The following stored procedures are for internal use only:


sp_syscollector_get_warehouse_connection_string
sp_syscollector_set_warehouse_connection_password
sp_syscollector_set_warehouse_connection_user
sp_syscollector_event_oncollectionbegin
sp_syscollector_event_oncollectionend
sp_syscollector_event_onpackagebegin
sp_syscollector_event_onpackageend
sp_syscollector_event_onpackageupdate
sp_syscollector_event_onerror
sp_syscollector_event_onstatsupdate

See Also
System Stored Procedures (Transact-SQL)
sp_syscollector_create_collection_item (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a collection item in a user-defined collection set. A collection item defines the data to be collected and the
frequency with which the data is collected.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_create_collection_item
[ @collection_set_id = ] collection_set_id
, [ @collector_type_uid = ] 'collector_type_uid'
, [ @name = ] 'name'
, [ [ @frequency = ] frequency ]
, [ @parameters = ] 'parameters'
, [ @collection_item_id = ] collection_item_id OUTPUT

Arguments
[ @collection_set_id = ] collection_set_id
Is the unique local identifier for the collection set. collection_set_id is int.
[ @collector_type_uid = ] 'collector_type_uid'
Is the GUID that identifies the collector type to use for this item collector_type_uid is uniqueidentifier with no
default value.. For a list of collector types, query the syscollector_collector_types system view.
[ @name = ] 'name'
Is the name of the collection item. name is sysname and cannot be an empty string or NULL.
name must be unique. For a list of current collection item names, query the syscollector_collection_items system
view.
[ @frequency = ] frequency
Is used to specify (in seconds) how frequently data is collected by this collection item. frequency is int, with a
default of 5. The minimum value that can be specified is 5 seconds.
If the collection set is set to non-cached mode, the frequency is ignored because this mode causes both data
collection and upload to occur at the schedule specified for the collection set. To view the collection mode of the
collection set, query the syscollector_collection_sets system view.
[ @parameters = ] 'parameters'
The input parameters for the collector type. parameters is xml with a default of NULL. The parameters schema
must match the parameters schema of the collector type.
[ @collection_item_id = ] collection_item_id
Is the unique identifer that identifies the collection set item. collection_item_id is int and has OUTPUT.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_syscollector_create_collection_item must be run in the context of the msdb system database.
The collection set to which the collection item is being added must be stopped before creating the collection item.
Collection items cannot be added to system collection sets.

Permissions
Requires membership in the dc_admin (with EXECUTE permission) fixed database role to execute this procedure.

Examples
The following example creates a collection item based on the collection type Generic T-SQL Query Collector Type
and adds it to the collection set named Simple collection set test 2 . To create the specified collection set, run
example B in sp_syscollector_create_collection_set (Transact-SQL).

USE msdb;
GO
DECLARE @collection_item_id int;
DECLARE @collection_set_id int = (SELECT collection_set_id
FROM syscollector_collection_sets
WHERE name = N'Simple collection set test 2');
DECLARE @collector_type_uid uniqueidentifier =
(SELECT collector_type_uid
FROM syscollector_collector_types
WHERE name = N'Generic T-SQL Query Collector Type');
DECLARE @params xml =
CONVERT(xml, N'\<ns:TSQLQueryCollector xmlns:ns="DataCollectorType">
<Query>
<Value>SELECT * FROM sys.objects</Value>
<OutputTable>MyOutputTable</OutputTable>
</Query>
<Databases>
<Database> UseSystemDatabases = "true"
UseUserDatabases = "true"
</Database>
</Databases>
\</ns:TSQLQueryCollector>');

EXEC sp_syscollector_create_collection_item
@collection_set_id = @collection_set_id,
@collector_type_uid = @collector_type_uid,
@name = 'My custom TSQL query collector item',
@frequency = 6000,
@parameters = @params,
@collection_item_id = @collection_item_id OUTPUT;

See Also
System Stored Procedures (Transact-SQL)
Data Collection
sp_syscollector_update_collection_item (Transact-SQL)
sp_syscollector_delete_collection_item (Transact-SQL)
syscollector_collector_types (Transact-SQL)
sp_syscollector_create_collection_set (Transact-SQL)
syscollector_collection_items (Transact-SQL)
sp_syscollector_create_collection_set (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a new collection set. You can use this stored procedure to create a custom collection set for data collection.

WARNING
In cases where the Windows account configured as a proxy is a non-interactive or interactive user that has not yet logged
in, the profile directory will not exist, and the creation of the staging directory will fail. Therefore, if you are using a proxy
account on a domain controller, you must specify an interactive account that has been used at least once in order to assure
that the profile directory has been created.

Transact-SQL Syntax Conventions

Syntax
sp_syscollector_create_collection_set
[ @name = ] 'name'
, [ [ @target = ] 'target' ]
, [ [ @collection_mode = ] collection_mode ]
, [ [ @days_until_expiration = ] days_until_expiration ]
, [ [ @proxy_id = ] proxy_id ]
, [ [ @proxy_name = ] 'proxy_name' ]
, [ [ @schedule_uid = ] 'schedule_uid' ]
, [ [ @schedule_name = ] 'schedule_name' ]
, [ [ @logging_level = ] logging_level ]
, [ [ @description = ] 'description' ]
, [ @collection_set_id = ] collection_set_id OUTPUT
, [ [ @collection_set_uid = ] 'collection_set_uid' OUTPUT ]

Arguments
[ @name = ] 'name'
Is the name of the collection set. name is sysname and cannot be an empty string or NULL.
name must be unique. For a list of current collection set names, query the syscollector_collection_sets system
view.
[ @target = ] 'target'
Reserved for future use. name is nvarchar(128) with a default value of NULL.
[ @collection_mode = ] collection_mode
Specifies the manner in which the data is collected and stored. collection_mode is smallint and can have one of
the following values:
0 - Cached mode. Data collection and upload are on separate schedules. Specify cached mode for continuous
collection.
1 - Non-cached mode. Data collection and upload is on the same schedule. Specify non-cached mode for ad hoc
collection or snapshot collection.
The default value for collection_mode is 0. When collection_mode is 0, schedule_uid or schedule_name must be
specified.
[ @days_until_expiration = ] days_until_expiration
Is the number of days that the collected data is saved in the management data warehouse. days_until_expiration is
smallint with a default value of 730 (two years). days_until_expiration must be 0 or a positive integer.
[ @proxy_id = ] proxy_id
Is the unique identifier for a SQL Server Agent proxy account. proxy_id is int with a default value of NULL. If
specified, proxy_name must be NULL. To obtain proxy_id, query the sysproxies system table. The dc_admin fixed
database role must have permission to access the proxy. For more information, see Create a SQL Server Agent
Proxy.
[ @proxy_name = ] 'proxy_name'
Is the name of the proxy account. proxy_name is sysname with a default value of NULL. If specified, proxy_id must
be NULL. To obtain proxy_name, query the sysproxies system table.
[ @schedule_uid = ] 'schedule_uid'
Is the GUID that points to a schedule. schedule_uid is uniqueidentifier with a default value of NULL. If specified,
schedule_name must be NULL. To obtain schedule_uid, query the sysschedules system table.
When collection_mode is set to 0, schedule_uid or schedule_name must be specified. When collection_mode is set
to 1, schedule_uid or schedule_name is ignored if specified.
[ @schedule_name = ] 'schedule_name'
Is the name of the schedule. schedule_name is sysname with a default value of NULL. If specified, schedule_uid
must be NULL. To obtain schedule_name, query the sysschedules system table.
[ @logging_level = ] logging_level
Is the logging level. logging_level is smallint with one of the following values:
0 - log execution information and SSIS events that track:
Starting/stopping collection sets
Starting/stopping packages
Error information
1 - level-0 logging and:
Execution statistics
Continuously running collection progress
Warning events from SSIS
2 - level-1 logging and detailed event information from SSIS
The default value for logging_level is 1.
[ @description = ] 'description'
Is the description of the collection set. description is nvarchar(4000) with a default value of NULL.
[ @collection_set_id = ] collection_set_id
Is the unique local identifier for the collection set. collection_set_id is int with OUTPUT and is required.
[ @collection_set_uid = ] 'collection_set_uid'
Is the GUID for the collection set. collection_set_uid is uniqueidentifier with OUTPUT with a default value
of NULL.
Return Code Values
0 (success) or 1 (failure)

Remarks
sp_syscollector_create_collection_set must be run in the context of the msdb system database.

Permissions
Requires membership in the dc_admin (with EXECUTE permission) fixed database role to execute this procedure.

Examples
A. Creating a collection set by using default values
The following example creates a collection set by specifying only the required parameters. @collection_mode is not
required, but the default collection mode (cached) requires specifying either a schedule ID or schedule name.

USE msdb;
GO
DECLARE @collection_set_id int;
EXECUTE dbo.sp_syscollector_create_collection_set
@name = N'Simple collection set test 1',
@description = N'This is a test collection set that runs in non-cached mode.',
@collection_mode = 1,
@collection_set_id = @collection_set_id OUTPUT;
GO

B. Creating a collection set by using specified values


The following example creates a collection set by specifying values for many of the parameters.

USE msdb;
GO
DECLARE @collection_set_id int;
DECLARE @collection_set_uid uniqueidentifier;
SET @collection_set_uid = NEWID();
EXEC dbo.sp_syscollector_create_collection_set
@name = N'Simple collection set test 2',
@collection_mode = 0,
@days_until_expiration = 365,
@description = N'This is a test collection set that runs in cached mode.',
@logging_level = 2,
@schedule_name = N'CollectorSchedule_Every_30min',
@collection_set_id = @collection_set_id OUTPUT,
@collection_set_uid = @collection_set_uid OUTPUT;

See Also
Data Collection
Create a Custom Collection Set That Uses the Generic T-SQL Query Collector Type (Transact-SQL)
Data Collector Stored Procedures (Transact-SQL)
syscollector_collection_sets (Transact-SQL)
sp_syscollector_create_collector_type (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Creates a collector type for the data collector. A collector type is a logical wrapper around the SSIS packages that
provide the actual mechanism for collecting data and uploading it to the management data warehouse.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_create_collector_type
[ [@collector_type_uid = ] 'collector_type_uid' OUTPUT ]
, [ @name = ] 'name'
, [ [ @parameter_schema = ] 'parameter_schema' ]
, [ [ @parameter_formatter = ] 'parameter_formatter' ]
, [ @collection_package_id = ] 'collection_package_id'
, [ @upload_package_id = ] 'upload_package_id'

Arguments
[ @collector_type_uid = ] 'collector_type_uid'
Is the GUID for the collector type. collector_type_uid is uniqueidentifier and if it is NULL it will be automatically
created and returned as OUTPUT.
[ @name = ] 'name'
Is the name of the collector type. name is sysname and must be specified.
[ @parameter_schema = ] 'parameter_schema'
Is the XML schema for this collector type. parameter_schema is xml with a default of NULL.
[ @parameter_formatter = ] 'parameter_formatter'
Is the template to use to transform the XML for use in the collection set property page. parameter_formatter is xml
with a default of NULL.
[@collection_package_id = ] collection_package_id
Is a local unique identifier that points to the SSIS collection package used by the collection set.
collection_package_id is uniqueidentifer and is required.
[@upload_package_id = ] upload_package_id
Is a local unique identifier that points to the SSIS upload package used by the collection set. upload_package_id is
uniqueidentifier and is required.

Return Code Values


0 (success) or 1 (failure)

Permissions
Requires membership in the dc_admin (with EXECUTE permission) fixed database role to execute this procedure.
Example
This creates the Generic T-SQL Query collector type.

EXEC sp_syscollector_create_collector_type
@collector_type_uid = '302E93D1-3424-4be7-AA8E-84813ECF2419',
@name = 'Generic T-SQL Query Collector Type',
@parameter_schema = '<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="DataCollectorType">
<xs:element name="TSQLQueryCollector">
<xs:complexType>
<xs:sequence>
<xs:element name="Query" minOccurs="1" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="Value" type="xs:string" />
<xs:element name="OutputTable" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Databases" minOccurs="0" maxOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="Database" minOccurs="0" maxOccurs="unbounded" type="xs:string" />
</xs:sequence>
<xs:attribute name="UseSystemDatabases" type="xs:boolean" use="optional" />
<xs:attribute name="UseUserDatabases" type="xs:boolean" use="optional" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>',
@collection_package_id = '292B1476-0F46-4490-A9B7-6DB724DE3C0B',
@upload_package_id = '6EB73801-39CF-489C-B682-497350C939F0';
GO

See Also
System Stored Procedures (Transact-SQL)
Data Collection
sp_syscollector_delete_collection_item (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes a collection item from a collection set.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_delete_collection_item [[ @collection_item_id = ] collection_item_id ]
, [[ @name = ] 'name' ]

Arguments
[ @collection_item_id = ] collection_item_id
Is the unique identifier for the collection item. collection_item_id is int with a default of NULL. collection_item_id
must have a value if name is NULL.
[ @name = ] 'name'
Is the name of the collection item. name is sysname with a default value of NULL. name must have a value if
collection_item_id is NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_syscollector_delete_collection_item must be run in the context of the msdb system database. Collection items
cannot be deleted from system collection sets.
The collection set that contains the collection item is stopped and restarted during this operation.

Permissions
Requires membership in the dc_admin (with EXECUTE permission) fixed database role to execute this procedure.

Examples
The following example deletes a collection item named MyCollectionItem1 .

USE msdb;
GO
EXEC sp_syscollector_delete_collection_item @name = 'MyCollectionItem1';

See Also
Data Collection
sp_syscollector_create_collection_item (Transact-SQL)
Data Collector Stored Procedures (Transact-SQL)
syscollector_collection_items (Transact-SQL)
sp_syscollector_delete_collection_set (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes a user-defined collection set and all its collection items.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_delete_collection_set [[ @collection_set_id = ] collection_set_id OUTPUT ]
, [[ @name = ] 'name' ]

Arguments
[ @collection_set_id = ] collection_set_id
Is the unique identifier for the collection set. collection_set_id is int and must have a value if name is NULL.
[ @name = ] 'name'
Is the name of the collection set. name is sysname and must have a value if collection_set_id is NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_syscollector_delete_collection_set must be run in the context of the msdb system database.
Either collection_set_id or name must have a value, both cannot be NULL. To obtain these values, query the
syscollector_collection_set system view.
System-defined collection sets cannot be deleted.

Permissions
Requires membership in the dc_admin (with EXECUTE permission) fixed database role to execute this procedure.

Examples
The following example deletes a user-defined collection set specifying the collection_set_id.

USE msdb;
GO
EXEC dbo.sp_syscollector_delete_collection_set
@collection_set_id = 4;

See Also
Data Collector Stored Procedures (Transact-SQL)
Data Collection
syscollector_collection_sets (Transact-SQL)
sp_syscollector_delete_collector_type (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes the definition of a collector type.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_delete_collector_type [[ @collector_type_uid = ] 'collector_type_uid' ]
, [[ @name = ] 'name' ]

Arguments
[ @collector_type_uid = ] 'collector_type_uid'
Is the GUID for the collector type. collector_type_uid is uniqueidentifier and must have a value if name is NULL.
[ @name = ] 'name'
Is the name of the collector type. name is sysname and must have a value if collector_type_uid is NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
Either collector_type_uid or name must have a value, both cannot be NULL.
This procedure will throw an error if collection items of this collection type exist.

Permissions
Requires membership in the dc_admin (with EXECUTE permission) fixed database role to execute this procedure.

Example
This example deletes the Generic T-SQL Query collector type.

USE msdb;
GO
EXEC sp_syscollector_delete_collector_type @collector_type_uid = '302E93D1-3424-4be7-AA8E-84813ECF2419';

See Also
System Stored Procedures (Transact-SQL)
Data Collection
sp_syscollector_delete_execution_log_tree (Transact-
SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes all the log entries for the run of a single collection set. It also deletes the log entries from the SSIS tables for
that run.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_delete_execution_log_tree[ @log_id = ] log_id
, [ @from_collection_set = ] from_collection_set

Arguments
[ @log_id = ] log_id
Is the unique identifier for the collection set log. log_id is int.
[ @from_collection_set = ] from_collection_set
Is the identifier for the collection set. from_collection_set is bit=1.

Return Code Values


0 (success) or 1 (failure)

Permissions
Requires membership in the dc_operator (with EXECUTE permission) fixed database role to execute this
procedure.

See Also
System Stored Procedures (Transact-SQL)
sp_syscollector_disable_collector (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Disables the data collector. Because there is only one data collector per server, no parameters are required.
Transact-SQL Syntax Conventions

Syntax
dbo.sp_syscollector_disable_collector

Arguments
None

Return Code Values


0 (success) or 1 (failure)

Remarks
Defaults to the data collector on the server.

Permissions
Requires membership in the dc_admin or dc_operator (with EXECUTE permission) fixed database role to execute
this procedure.

Examples
The following example disables the data collector.

EXEC dbo.sp_syscollector_disable_collector;

See Also
System Stored Procedures (Transact-SQL)
Data Collection
sp_syscollector_enable_collector (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Enables the data collector. Because there is only one data collector per server, no parameters are required.
Transact-SQL Syntax Conventions

Syntax
dbo.sp_syscollector_enable_collector

Arguments
None

Return Code Values


0 (success) or 1 (failure)

Remarks
Defaults to the data collector on the server.

Permissions
Requires membership in the dc_admin or dc_operator (with EXECUTE permission) fixed database role to execute
this procedure.

Examples
The following example enables the data collector.

USE msdb;
GO
EXEC dbo.sp_syscollector_enable_collector;

See Also
System Stored Procedures (Transact-SQL)
Data Collection
sp_syscollector_set_cache_directory (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Specifies the directory where collected data is stored before it is uploaded to the management data warehouse.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_set_cache_directory [ @cache_directory = ] 'cache_directory'

Arguments
[ @cache_directory = ] 'cache_directory'
The directory in the file system where collected data is stored temporarily. cache_directory is nvarchar(255), with
a default value of NULL. If no value is specified, the default temporary SQL Server directory is used.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must disable the data collector before changing the cache directory configuration. This stored procedure fails if
the data collector is enabled. For more information, see Enable or Disable Data Collection, and Manage Data
Collection.
The specified directory does not need to exist at the time the sp_syscollector_set_cache_directory is executed;
however, data cannot be successully cached and uploaded until the directory is created. We recommend creating
the directory before executing this stored procedure.

Permissions
Requires membership in the dc_admin (with EXECUTE permission) fixed database role to execute this procedure.

Examples
The following example disables the data collector, sets the cache directory for the data collector to D:\tempdata
,and then enables the data collector.
USE msdb;
GO
EXECUTE dbo.sp_syscollector_disable_collector;
GO
EXEC dbo.sp_syscollector_set_cache_directory N'D:\tempdata';
GO
EXECUTE dbo.sp_syscollector_enable_collector;
GO

See Also
Data Collector Stored Procedures (Transact-SQL)
sp_syscollector_set_cache_window (Transact-SQL)
sp_syscollector_set_cache_window (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sets the number of times to attempt a data upload in case of failure. Retrying an upload in the event of a failure
mitigates the risk of losing collected data.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_set_cache_window [ @cache_window = ] cache_window

Arguments
[ @cache_window = ] cache_window
Is the number of times a failed data upload to the management data warehouse is retried without losing data.
cache_window is int with a default value of 1. cache_window can have one of the following values:

VALUE DESCRIPTION

-1 Cache all the upload data from the previous upload failures.

0 Do not cache any data from an upload failure.

n Cache data from n previous upload failures, where n >= 1.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must disable the data collector before changing the cache window configuration. This stored procedure fails if
the data collector is enabled. For more information, see Enable or Disable Data Collection, and Manage Data
Collection.

Permissions
Requires membership in the dc_admin (with EXECUTE permission) fixed database role to execute this procedure.

Examples
The following example disables the data collector, configures the cache window to retain data for up to three failed
uploads, and then enables to data collector.
USE msdb;
GO
EXECUTE dbo.sp_syscollector_disable_collector;
GO
EXECUTE dbo.sp_syscollector_set_cache_window 3;
GO
EXECUTE dbo.sp_syscollector_enable_collector;

See Also
System Stored Procedures (Transact-SQL)
sp_syscollector_set_cache_directory (Transact-SQL)
sp_syscollector_set_warehouse_database_name
(Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Specifies the database name defined in the connection string used to connect to the management data warehouse.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_set_warehouse_database_name [ @database_name = ] 'database_name'

Arguments
[ @database_name = ] 'database_name'
Is the name of the management data warehouse. database_name is sysname with a default value of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must disable the data collector before changing the data collector-wide configuration. This procedure fails if
the data collector is enabled.
To view the current database name, query the syscollector_config_store system view.

Permissions
Requires membership in the dc_admin (with EXECUTE permission) fixed database role to execute this procedure.

Examples
The following example sets the name of the management data warehouse to RemoteMDW .

USE msdb;
GO
EXEC sp_syscollector_set_warehouse_database_name N'RemoteMDW';
GO

See Also
System Stored Procedures (Transact-SQL)
sp_syscollector_set_warehouse_instance_name
(Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Specifies the instance name for the connection string used to connect to the management data warehouse.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_set_warehouse_instance_name [ @instance_name = ] 'instance_name'

Arguments
[ @instance_name = ] 'instance_name'
Is the instance name. instance_name is sysname and defaults to the local instance if NULL.

NOTE: instance_name must be the fully qualified instance name, which consists of the computer name and the
instance name in the form computerName\instanceName.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must disable the data collector before changing this data collector-wide configuration. This procedure fails if
the data collector is enabled.
To view the current instance name, query the syscollector_config_store system view.

Permissions
Requires membership in the dc_admin (with EXECUTE permission) fixed database role to execute this procedure.

Examples
The following example illustrates how to configure the data collector to use a management data warehouse
instance on a remote server. In this example the remote server is named RemoteSERVER and the database is
installed on the default instance.
USE msdb;
GO
EXEC sp_syscollector_set_warehouse_instance_name N'RemoteSERVER'; -- the default instance is assumed on the
remote server
GO

See Also
Data Collector Stored Procedures (Transact-SQL)
syscollector_config_store (Transact-SQL)
sp_syscollector_start_collection_set (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Starts a collection set if the collector is already enabled and the collection set is not running. If the collector is not
enabled, enable the collector by running sp_syscollector_enable_collector and then use this stored procedure to
start a collection set.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_start_collection_set
[ [ @collection_set_id = ] collection_set_id ]
, [[ @name = ] 'name' ]

Arguments
[ @collection_set_id = ] collection_set_id
Is the unique local identifier for the collection set. collection_set_id is int with a default value of NULL.
collection_set_id must have a value if name is NULL.
[ @name = ] 'name'
Is the name of the collection set. name is sysname with a default value of NULL. name must have a value if
collection_set_id is NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_syscollector_create_collection_set must be run in the context of the msdb system database and SQL Server
Agent must be enabled.
This procedure fails when run against a collection set that does not have a schedule. If the collection set does not
have a schedule (because its collection mode is set to non-cached, for example), use the
sp_syscollector_run_collection_set stored procedure to start the collection set.
This procedure enables the collection and upload jobs for the specified collection set, and will immediately start the
collection agent job if the collection set has its collection mode set to cached (0). For more information, see
sp_syscollector_create_collection_set.
If the collection set does not contain any collection items, this operation has no effect. Error 14685 is returned as a
warning.

Permissions
Requires membership in the dc_operator fixed database role to execute this procedure. If the collection set does not
have a proxy account, membership in the sysadmin fixed server role is required.

Examples
The following example starts a collection set using its identifier.

USE msdb;
GO
EXEC sp_syscollector_start_collection_set @collection_set_id = 1;

See Also
Data Collector Stored Procedures (Transact-SQL)
Data Collection
syscollector_collection_sets (Transact-SQL)
sp_syscollector_stop_collection_set (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Stops a collection set.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_stop_collection_set
[ [ @collection_set_id = ] collection_set_id ]
, [ [ @name = ] 'name' ]
, [ [ @stop_collection_job = ] stop_collection_job ]

Arguments
[ @collection_set_id = ] collection_set_id
Is the unique local identifier for the collection set. collection_set_id is int with a default value of NULL.
collection_set_id must have a value if name is NULL.
[ @name = ] 'name'
Is the name of the collection set. name is sysname with a default value of NULL. name must have a value if
collection_set_id is NULL.
[ @stop_collection_job = ] stop_collection_job
Specifies that the collection job for the collection set be stopped if it is running. stop_collection_job is bit with a
default of 1.
stop_collection_job applies only to collection sets with collection mode set to cached. For more information, see
sp_syscollector_create_collection_set (Transact-SQL).

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_syscollector_create_collection_set must be run in the context of the msdb system database.

Permissions
Requires membership in the dc_operator (with EXECUTE permission) fixed database role to execute this procedure.

Examples
The following example stops a collection set using its identifier.
USE msdb;
GO
EXEC sp_syscollector_stop_collection_set @collection_set_id = 1;

See Also
Data Collection
Data Collector Stored Procedures (Transact-SQL)
sp_syscollector_run_collection_set (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Starts a collection set if the collector is already enabled and the collection set is configured for non-cached
collection mode.

NOTE
This procedure will fail if it is run against a collection set that is configured for cached collection mode.

sp_syscollector_run_collection_set enables a user to take on-demand data snapshots.


Transact-SQL Syntax Conventions

Syntax
sp_syscollector_run_collection_set [[ @collection_set_id = ] collection_set_id ]
, [[ @name = ] 'name' ]

Arguments
[ @collection_set_id = ] collection_set_id
Is the unique local identifier for the collection set. collection_set_id is int and must have a value if name is NULL.
[ @name = ] 'name'
Is the name of the collection set. name is sysname and must have a value if collection_set_id is NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
Either collection_set_id or name must have a value, both cannot be NULL.
This procedure will start the collection and upload jobs for the specified collection set and will immediately start
the collection agent job if the collection set has its @collection_mode set to non-cached (1). For more
information see, sp_syscollector_create_collection_set (Transact-SQL).
sp_sycollector_run_collection_set can also be used to run a collection set that does not have a schedule.

Permissions
Requires membership in the dc_operator (with EXECUTE permission) fixed database role to execute this
procedure.
Example
Start a collection set using its identifier.

USE msdb;
GO
EXEC sp_syscollector_run_collection_set @collection_set_id = 1;

See Also
System Stored Procedures (Transact-SQL)
Data Collection
sp_syscollector_update_collection_item (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Used to modify the properties of a user-defined collection item or to rename a user-defined collection item.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_update_collection_item
[ [ @collection_item_id = ] collection_item_id ]
, [ [ @name = ] 'name' ]
, [ [ @new_name = ] 'new_name' ]
, [ [ @frequency = ] frequency ]
, [ [ @parameters = ] 'parameters' ]

Arguments
[ @collection_item_id = ] collection_item_id
Is the unique identifer that identifies the collection item. collection_item_id is int with a default value of NULL.
collection_item_id must have a value if name is NULL.
[ @name = ] 'name'
Is the name of the collection item. name is sysname with a default value of NULL. name must have a value if
collection_item_id is NULL.
[ @new_name = ] 'new_name'
Is the new name for the collection item. new_name is sysname, and if used, cannot be an empty string.
new_name must be unique. For a list of current collection item names, query the syscollector_collection_items
system view.
[ @frequency = ] frequency
Is the frequency (in seconds) that data is collected by this collection item. frequency is int, with a default of 5, the
minimum value that can be specified.
[ @parameters = ] 'parameters'
The input parameters for the collection item. parameters is xml with a default of NULL. The parameters schema
must match the parameters schema of the collector type.

Return Code Values


0 (success) or 1 (failure)

Remarks
If the collection set is set to non-cached mode, changing the frequency is ignored because this mode causes both
data collection and upload to occur at the schedule specified for the collection set. To view the status of the
collection set, run the following query. Replace <collection_item_id> with the ID of the collection item to be
updated.

USE msdb;
GO
SELECT cs.collection_set_id, collection_set_uid, cs.name
,'is running' = CASE WHEN is_running = 0 THEN 'No' ELSE 'Yes' END
,'cache mode' = CASE WHEN collection_mode = 0 THEN 'Cached mode' ELSE 'Non-cached mode' END
FROM syscollector_collection_sets AS cs
JOIN syscollector_collection_items AS ci
ON ci.collection_set_id = cs.collection_set_id
WHERE collection_item_id = <collection_item_id>;

Permissions
Requires membership in the dc_admin or the dc_operator (with EXECUTE permission) fixed database role to
execute this procedure. Although dc_operator can run this stored procedure, members of this role are limited in
the properties that they can change. The following properties can only be changed by dc_admin:
@new_name
@parameters

Examples
The following examples are based on the collection item created in the example defined in
sp_syscollector_create_collection_item (Transact-SQL).
A. Changing the collection frequency
The following example changes the collection frequency for the specified collection item.

USE msdb;
GO
EXEC sp_syscollector_update_collection_item
@name = N'My custom TSQL query collector item',
@frequency = 3000;
GO

B. Renaming a collection item


The following example renames a collection item.

USE msdb;
GO
EXEC sp_syscollector_update_collection_item
@name = N'My custom TSQL query collector item',
@new_name = N'My modified TSQL item';
GO

C. Changing the parameters of a collection item


The following example changes the parameters associated with the collection item. The statement defined within
the <Value> attribute is changed and the UseSystemDatabases attribute is set to false. To view the current
parameters for this item, query the parameters column in the syscollector_collection_items system view. You may
need to modify the value for @collection_item_id .
USE msdb;
GO
EXEC sp_syscollector_update_collection_item
@collection_item_id = 9,
@parameters = '
\<ns:TSQLQueryCollector xmlns:ns="DataCollectorType">
<Query>
<Value>SELECT * FROM sys.dm_db_index_usage_stats</Value>
<OutputTable>MyOutputTable</OutputTable>
</Query>
<Databases>
<Database> UseSystemDatabases = "false"
UseUserDatabases = "true"</Database>
</Databases>
\</ns:TSQLQueryCollector>';
GO

See Also
System Stored Procedures (Transact-SQL)
Data Collection
sp_syscollector_create_collection_item (Transact-SQL)
syscollector_collection_items (Transact-SQL)
sp_syscollector_update_collection_set (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Used to modify the properties of a user-defined collection set or to rename a user-defined collection set.

WARNING
In cases where the Windows account configured as a proxy is a non-interactive or interactive user that has not yet logged in,
the profile directory will not exist, and the creation of the staging directory will fail. Therefore, if you are using a proxy account
on a domain controller, you must specify an interactive account that has been used at least once in order to assure that the
profile directory has been created.

Transact-SQL Syntax Conventions

Syntax
sp_syscollector_update_collection_set
[ [ @collection_set_id = ] collection_set_id ]
, [ [ @name = ] 'name' ]
, [ [ @new_name = ] 'new_name' ]
, [ [ @target = ] 'target' ]
, [ [ @collection_mode = ] collection_mode ]
, [ [ @days_until_expiration = ] days_until_expiration ]
, [ [ @proxy_id = ] proxy_id ]
, [ [ @proxy_name = ] 'proxy_name' ]
,[ [ @schedule_uid = ] 'schedule_uid' ]
,[ [ @schedule_name = ] 'schedule_uid' ]
, [ [ @logging_level = ] logging_level ]
, [ [ @description = ] 'description' ]

Arguments
[ @collection_set_id = ] collection_set_id
Is the unique local identifier for the collection set. collection_set_id is int and must have a value if name is NULL.
[ @name = ] 'name'
Is the name of the collection set. name is sysname and must have a value if collection_set_id is NULL.
[ @new_name = ] 'new_name'
Is the new name for the collection set. new_name is sysname, and if used, cannot be an empty string. new_name
must be unique. For a list of current collection set names, query the syscollector_collection_sets system view.
[ @target = ] 'target'
Reserved for future use.
[ @collection_mode = ] collection_mode
Is the type of data collection to use. collection_mode is smallint and can have one of the following values:
0 - Cached mode. Data collection and upload are on separate schedules. Specify cached mode for continuous
collection.
1 - Non-cached mode. Data collection and upload is on the same schedule. Specify non-cached mode for ad hoc
collection or snapshot collection.
If changing from non-cached mode to cached mode (0), you must also specify either schedule_uid or
schedule_name.
[ @days_until_expiration= ] days_until_expiration
Is the number of days that the collected data is saved in the management data warehouse. days_until_expiration is
smallint. days_until_expiration must be 0 or a positive integer.
[ @proxy_id = ] proxy_id
Is the unique identifier for a SQL Server Agent proxy account. proxy_id is int.
[ @proxy_name = ] 'proxy_name'
Is the name of the proxy. proxy_name is sysname and is nullable.
[ @schedule_uid = ] 'schedule_uid'
Is the GUID that points to a schedule. schedule_uid is uniqueidentifier.
To obtain schedule_uid, query the sysschedules system table.
When collection_mode is set to 0, schedule_uid or schedule_name must be specified. When collection_mode is set
to 1, schedule_uid or schedule_name is ignored if specified.
[ @schedule_name = ] 'schedule_name'
Is the name of the schedule. schedule_name is sysname and is nullable. If specified, schedule_uid must be NULL.
To obtain schedule_name, query the sysschedules system table.
[ @logging_level = ] logging_level
Is the logging level. logging_level is smallint with one of the following values:
0 - Log execution information and SSIS events that track:
Starting/stopping collection sets
Starting/stopping packages
Error information
1 - Level-0 logging and:
Execution statistics
Continuously running collection progress
Warning events from SSIS
2 - Level-1 logging and detailed event information from SSIS.
The default value for logging_level is 1.
[ @description = ] 'description'
Is the description of the collection set. description is nvarchar(4000).

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_syscollector_update_collection_set must be run in the context of the msdb system database.
Either collection_set_id or name must have a value, both cannot be NULL. To obtain these values, query the
syscollector_collection_sets system view.
If the collection set is running, you can only update schedule_uid and description. To stop the collection set, use
sp_syscollector_stop_collection_set.

Permissions
Requires membership in the dc_admin or the dc_operator (with EXECUTE permission) fixed database role to
execute this procedure. Although dc_operator can run this stored procedure, members of this role are limited in the
properties that they can change. The following properties can only be changed by dc_admin:
@new_name
@target
@proxy_id
@description
@collection_mode
@days_until_expiration

Examples
A. Renaming a collection set
The following example renames a user-defined collection set.

USE msdb;
GO
EXECUTE dbo.sp_syscollector_update_collection_set
@name = N'Simple collection set test 1',
@new_name = N'Collection set test 1 in cached mode';
GO

B. Changing the collection mode from non-cached to cached


The following example changes the collection mode from non-cached mode to cached mode. This change requires
that you specify a schedule ID or schedule name.

USE msdb;
GO
EXECUTE dbo.sp_syscollector_update_collection_set
@name = N'Collection set test 1 in cached mode',
@collection_mode = 0,
@schedule_uid = 'C7022AF3-51B8-4011-B159-64C47C88FF70';
-- alternatively, use @schedule_name.
-- @schedule_name = N'CollectorSchedule_Every_15min;
GO

C. Changing other collection set parameters


The following example updates various properties of the collection set named "Simple collection set test 2'.
USE msdb;
GO
EXEC dbo.sp_syscollector_update_collection_set
@name = N'Simple collection set test 2',
@collection_mode = 1,
@days_until_expiration = 5,
@description = N'This is a test collection set that runs in noncached mode.',
@logging_level = 0;
GO

See Also
System Stored Procedures (Transact-SQL)
Data Collection
syscollector_collection_sets (Transact-SQL)
dbo.sysschedules (Transact-SQL)
sp_syscollector_update_collector_type (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Updates a collector type for a collection item. Given the name and GUID of a collector type, updates the collector
type configuration, including the collection and upload package, the parameter schema, and the parameter
formatter schema.
Transact-SQL Syntax Conventions

Syntax
sp_syscollector_update_collector_type [ @collector_type_uid = ] 'collector_type_uid' OUTPUT
, [ @name = ] 'name'
, [ @parameter_schema = ] 'parameter_schema'
, [ @collection_package_id = ] collection_package_id
, [ @upload_package_id = ] upload_package_id

Arguments
[ @collector_type_uid = ] 'collector_type_uid'
Is the GUID for the collector type. collector_type_uid is uniqueidentifier, and if it is NULL it will be automatically
created and returned as OUTPUT.
[ @name = ] 'name'
Is the name of the collector type. name is sysname and must be specified.
[ @parameter_schema = ] 'parameter_schema'
Is the XML schema for this collector type. parameter_schema is xml and may be required by certain collector types.
If it is not required, this argument can be NULL.
[ @collection_package_id = ] collection_package_id
Is a local unique identifier that points to the SSIS collection package used by the collection set.
collection_package_id is uniqueidentifer and is required. To obtain the value for collection_package_id, query the
dbo.syscollector_collector_types system view in the msdb database.
[ @upload_package_id = ] upload_package_id
Is a local unique identifier that points to the SSIS upload package used by the collection set. upload_package_id is
uniqueidentifier and is required. To obtain the value for upload_package_id, query the
dbo.syscollector_collector_types system view in the msdb database.

Return Code Values


0 (success) or 1 (failure)

Permissions
Requires membership in the dc_admin (with EXECUTE permission) fixed database role.
Example
This example updates the Generic T-SQL Query collector type. (In the example, the default schema for the Generic
T-SQL Query collector type is used.)

USE msdb;
GO
EXEC sp_syscollector_update_collector_type
@collector_type_uid = '302E93D1-3424-4BE7-AA8E-84813ECF2419',
@name = 'Generic T-SQL Query Collector Type',
@parameter_schema = '<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="DataCollectorType">
<xs:element name="TSQLQueryCollector">
<xs:complexType>
<xs:sequence>
<xs:element name="Query" minOccurs="1" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="Value" type="xs:string" />
<xs:element name="OutputTable" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Databases" minOccurs="0" maxOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="Database" minOccurs="0" maxOccurs="unbounded" type="xs:string" />
</xs:sequence>
<xs:attribute name="UseSystemDatabases" type="xs:boolean" use="optional" />
<xs:attribute name="UseUserDatabases" type="xs:boolean" use="optional" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>',
@collection_package_id = '292B1476-0F46-4490-A9B7-6DB724DE3C0B',
@upload_package_id = '6EB73801-39CF-489C-B682-497350C939F0';
GO

See Also
System Stored Procedures (Transact-SQL)
Data Collection
sp_syscollector_upload_collection_set (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Starts an upload of collection set data if the collection set is enabled.

IMPORTANT
This stored procedure can only be used for collection sets that are configured for cached mode data collection and upload.

Transact-SQL Syntax Conventions

Syntax
sp_syscollector_upload_collection_set [[ @collection_set_id = ] collection_set_id ]
, [[ @name = ] 'name' ]

Arguments
[ @collection_set_id = ] collection_set_id
Is the unique local identifier for the collection set. collection_set_id is int and must have a value if name is NULL.
[ @name = ] 'name'
Is the name of the collection set. name is sysname and must have a value if collection_set_id is NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
Either collection_set_id or name must have a value; both cannot be NULL.
This procedure can be used for starting an on-demand upload for a running collection set. It can only be used for
collection sets that are configured for cached mode data collection and upload. This enables a user to obtain data to
analyze without having to wait for a scheduled upload.

Permissions
Requires membership in the dc_operator (with EXECUTE permission) fixed database role to execute this
procedure.

Example
Does an on-demand upload of a collection set named Simple Collection Set .
USE msdb;
GO
EXEC sp_syscollector_upload_collection_set @name = 'Simple Collection Set' ;

See Also
System Stored Procedures (Transact-SQL)
Data Collection
Database Engine Stored Procedures (Transact-
SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
SQL Server supports the following system stored procedures that are used for general maintenance of an
instance of SQL Server.

sp_add_data_file_recover_suspect_db sp_help

sp_add_log_file_recover_suspect_db sp_helpconstraint

sp_addextendedproc sp_helpdb

sp_addextendedproperty sp_helpdevice

sp_addmessage sp_helpextendedproc

sp_addtype sp_helpfile

sp_addumpdevice sp_helpfilegroup

sp_altermessage sp_helpindex

sp_attach_db sp_helplanguage

sp_attach_single_file_db sp_helpserver

sp_autostats sp_helpsort

sp_bindefault sp_helpstats

sp_bindrule sp_helptext

sp_bindsession sp_helptrigger

sp_certify_removable sp_indexoption

sp_clean_db_file_free_space sp_invalidate_textptr

sp_clean_db_free_space sp_lock

sp_configure sys.sp_merge_xtp_checkpoint_files

sp_control_plan_guide sp_monitor
sp_create_plan_guide sp_prepare

sp_create_plan_guide_from_handle sp_prepexec

sp_create_removable sp_prepexecrpc

sp_createstats sp_procoption

sp_cycle_errorlog sp_recompile

sp_datatype_info sp_refreshview

sp_db_increased_partitions sp_releaseapplock

sp_dbcmptlevel sp_rename

sp_dbmmonitoraddmonitoring sp_renamedb

sp_dbmmonitorchangealert sp_resetstatus

sp_dbmmonitorchangemonitoring sp_sequence_get_range

sp_dbmmonitordropalert sp_serveroption

sp_dbmmonitordropmonitoring sp_set_session_context

sp_dbmmonitorhelpalert sp_setnetname

sp_dbmmonitorhelpmonitoring sp_settriggerorder

sp_dbmmonitorresults sp_spaceused

sp_delete_backuphistory sp_tableoption

sp_depends sp_unbindefault

sp_describe_first_result_set sp_unbindrule

sp_describe_undeclared_parameters sp_updateextendedproperty

sp_detach_db sp_updatestats

sp_dropdevice sp_unprepare

sp_dropextendedproc sp_validname

sp_dropextendedproperty sp_who

sp_dropmessage sys.sp_xtp_control_proc_exec_stats

sp_droptype sys.sp_flush_log
sp_execute sys.sp_xtp_bind_db_resource_pool

sp_executesql sys.sp_xtp_control_query_exec_stats

sp_getapplock sys.sp_xtp_checkpoint_force_garbage_collection

sp_getbindtoken sys.sp_xtp_unbind_db_resource_pool

See Also
System Stored Procedures (Transact-SQL)
sp_add_data_file_recover_suspect_db (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adds a data file to a filegroup when recovery cannot complete on a database due to insufficient space on the file
group (error 1105). After the file is added, this stored procedure turns off the suspect setting and completes the
recovery of the database. The parameters are the same as those for ALTER DATABASE database_name ADD FILE.
Transact-SQL Syntax Conventions

Syntax
sp_add_data_file_recover_suspect_db [ @dbName= ] 'database'
, [ @filegroup = ] 'filegroup_name'
, [ @name = ] 'logical_file_name'
, [ @filename= ] 'os_file_name'
, [ @size = ] 'size'
, [ @maxsize = ] 'max_size'
, [ @filegrowth = ] 'growth_increment'

Arguments
[ @dbName= ] 'database '
Is the name of the database. database is sysname, with no default.
[ @filegroup= ] 'filegroup_name '
Is the filegroup to which to add the file. filegroup_name is nvarchar(260), with a default of NULL, which indicates
the primary file.
[ @name= ] 'logical_file_name '
Is the name used in the SQL Server to reference the file. The name must be unique in the server. logical_file_name
is nvarchar(260), with no default.
[ @filename= ] 'os_file_name '
Is the path and file name used by the operating system for the file. The file must reside on an instance of the
Database Engine. os_file_name is nvarchar(260), with no default.
[ @size= ] 'size '
Is the initial size of the file. size is nvarchar(20), with a default of NULL. Specify a whole number; do not include a
decimal. The MB and KB suffixes can be used to specify megabytes or kilobytes. The default is MB. The minimum
value is 512 KB. If size is not specified, the default is 1 MB.
[ @maxsize= ] 'max_size '
Is the maximum size to which the file can grow. max_size is nvarchar(20), with a default of NULL. Specify a whole
number; do not include a decimal. The MB and KB suffixes can be used to specify megabytes or kilobytes. The
default is MB.
If max_size is not specified, the file will grow until the disk is full. The Microsoft Windows application log warns an
administrator when a disk is about to become full.
[ @filegrowth= ] 'growth_increment '
Is the amount of space added to the file each time new space is required. growth_increment is nvarchar(20), with
a default of NULL. A value of 0 indicates no growth. Specify a whole number; do not include a decimal. The value
can be specified in MB, KB, or percent (%). When % is specified, the growth increment is the specified percentage of
the size of the file at the time the increment occurs. If a number is specified without an MB, KB, or % suffix, the
default is MB.
If growth_increment is NULL, the default value is 10%, and the minimum value is 64 KB. The size specified is
rounded to the nearest 64 KB.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Permissions
Execute permissions default to members of the sysadmin fixed server role. These permissions are not transferable.

Examples
In the following example, database db1 was marked suspect during recovery due to insufficient space (error 1105)
in file group fg1 .

USE master;
GO
EXEC sp_add_data_file_recover_suspect_db db1, fg1, file2,
'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\db1_file2.mdf', '1MB';

See Also
ALTER DATABASE (Transact-SQL)
sp_add_log_file_recover_suspect_db (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addextendedproc (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Registers the name of a new extended stored procedure to Microsoft SQL Server.

NOTE
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use CLR Integration instead.

Transact-SQL Syntax Conventions

Syntax
sp_addextendedproc [ @functname = ] 'procedure' ,
[ @dllname = ] 'dll'

Arguments
[ @functname = ] 'procedure'
Is the name of the function to call within the dynamic-link library (DLL). procedure is nvarchar(517), with no
default. procedure optionally can include the owner name in the form owner.function.
[ @dllname = ] 'dll'
Is the name of the DLL that contains the function. dll is varchar(255), with no default. It is recommended that you
specify the complete path of the DLL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
After an extended stored procedure is created, it must be added to SQL Server by using sp_addextendedproc.
For more information, see Adding an Extended Stored Procedure to SQL Server.
This procedure can be run only in the master database. To execute an extended stored procedure from a database
other than master, qualify the name of the extended stored procedure with master.
sp_addextendedproc adds entries to the sys.objects catalog view, registering the name of the new extended
stored procedure with SQL Server. It also adds an entry in the sys.extended_procedures catalog view.
IMPORTANT
Existing DLLs that were not registered with a complete path will not work after upgrading to SQL Server 2017. To correct the
problem, use sp_dropextendedproc to unregister the DLL, and then reregister it with sp_addextendedproc, specifying
the complete path.

Permissions
Only members of the sysadmin fixed server role can execute sp_addextendedproc.

Examples
The following example adds the xp_hello extended stored procedure.

USE master;
GO
EXEC sp_addextendedproc xp_hello, 'c:\xp_hello.dll';

See Also
EXECUTE (Transact-SQL)
GRANT (Transact-SQL)
REVOKE (Transact-SQL)
sp_dropextendedproc (Transact-SQL)
sp_helpextendedproc (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addextendedproperty (Transact-SQL)
11/21/2017 • 6 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a new extended property to a database object.
Transact-SQL Syntax Conventions

Syntax
sp_addextendedproperty
[ @name = ] { 'property_name' }
[ , [ @value = ] { 'value' }
[ , [ @level0type = ] { 'level0_object_type' }
, [ @level0name = ] { 'level0_object_name' }
[ , [ @level1type = ] { 'level1_object_type' }
, [ @level1name = ] { 'level1_object_name' }
[ , [ @level2type = ] { 'level2_object_type' }
, [ @level2name = ] { 'level2_object_name' }
]
]
]
]
[;]

Arguments
[ @name ] = { 'property_name' }
Is the name of the property to be added. property_name is sysname and cannot be NULL. Names can also include
blank or non-alphanumeric character strings, and binary values.
[ @value= ] { 'value'}
Is the value to be associated with the property. value is sql_variant, with a default of NULL. The size of value
cannot be more than 7,500 bytes.
[ @level0type= ] { 'level0_object_type' }
Is the type of level 0 object. level0_object_type is varchar(128), with a default of NULL.
Valid inputs are ASSEMBLY, CONTRACT, EVENT NOTIFICATION, FILEGROUP, MESSAGE TYPE, PARTITION
FUNCTION, PARTITION SCHEME, REMOTE SERVICE BINDING, ROUTE, SCHEMA, SERVICE, USER, TRIGGER, TYPE,
PLAN GUIDE, and NULL.

IMPORTANT
The ability to specify USER as a level 0 type in an extended property of a level 1 type object will be removed in a future
version of SQL Server. Use SCHEMA as the level 0 type instead. For example, when defining an extended property on a table,
specify the schema of the table instead of a user name. The ability to specify TYPE as level-0 type will be removed in a future
version of SQL Server. For TYPE, use SCHEMA as the level 0 type and TYPE as the level 1 type.

[ @level0name= ] { 'level0_object_name' }
Is the name of the level 0 object type specified. level0_object_name is sysname with a default of NULL.
[ @level1type= ] { 'level1_object_type' }
Is the type of level 1 object. level1_object_type is varchar(128), with a default of NULL. Valid inputs are
AGGREGATE, DEFAULT, FUNCTION, LOGICAL FILE NAME, PROCEDURE, QUEUE, RULE, SYNONYM, TABLE,
TABLE_TYPE, TYPE, VIEW, XML SCHEMA COLLECTION, and NULL.
[ @level1name= ] { 'level1_object_name' }
Is the name of the level 1 object type specified. level1_object_name is sysname, with a default of NULL.
[ @level2type= ] { 'level2_object_type' }
Is the type of level 2 object. level2_object_type is varchar(128), with a default of NULL. Valid inputs are COLUMN,
CONSTRAINT, EVENT NOTIFICATION, INDEX, PARAMETER, TRIGGER, and NULL.
[ @level2name= ] { 'level2_object_name' }
Is the name of the level 2 object type specified. level2_object_name is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
For specifying extended properties, the objects in a SQL Server database are classified into three levels: 0, 1, and 2.
Level 0 is the highest level and is defined as objects that are contained at the database scope. Level 1 objects are
contained in a schema or user scope, and level 2 objects are contained by level 1 objects. Extended properties can
be defined for objects at any of these levels.
References to an object in one level must be qualified with the names of the higher level objects that own or
contain them. For example, when you add an extended property to a table column (level 2), you must also specify
the table name (level 1) that contains the column and the schema (level 0) that contains the table.
If all object types and names are null, the property belongs to the current database itself.
Extended properties are not allowed on system objects, objects outside the scope of a user-defined database, or
objects not listed in Arguments as valid inputs.
Extended properties are not allowed on memory-optimized tables.

Replicating Extended Properties


Extended properties are replicated only in the initial synchronization between the Publisher and the Subscriber. If
you add or modify an extended property after the initial synchronization, the change is not replicated. For more
information about how to replicate database objects, see Publish Data and Database Objects.

Schema vs. User


We do not recommend specifying USER as a level 0 type when you apply an extended property to a database
object, because this can cause name resolution ambiguity. For example, assume user Mary owns two schemas
(Mary and MySchema) and these schemas both contain a table named MyTable. If Mary adds an extended property
to table MyTable and specifies @level0type = N'USER', @level0name = Mary, it is not clear to which table the
extended property is applied. To maintain backward compatibility, SQL Server will apply the property to the table
that is contained in the schema named Mary.

Permissions
Members of the db_owner and db_ddladmin fixed database roles can add extended properties to any object with
the following exception: db_ddladmin cannot add properties to the database itself, or to users or roles.
Users can add extended properties to objects they own or have ALTER or CONTROL permissions on.

Examples
A. Adding an extended property to a database
The following example adds the property name 'Caption' with a value of
'AdventureWorks2012 Sample OLTP Database' to the AdventureWorks2012 sample database.

USE AdventureWorks2012;
GO
--Add a caption to the AdventureWorks2012 Database object itself.
EXEC sp_addextendedproperty
@name = N'Caption',
@value = 'AdventureWorks2012 Sample OLTP Database';

B. Adding an extended property to a column in a table


The following example adds a caption property to column PostalCode in table Address .

USE AdventureWorks2012;
GO
EXEC sp_addextendedproperty
@name = N'Caption',
@value = 'Postal code is a required column.',
@level0type = N'Schema', @level0name = 'Person',
@level1type = N'Table', @level1name = 'Address',
@level2type = N'Column', @level2name = 'PostalCode';
GO

C. Adding an input mask property to a column


The following example adds an input mask property ' 99999 or 99999-9999 or #### ### ' to the column PostalCode
in the table Address .

USE AdventureWorks2012;
GO
EXEC sp_addextendedproperty
@name = N'Input Mask ', @value = '99999 or 99999-9999 or #### ###',
@level0type = N'Schema', @level0name = 'Person',
@level1type = N'Table', @level1name = 'Address',
@level2type = N'Column',@level2name = 'PostalCode';
GO

D. Adding an extended property to a filegroup


The following example adds an extended property to the PRIMARY filegroup.

USE AdventureWorks2012;
GO
EXEC sys.sp_addextendedproperty
@name = N'MS_DescriptionExample',
@value = N'Primary filegroup for the AdventureWorks2012 sample database.',
@level0type = N'FILEGROUP', @level0name = 'PRIMARY';
GO

E. Adding an extended property to a schema


The following example adds an extended property to the HumanResources schema.

USE AdventureWorks2012;
GO
EXECUTE sys.sp_addextendedproperty
@name = N'MS_DescriptionExample',
@value = N'Contains objects related to employees and departments.',
@level0type = N'SCHEMA',
@level0name = 'HumanResources';

F. Adding an extended property to a table


The following example adds an extended property to the Address table in the Person schema.

USE AdventureWorks2012;
GO
EXEC sys.sp_addextendedproperty
@name = N'MS_DescriptionExample',
@value = N'Street address information for customers, employees, and vendors.',
@level0type = N'SCHEMA', @level0name = 'Person',
@level1type = N'TABLE', @level1name = 'Address';
GO

G. Adding an extended property to a role


The following example creates an application role and adds an extended property to the role.

USE AdventureWorks2012;
GO
CREATE APPLICATION ROLE Buyers
WITH Password = '987G^bv876sPY)Y5m23';
GO
EXEC sys.sp_addextendedproperty
@name = N'MS_Description',
@value = N'Application Role for the Purchasing Department.',
@level0type = N'USER',
@level0name = 'Buyers';

H. Adding an extended property to a type


The following example adds an extended property to a type.

USE AdventureWorks2012;
GO
EXEC sys.sp_addextendedproperty
@name = N'MS_Description',
@value = N'Data type (alias) to use for any column that represents an order number. For example a sales order
number or purchase order number.',
@level0type = N'SCHEMA',
@level0name = N'dbo',
@level1type = N'TYPE',
@level1name = N'OrderNumber';

I. Adding an extended property to a user


The following example creates a user and adds an extended property to the user.
USE AdventureWorks2012;
GO
CREATE USER CustomApp WITHOUT LOGIN ;
GO
EXEC sys.sp_addextendedproperty
@name = N'MS_Description',
@value = N'User for an application.',
@level0type = N'USER',
@level0name = N'CustomApp';

See Also
Database Engine Stored Procedures (Transact-SQL)
sys.fn_listextendedproperty (Transact-SQL)
sp_dropextendedproperty (Transact-SQL)
sp_updateextendedproperty (Transact-SQL)
sp_add_log_file_recover_suspect_db (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a log file to a file group when recovery cannot complete on a database due to insufficient log space (error
9002). After the file is added, sp_add_log_file_recover_suspect_db turns off the suspect setting and completes
the recovery of the database. The parameters are the same as those for ALTER DATABASE database_name ADD
LOG FILE.
Transact-SQL Syntax Conventions

Syntax
sp_add_log_file_recover_suspect_db [ @dbName= ] 'database' ,
[ @name = ] 'logical_file_name' ,
[ @filename= ] 'os_file_name' ,
[ @size = ] 'size' ,
[ @maxsize = ] 'max_size' ,
[ @filegrowth = ] 'growth_increment'

Arguments
[ @dbName = ] 'database'
Is the name of the database. database is sysname, with no default.
[ @name= ] 'logical_file_name'
Is the name used in the SQL Server when referencing the file. The name must be unique in the server.
logical_file_name is nvarchar(260), with no default.
[ @filename = ] 'os_file_name'
Is the path and file name used by the operating system for the file. The file must reside in the server in which the
Database Engine is installed. os_file_name is nvarchar(260), with no default.
[ @size= ] 'size '
Is the initial size of the file. size is nvarchar(20), with a default of NULL. Specify a whole number; do not include a
decimal. The MB and KB suffixes can be used to specify megabytes or kilobytes. The default is MB. The minimum
value is 512 KB. If size is not specified, the default is 1 MB.
[ @maxsize= ] 'max_size '
Is the maximum size to which the file can grow. max_size is nvarchar(20), with a default of NULL. Specify a whole
number; do not include a decimal. The MB and KB suffixes can be used to specify megabytes or kilobytes. The
default is MB.
If max_size is not specified, the file will grow until the disk is full. The Microsoft Windows application log warns an
administrator when a disk is about to become full.
[ @filegrowth= ] 'growth_increment '
Is the amount of space added to the file each time new space is required. growth_increment is nvarchar(20), with
a default of NULL. A value of 0 indicates no growth. Specify a whole number; do not include a decimal. The value
can be specified in MB, KB, or percent (%). When % is specified, the growth increment is the specified percentage of
the size of the file at the time the increment occurs. If a number is specified without an MB, KB, or % suffix, the
default is MB.
If growth_increment is NULL, the default value is 10%, and the minimum size value is 64 KB. The size specified is
rounded to the nearest 64 KB.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Permissions
Execute permissions default to members of the sysadmin fixed server role. These permissions are not transferable.

Examples
In the following example, the database db1 was marked suspect during recovery due to insufficient log space
(error 9002).

USE master;
GO
EXEC sp_add_log_file_recover_suspect_db db1, logfile2,
'C:\Program Files\Microsoft SQL
Server\MSSQL13.MSSQLSERVER\MSSQL\Data\db1_logfile2.ldf',
'1MB';

See Also
ALTER DATABASE (Transact-SQL)
sp_add_data_file_recover_suspect_db (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addmessage (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Stores a new user-defined error message in an instance of the SQL Server Database Engine. Messages stored by
using sp_addmessage can be viewed by using the sys.messages catalog view.
Transact-SQL Syntax Conventions

Syntax
sp_addmessage [ @msgnum= ] msg_id , [ @severity= ] severity , [ @msgtext= ] 'msg'
[ , [ @lang= ] 'language' ]
[ , [ @with_log= ] { 'TRUE' | 'FALSE' } ]
[ , [ @replace= ] 'replace' ]

Arguments
[ @msgnum= ] msg_id
Is the ID of the message. msg_id is int with a default of NULL. msg_id for user-defined error messages can be an
integer between 50,001 and 2,147,483,647. The combination of msg_id and language must be unique; an error is
returned if the ID already exists for the specified language.
[ @severity = ]severity
Is the severity level of the error. severity is smallint with a default of NULL. Valid levels are from 1 through 25. For
more information about severities, see Database Engine Error Severities.
[ @msgtext = ] 'msg'
Is the text of the error message. msg is nvarchar(255) with a default of NULL.
[ @lang = ] 'language'
Is the language for this message. language is sysname with a default of NULL. Because multiple languages can be
installed on the same server, language specifies the language in which each message is written. When language is
omitted, the language is the default language for the session.
[ @with_log = ] { 'TRUE' | 'FALSE' }
Is whether the message is to be written to the Windows application log when it occurs. @with_log is varchar(5)
with a default of FALSE. If TRUE, the error is always written to the Windows application log. If FALSE, the error is
not always written to the Windows application log but can be written, depending on how the error was raised.
Only members of the sysadmin server role can use this option.

NOTE
If a message is written to the Windows application log, it is also written to the Database Engine error log file.

[ @replace = ] 'replace'
If specified as the string replace, an existing error message is overwritten with new message text and severity level.
replace is varchar(7) with a default of NULL. This option must be specified if msg_id already exists. If you replace a
U.S. English message, the severity level is replaced for all messages in all other languages that have the same
msg_id.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
For non-English versions of SQL Server, the U.S. English version of a message must already exist before the
message can be added using another language. The severity of the two versions of the message must match.
When localizing messages that contain parameters, use parameter numbers that correspond to the parameters in
the original message. Insert an exclamation point (!) after each parameter number.

ORIGINAL MESSAGE LOCALIZED MESSAGE

'Original message param 1: %s, 'Localized message param 1: %1!,

param 2: %d' param 2: %2!'

Because of language syntax differences, the parameter numbers in the localized message may not occur in the
same sequence as in the original message.

Permissions
Requires membership in the sysadmin or serveradmin fixed server roles.

Examples
A. Defining a custom message
The following example adds a custom message to sys.messages.

USE master;
GO
EXEC sp_addmessage 50001, 16,
N'Percentage expects a value between 20 and 100.
Please reexecute with a more appropriate value.';
GO

B. Adding a message in two languages


The following example first adds a message in U.S. English and then adds the same message in French .
USE master;
GO
EXEC sp_addmessage @msgnum = 60000, @severity = 16,
@msgtext = N'The item named %s already exists in %s.',
@lang = 'us_english';

EXEC sp_addmessage @msgnum = 60000, @severity = 16,


@msgtext = N'L''élément nommé %1! existe déjà dans %2!',
@lang = 'French';
GO

C. Changing the order of parameters


The following example first adds a message in U.S. English, and then adds a localized message in which the
parameter order is changed.

USE master;
GO

EXEC sp_addmessage
@msgnum = 60000,
@severity = 16,
@msgtext =
N'This is a test message with one numeric
parameter (%d), one string parameter (%s),
and another string parameter (%s).',
@lang = 'us_english';

EXEC sp_addmessage
@msgnum = 60000,
@severity = 16,
@msgtext =
-- In the localized version of the message,
-- the parameter order has changed. The
-- string parameters are first and second
-- place in the message, and the numeric
-- parameter is third place.
N'Dies ist eine Testmeldung mit einem
Zeichenfolgenparameter (%3!),
einem weiteren Zeichenfolgenparameter (%2!),
und einem numerischen Parameter (%1!).',
@lang = 'German';
GO

-- Changing the session language to use the U.S. English


-- version of the error message.
SET LANGUAGE us_english;
GO

RAISERROR(60000,1,1,15,'param1','param2') -- error, severity, state,


GO -- parameters.

-- Changing the session language to use the German


-- version of the error message.
SET LANGUAGE German;
GO

RAISERROR(60000,1,1,15,'param1','param2'); -- error, severity, state,


GO -- parameters.

See Also
RAISERROR (Transact-SQL)
sp_altermessage (Transact-SQL)
sp_dropmessage (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addtype (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates an alias data type.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use CREATE TYPE instead.

Transact-SQL Syntax Conventions

Syntax
sp_addtype [ @typename = ] type,
[ @phystype = ] system_data_type
[ , [ @nulltype = ] 'null_type' ] ;

Arguments
[ @typename= ] type
Is the name of the alias data type. Alias data type names must follow the rules for identifiers and must be unique in
each database. type is sysname, with no default.
[ @phystype=] system_data_type
Is the physical, or SQL Server supplied, data type on which the alias data type is based.system_data_type is
sysname, with no default, and can be one of these values:

bigint binary(n) bit

char(n) datetime decimal

float image int

money nchar(n) ntext

numeric nvarchar(n) real

smalldatetime smallint smallmoney

sql_variant text tinyint

uniqueidentifier varbinary(n) varchar(n)

Quotation marks are required around all parameters that have embedded blank spaces or punctuation marks. For
more information about available data types, see Data Types (Transact-SQL).
n
Is a nonnegative integer that indicates the length for the chosen data type.
P
Is a nonnegative integer that indicates the maximum total number of decimal digits that can be stored, both to the
left and to the right of the decimal point. For more information, see decimal and numeric (Transact-SQL).
s
Is a nonnegative integer that indicates the maximum number of decimal digits that can be stored to the right of the
decimal point, and it must be less than or equal to the precision. For more information, see decimal and numeric
(Transact-SQL).
[ @nulltype = ] 'null_type'
Indicates the way the alias data type handles null values. null_type is varchar(8), with a default of NULL, and must
be enclosed in single quotation marks ('NULL', 'NOT NULL', or 'NONULL'). If null_type is not explicitly defined by
sp_addtype, it is set to the current default nullability. Use the GETANSINULL system function to determine the
current default nullability. This can be adjusted by using the SET statement or ALTER DATABASE. Nullability should
be explicitly defined. If @phystype is bit, and @nulltype is not specified, the default is NOT NULL.

NOTE
The null_type parameter only defines the default nullability for this data type. If nullability is explicitly defined when the alias
data type is used during table creation, it takes precedence over the defined nullability. For more information, see ALTER
TABLE (Transact-SQL) and CREATE TABLE (Transact-SQL).

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
An alias data type name must be unique in the database, but alias data types with different names can have the
same definition.
Executing sp_addtype creates an alias data type that appears in the sys.types catalog view for a specific database.
If the alias data type must be available in all new user-defined databases, add it to model. After an alias data type
is created, you can use it in CREATE TABLE or ALTER TABLE, and also bind defaults and rules to the alias data type.
All scalar alias data types that are created by using sp_addtype are contained in the dbo schema.
Alias data types inherit the default collation of the database. The collations of columns and variables of alias types
are defined in the Transact-SQL CREATE TABLE, ALTER TABLE and DECLARE @local_variable statements. Changing
the default collation of the database applies only to new columns and variables of the type; it does not change the
collation of existing ones.
IMPORTANT
For backward compatibility purposes, the public database role is automatically granted REFERENCES permission on alias
data types that are created by using sp_addtype. Note when alias data types are created by using the CREATE TYPE
statement instead of sp_addtype, no such automatic grant occurs.

Alias data types cannot be defined by using the SQL Server timestamp, table, xml, varchar(max),
nvarchar(max) or varbinary(max) data types.

Permissions
Requires membership in the db_owner or db_ddladmin fixed database role.

Examples
A. Creating an alias data type that does not allow for null values
The following example creates an alias data type named ssn (social security number) that is based on the SQL
Server-supplied varchar data type. The ssn data type is used for columns holding 11-digit social security
numbers (999-99-9999). The column cannot be NULL.
Notice that varchar(11) is enclosed in single quotation marks because it contains punctuation (parentheses).

USE master;
GO
EXEC sp_addtype ssn, 'varchar(11)', 'NOT NULL';
GO

B. Creating an alias data type that allows for null values


The following example creates an alias data type (based on datetime ) named birthday that allows for null values.

USE master;
GO
EXEC sp_addtype birthday, datetime, 'NULL';

C. Creating additional alias data types


The following example creates two additional alias data types, telephone and fax , for both domestic and
international telephone and fax numbers.

USE master;
GO
EXEC sp_addtype telephone, 'varchar(24)', 'NOT NULL';
GO
EXEC sp_addtype fax, 'varchar(24)', 'NULL';
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
CREATE TYPE (Transact-SQL)
CREATE DEFAULT (Transact-SQL)
CREATE RULE (Transact-SQL)
sp_bindefault (Transact-SQL)
sp_bindrule (Transact-SQL)
sp_droptype (Transact-SQL)
sp_rename (Transact-SQL)
sp_unbindefault (Transact-SQL)
sp_unbindrule (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addumpdevice (Transact-SQL)
11/17/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Applies to: SQL Server ( SQL Server 2008 through current version).
Adds a backup device to an instance of SQL Server.
Transact-SQL Syntax Conventions

Syntax
sp_addumpdevice [ @devtype = ] 'device_type'
, [ @logicalname = ] 'logical_name'
, [ @physicalname = ] 'physical_name'
[ , { [ @cntrltype = ] controller_type |
[ @devstatus = ] 'device_status' }
]

Arguments
[ @devtype= ] 'device_type'
Is the type of backup device. device_type is varchar(20), with no default, and can be one of the following values.

VALUE DESCRIPTION

disk Hard disk file as a backup device.

tape Any tape devices supported by Microsoft Windows.

Note: Support for tape backup devices will be removed in a


future version of SQL Server. Avoid using this feature in new
development work, and plan to modify applications that
currently use this feature.

[ @logicalname = ] 'logical_name'
Is the logical name of the backup device used in the BACKUP and RESTORE statements. logical_name is sysname,
with no default, and cannot be NULL.
[ @physicalname = ] 'physical_name'
Is the physical name of the backup device. Physical names must follow the rules for operating-system file names or
universal naming conventions for network devices, and must include a full path. physical_name is nvarchar(260),
with no default value, and cannot be NULL.
When creating a backup device on a remote network location, be sure that the name under which the Database
Engine was started has appropriate write capabilities on the remote computer.
If you add a tape device, this parameter must be the physical name assigned to the local tape device by Windows;
for example, \\.\TAPE0 for the first tape device on the computer. The tape device must be attached to the server
computer; it cannot be used remotely. Enclose names that contain nonalphanumeric characters in quotation marks.
NOTE
This procedure enters the specified physical name into the catalog. The procedure does not attempt to access or create the
device.

[ @cntrltype = ] 'controller_type'
Obsolete. If specified, this parameter is ignored. It is supported purely for backward compatibility. New uses of
sp_addumpdevice should omit this parameter.
[ @devstatus = ] 'device_status'
Obsolete. If specified, this parameter is ignored. It is supported purely for backward compatibility. New uses of
sp_addumpdevice should omit this parameter.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_addumpdevice adds a backup device to the sys.backup_devices catalog view. The device can then be
referred to logically in BACKUP and RESTORE statements. sp_addumpdevice does not perform any access to the
physical device. Access to the specified device only occurs when a BACKUP or RESTORE statement is performed.
Creating a logical backup device can simplify BACKUP and RESTORE statements, where specifying the device name
is an alternative using a "TAPE =" or "DISK =" clause to specify the device path.
Ownership and permissions problems can interfere with the use of disk or file backup devices. Make sure that
appropriate file permissions are given to the Windows account under which the Database Engine was started.
The Database Engine supports tape backups to tape devices that are supported by Windows. For more information
about Windows-supported tape devices, see the hardware compatibility list for Windows. To view the tape devices
available on the computer, use SQL Server Management Studio.
Use only the recommended tapes for the specific tape drive that are suggested by the drive manufacturer. If you
are using digital audio tape (DAT) drives, use computer-grade DAT tapes (Digital Data Storage (DDS)).
sp_addumpdevice cannot be executed inside a transaction.
To delete a device, use sp_dropdevice orSQL Server Management Studio.

Permissions
Requires membership in the diskadmin fixed server role.
Requires permission to write to the disk.

Examples
A. Adding a disk dump device
The following example adds a disk backup device named mydiskdump , with the physical name c:\dump\dump1.bak .
USE master;
GO
EXEC sp_addumpdevice 'disk', 'mydiskdump', 'c:\dump\dump1.bak';

B. Adding a network disk backup device


The following example shows adding a remote disk backup device called networkdevice . The name under which
the Database Engine was started must have permissions to that remote file (
\\<servername>\<sharename>\<path>\<filename>.bak ).

USE master;
GO
EXEC sp_addumpdevice 'disk', 'networkdevice',
'\\<servername>\<sharename>\<path>\<filename>.bak';

C. Adding a tape backup device


The following example adds the tapedump1 device with the physical name \\.\tape0 .

USE master;
GO
EXEC sp_addumpdevice 'tape', 'tapedump1', '\\.\tape0';

D. Backing up to a logical backup device


The following example creates a logical backup device, AdvWorksData , for a backup disk file. The example then
backs up the AdventureWorks2012 database to this logical backup device.

USE master;
GO
EXEC sp_addumpdevice 'disk', 'AdvWorksData',
'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\BACKUP\AdvWorksData.bak';
GO
BACKUP DATABASE AdventureWorks2012
TO AdvWorksData
WITH FORMAT;
GO

See Also
Backup Devices (SQL Server)
BACKUP (Transact-SQL)
Define a Logical Backup Device for a Disk File (SQL Server)
Define a Logical Backup Device for a Tape Drive (SQL Server)
RESTORE (Transact-SQL)
sp_dropdevice (Transact-SQL)
sys.backup_devices (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_altermessage (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Alters the state of user-defined or system messages in an instance of the SQL Server Database Engine. User-
defined messages can be viewed using the sys.messages catalog view.
Transact-SQL Syntax Conventions

Syntax
sp_altermessage [ @message_id = ] message_number ,[ @parameter = ]'write_to_log'
,[ @parameter_value = ]'value'

Arguments
[@message_id = ] message_number
Is the error number of the message to alter from sys.messages. message_number is int with no default value.
[ @parameter = ] 'write_to_log'
Is used with @parameter_value to indicate that the message is to be written to the Microsoft Windows
application log. write_to_log is sysname with no default value. write_to_log must be set to WITH_LOG or NULL. If
write_to_log is set to WITH_LOG or NULL, and the value for @parameter_value is true, the message is written to
the Windows application log. If write_to_log is set to WITH_LOG or NULL and the value for @parameter_value is
false, the message is not always written to the Windows application log, but may be written depending upon how
the error was raised. If write_to_log is specified, the value for @parameter_value must also be specified.

NOTE
If a message is written to the Windows application log, it is also written to the Database Engine error log file.

[ @parameter_value = ]'value'
Is used with @parameter to indicate that the error is to be written to the Microsoft Windows application log.
value is varchar(5), with no default value. If true, the error is always written to the Windows application log. If
false, the error is not always written to the Windows application log, but may be written depending upon how the
error was raised. If value is specified, write_to_log for @parameter must also be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
The effect of sp_altermessage with the WITH_LOG option is similar to that of the RAISERROR WITH LOG
parameter, except that sp_altermessage changes the logging behavior of an existing message. If a message has
been altered to be WITH_LOG, it is always written to the Windows application log, regardless of how a user
invokes the error. Even if RAISERROR is executed without the WITH_LOG option, the error is written to the
Windows application log.
System messages can be modified by using sp_altermessage.

Permissions
Requires membership in the serveradmin fixed server role.

Examples
The following example causes existing message 55001 to be logged to the Windows application log.

EXECUTE sp_altermessage 55001, 'WITH_LOG', 'true';


GO

See Also
RAISERROR (Transact-SQL)
sp_addmessage (Transact-SQL)
sp_dropmessage (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_attach_db (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Attaches a database to a server.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. We recommend that you use CREATE DATABASE
database_name FOR ATTACH instead. For more information, see CREATE DATABASE (SQL Server Transact-SQL).

NOTE
To rebuild multiple log files when one or more have a new location, use CREATE DATABASE database_name FOR
ATTACH_REBUILD_LOG.

IMPORTANT
We recommend that you do not attach or restore databases from unknown or untrusted sources. Such databases could
contain malicious code that might execute unintended Transact-SQL code or cause errors by modifying the schema or the
physical database structure. Before you use a database from an unknown or untrusted source, run DBCC CHECKDB on the
database on a nonproduction server and also examine the code, such as stored procedures or other user-defined code, in the
database.

Syntax
sp_attach_db [ @dbname= ] 'dbname'
, [ @filename1= ] 'filename_n' [ ,...16 ]

Arguments
[ @dbname= ] 'dbnam '
Is the name of the database to be attached to the server. The name must be unique. dbname is sysname, with a
default of NULL.
[ @filename1= ] 'filename_n'
Is the physical name, including path, of a database file. filename_n is nvarchar(260), with a default of NULL. Up to
16 file names can be specified. The parameter names start at @filename1 and increment to @filename16. The
file name list must include at least the primary file. The primary file contains the system tables that point to other
files in the database. The list must also include any files that were moved after the database was detached.
NOTE
This argument maps to the FILENAME parameter of the CREATE DATABASE statement. For more information, see CREATE
DATABASE (SQL Server Transact-SQL).
When you attach a SQL Server 2005 database that contains full-text catalog files onto a SQL Server 2017 server instance, the
catalog files are attached from their previous location along with the other database files, the same as in SQL Server 2005.
For more information, see Upgrade Full-Text Search.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
The sp_attach_db stored procedure should only be executed on databases that were previously detached from the
database server by using an explicit sp_detach_db operation or on copied databases. If you have to specify more
than 16 files, use CREATE DATABASE database_name FOR ATTACH or CREATE DATABASE database_name
FOR_ATTACH_REBUILD_LOG. For more information, see CREATE DATABASE (SQL Server Transact-SQL).
Any unspecified file is assumed to be in its last known location. To use a file in a different location, you must specify
the new location.
A database created by a more recent version of SQL Server cannot be attached in earlier versions.

NOTE
A database snapshot cannot be detached or attached.

When you attach a replicated database that was copied instead of being detached, consider the following:
If you attach the database to the same server instance and version as the original database, no additional
steps are required.
If you attach the database to the same server instance but with an upgraded version, you must execute
sp_vupgrade_replication to upgrade replication after the attach operation is complete.
If you attach the database to a different server instance, regardless of version, you must execute
sp_removedbreplication to remove replication after the attach operation is complete.
When a database is first attached or restored to a new instance of SQL Server, a copy of the database master
key (encrypted by the service master key) is not yet stored in the server. You must use the OPEN MASTER
KEY statement to decrypt the database master key (DMK). Once the DMK has been decrypted, you have the
option of enabling automatic decryption in the future by using the ALTER MASTER KEY REGENERATE
statement to provision the server with a copy of the DMK, encrypted with the service master key (SMK).
When a database has been upgraded from an earlier version, the DMK should be regenerated to use the
newer AES algorithm. For more information about regenerating the DMK, see ALTER MASTER KEY (Transact-
SQL). The time required to regenerate the DMK key to upgrade to AES depends upon the number of objects
protected by the DMK. Regenerating the DMK key to upgrade to AES is only necessary once, and has no
impact on future regenerations as part of a key rotation strategy.
Permissions
For information about how permissions are handled when a database is attached, see CREATE DATABASE (SQL
Server Transact-SQL).

Examples
The following example attaches files from AdventureWorks2012 to the current server.

EXEC sp_attach_db @dbname = N'AdventureWorks2012',


@filename1 =
N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\AdventureWorks2012_Data.mdf',
@filename2 =
N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\AdventureWorks2012_log.ldf';

See Also
Database Detach and Attach (SQL Server)
sp_detach_db (Transact-SQL)
sp_helpfile (Transact-SQL)
sp_removedbreplication (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_attach_single_file_db (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Attaches a database that has only one data file to the current server. sp_attach_single_file_db cannot be used
with multiple data files.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. We recommend that you use CREATE DATABASE
database_name FOR ATTACH instead. For more information, see CREATE DATABASE (SQL Server Transact-SQL). Do not use
this procedure on a replicated database.

IMPORTANT
We recommend that you do not attach or restore databases from unknown or untrusted sources. Such databases could
contain malicious code that might execute unintended Transact-SQL code or cause errors by modifying the schema or the
physical database structure. Before you use a database from an unknown or untrusted source, run DBCC CHECKDB on the
database on a nonproduction server and also examine the code, such as stored procedures or other user-defined code, in the
database.

Transact-SQL Syntax Conventions

Syntax
sp_attach_single_file_db [ @dbname= ] 'dbname'
, [ @physname= ] 'physical_name'

Arguments
[ @dbname= ] 'dbname'
Is the name of the database to be attached to the server. The name must be unique. dbname is sysname, with a
default of NULL.
[ @physname= ] 'physical_name'
Is the physical name, including path, of the database file. physical_name is nvarchar(260), with a default of NULL.

NOTE
This argument maps to the FILENAME parameter of the CREATE DATABASE statement. For more information, see CREATE
DATABASE (SQL Server Transact-SQL).

When you attach a SQL Server 2005 database that contains full-text catalog files onto a SQL Server 2017 server
instance, the catalog files are attached from their previous location along with the other database files, the same as
in SQL Server 2005. For more information, see Upgrade Full-Text Search.
Return Code Values
0 (success) or 1 (failure)

Result Sets
None

Remarks
Use sp_attach_single_file_db only on databases that were previously detached from the server by using an
explicit sp_detach_db operation or on copied databases.
sp_attach_single_file_db works only on databases that have a single log file. When sp_attach_single_file_db
attaches the database to the server, it builds a new log file. If the database is read-only, the log file is built in its
previous location.

NOTE
A database snapshot cannot be detached or attached.

Do not use this procedure on a replicated database.

Permissions
For information about how permissions are handled when a database is attached, see CREATE DATABASE (SQL
Server Transact-SQL).

Examples
The following example detaches AdventureWorks2012 and then attaches one file from AdventureWorks2012 to
the current server.

USE master;
GO
EXEC sp_detach_db @dbname = 'AdventureWorks2012';
EXEC sp_attach_single_file_db @dbname = 'AdventureWorks2012',
@physname =
N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\AdventureWorks2012_Data.mdf';

See Also
Database Detach and Attach (SQL Server)
sp_detach_db (Transact-SQL)
sp_helpfile (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_autostats (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Displays or changes the automatic statistics update option, AUTO_UPDATE_STATISTICS, for an index, a statistics
object, a table, or an indexed view.
For more information about the AUTO_UPDATE_STATISTICS option, see ALTER DATABASE SET Options (Transact-
SQL) and Statistics.
Transact-SQL Syntax Conventions

Syntax
sp_autostats [ @tblname = ] 'table_or_indexed_view_name'
[ , [ @flagc = ] 'stats_value' ]
[ , [ @indname = ] 'statistics_name' ]

Arguments
[ @tblname= ] 'table_or_indexed_view_name'
Is the name of the table or indexed view to display the AUTO_UPDATE_STATISTICS option on.
table_or_indexed_view_name is nvarchar(776), with no default.
[ @flagc= ] 'stats_value'
Updates the AUTO_UPDATE_STATISTICS option to one of these values:
ON = ON
OFF = OFF
When stats_flag is not specified, display the current AUTO_UPDATE_STATISTICS setting. stats_value is varchar(10),
with a default of NULL.
[ @indname= ] 'statistics_name'
Is the name of the statistics to display or update the AUTO_UPDATE_STATISTICS option on. To display the statistics
for an index, you can use the name of the index; an index and its corresponding statistics object have the same
name.
statistics_name is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
If stats_flag is specified, sp_autostats reports the action that was taken but returns no result set.
If stats_flag is not specified, sp_autostats returns the following result set.
COLUMN NAME DATA TYPE DESCRIPTION

Index Name varchar(60) Name of the index or statistics.

AUTOSTATS varchar(3) Current value for the


AUTO_UPDATE_STATISTICS option.

Last Updated datetime Date of the most recent statistics


update.

The result set for a table or indexed view includes statistics created for indexes, single-column statistics generated
with the AUTO_CREATE_STATISTICS option and statistics created with the CREATE STATISTICS statement.

Remarks
If the specified index is disabled, or the specified table has a disabled clustered index, an error message is
displayed.
AUTO_UPDATE_STATISTICS is always OFF for memory-optimized tables.

Permissions
To change the AUTO_UPDATE_STATISTICS option requires membership n the db_owner fixed database role, or
ALTER permission on table_name.To display the AUTO_UPDATE_STATISTICS option requires membership in the
public role.

Examples
A. Display the status of all statistics on a table
The following displays the status of all statistics on the Product table.

USE AdventureWorks2012;
GO
EXEC sp_autostats 'Production.Product';
GO

B. Enable AUTO_UPDATE_STATISTICS for all statistics on a table


The following enables the AUTO_UPDATE_STATISTICS option for all statistics on the Product table.

USE AdventureWorks2012;
GO
EXEC sp_autostats 'Production.Product', 'ON';
GO

C. Disable AUTO_UPDATE_STATISTICS for a specific index


The following example disables the AUTO_UPDATE_STATISTICS option for the AK_Product_Name index on the
Product table.

USE AdventureWorks2012;
GO
EXEC sp_autostats 'Production.Product', 'OFF', AK_Product_Name;
GO
See Also
Statistics
ALTER DATABASE SET Options (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
CREATE STATISTICS (Transact-SQL)
DBCC SHOW_STATISTICS (Transact-SQL)
DROP STATISTICS (Transact-SQL)
sp_createstats (Transact-SQL)
UPDATE STATISTICS (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_batch_params (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a rowset that contains information about the parameters included in a Transact-SQL batch.
sp_batch_params only parses the batch specified and returns information about embedded parameter values. It
does not execute the batch or modify the execution environment.
Transact-SQL Syntax Conventions

Syntax
sp_batch_params [ [ @tsqlbatch = ] 'tsqlbatch' ]

Arguments
[ @tsqlbatch =] 'tsqlbatch'
Is a Unicode string that contains a Transact-SQL statement or batch for which parameter information is that you
want. tsqlbatch is nvarchar(max) or implicitly convertible to nvarchar(max).

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

PARAMETER_NAME sysname Name of the parameter that SQL Server


found in the batch.

COLUMN_TYPE smallint This field returns one of the following


values:

0 = SQL_PARAM_TYPE_UNKNOWN

1 = SQL_PARAM_TYPE_INPUT

2 = SQL_PARAM_TYPE_OUTPUT

3 = SQL_RESULT_COL

4 = SQL_PARAM_OUTPUT

5 = SQL_RETURN_VALUE

This column is always 0.


COLUMN NAME DATA TYPE DESCRIPTION

DATA_TYPE smallint Data type of the parameter (Integer


code for an ODBC data type). If this
data type cannot be mapped to an ISO
type, the value is NULL. The native data
type name is returned in the
TYPE_NAME column. This value is
always NULL.

TYPE_NAME sysname String representation of the data type


as it is presented by the underlying
DBMS. This value is NULL.

PRECISION int Number of significant digits. The return


value for the PRECISION column is in
base 10.

LENGTH int Transfer size of the data. This value is


NULL.

SCALE smallint Number of digits to the right of the


decimal point. This value is NULL.

RADIX smallint Is the base for numeric types. This value


is NULL.

NULLABLE smallint Specifies nullability:

1 = Parameter data type can be created


allowing null values.

0 = Null values are not allowed.

This value is NULL.

SQL_DATA_TYPE smallint Value of the SQL Server system data


type as it appears in the TYPE field of
the descriptor. This column is the same
as the DATA_TYPE column, except for
the datetime and ISO interval data
types. This column always returns a
value. This value is NULL.

SQL_DATETIME_SUB smallint The datetime or ISO interval subcode


if the value of SQL_DATA_TYPE is
SQL_DATETIME or SQL_INTERVAL. For
data types other than datetime and
ISO interval, this column is NULL. This
value is NULL.

CHAR_OCTET_LENGTH int Maximum length in bytes of a


character or binary data type
parameter. For all other data types, this
column returns a NULL. This value is
always NULL.
COLUMN NAME DATA TYPE DESCRIPTION

ORDINAL_POSITION int Ordinal position of the parameter in the


batch. If the parameter name is
repeated multiple times, this column
contains the ordinal of the first
occurrence. The first parameter has
ordinal 1. This column always returns a
value.

Permissions
Permission to execute sp_batch_params is granted to public.

Examples
The following example shows a query being passed to sp_batch_params . The result set enumerates the list of
embedded parameter values.

DECLARE @SQLString nvarchar(500);


/* Build the SQL string */
SET @SQLString =
N'SELECT * FROM AdventureWorks2012.HumanResources.Employee
WHERE BusinessEntityID = @BusinessEntityID';
EXECUTE sp_batch_params @SQLString;

See Also
Running Stored Procedures
Running Stored Procedures How-to Topics (ODBC)
Running Stored Procedures (OLE DB)
sp_bindefault (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Binds a default to a column or to an alias data type.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Do not use this feature in new development work,
and modify applications that currently use this feature as soon as possible. We recommend that you create default
definitions by using the DEFAULT keyword of the ALTER TABLE or CREATE TABLE statements instead.

Transact-SQL Syntax Conventions

Syntax
sp_bindefault [ @defname = ] 'default' ,
[ @objname = ] 'object_name'
[ , [ @futureonly = ] 'futureonly_flag' ]

Arguments
[ @defname= ] 'default'
Is the name of the default that is created by CREATE DEFAULT. default is nvarchar(776), with no default.
[ @objname= ] 'object_name'
Is the name of table and column or the alias data type to which the default is to be bound. object_name is
nvarchar(776) with no default. object_name cannot be defined with the varchar(max), nvarchar(max),
varbinary(max), xml, or CLR user-defined types.
If object_name is a one-part name, it is resolved as an alias data type. If it is a two- or three-part name, it is first
resolved as a table and column; and if this resolution fails, it is resolved as an alias data type. By default, existing
columns of the alias data type inherit default, unless a default has been bound directly to the column. A default
cannot be bound to a text, ntext, image, varchar(max), nvarchar(max), varbinary(max), xml, timestamp, or
CLR user-defined type column, a column with the IDENTITY property, a computed column, or a column that
already has a DEFAULT constraint.

NOTE
object_name can contain brackets [] as delimited identifiers. For more information, see Database Identifiers.

[ @futureonly= ] 'futureonly_flag'
Is used only when binding a default to an alias data type. futureonly_flag is varchar(15) with a default of NULL.
When this parameter is set to futureonly, existing columns of that data type cannot inherit the new default. This
parameter is never used when binding a default to a column. If futureonly_flag is NULL, the new default is bound
to any columns of the alias data type that currently have no default or that are using the existing default of the
alias data type.
Return Code Values
0 (success) or 1 (failure)

Remarks
You can use sp_bindefault to bind a new default to a column, although using the DEFAULT constraint is preferred,
or to an alias data type without unbinding an existing default. The old default is overridden. You cannot bind a
default to a SQL Server system data type or a CLR user-defined type. If the default is not compatible with the
column to which you have bound it, the SQL Server Database Engine returns an error message when it tries to
insert the default value, not when you bind it.
Existing columns of the alias data type inherit the new default, unless either a default is bound directly to them or
futureonly_flag is specified as futureonly. New columns of the alias data type always inherit the default.
When you bind a default to a column, related information is added to the sys.columns catalog view. When you
bind a default to an alias data type, related information is added to the sys.types catalog view.

Permissions
User must own the table, or be a member of the sysadmin fixed server role, or the db_owner and db_ddladmin
fixed database roles.

Examples
A. Binding a default to a column
A default named today has been defined in the current database by using CREATE DEFAULT, the following
example binds the default to the HireDate column of the Employee table. Whenever a row is added to the
Employee table and data for the HireDate column is not supplied, the column gets the value of the default today .

USE master;
GO
EXEC sp_bindefault 'today', 'HumanResources.Employee.HireDate';

B. Binding a default to an alias data type


A default named def_ssn and an alias data type named ssn already exists. The following example binds the
default def_ssn to ssn . When a table is created, the default is inherited by all columns that are assigned the alias
data type ssn . Existing columns of type ssn also inherit the default def_ssn, unless futureonly is specified for
futureonly_flag value, or unless the column has a default bound directly to it. Defaults bound to columns always
take precedence over those bound to data types.

USE master;
GO
EXEC sp_bindefault 'def_ssn', 'ssn';

C. Using the futureonly_flag


The following example binds the default def_ssn to the alias data type ssn . Because futureonly is specified, no
existing columns of type ssn are affected.

USE master;
GO
EXEC sp_bindefault 'def_ssn', 'ssn', 'futureonly';
D. Using delimited identifiers
The following example shows using delimited identifiers, [t.1] , in object_name.

USE master;
GO
CREATE TABLE [t.1] (c1 int);
-- Notice the period as part of the table name.
EXEC sp_bindefault 'default1', '[t.1].c1' ;
-- The object contains two periods;
-- the first is part of the table name,
-- and the second distinguishes the table name from the column name.

See Also
Database Engine Stored Procedures (Transact-SQL)
CREATE DEFAULT (Transact-SQL)
DROP DEFAULT (Transact-SQL)
sp_unbindefault (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_bindrule (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Binds a rule to a column or to an alias data type.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Do not use this feature in new development work,
and modify applications that currently use this feature as soon as possible. UseUnique Constraints and Check Constraints
instead. CHECK constraints are created by using the CHECK keyword of the CREATE TABLE or ALTER TABLE statements.

Transact-SQL Syntax Conventions

Syntax
sp_bindrule [ @rulename = ] 'rule' ,
[ @objname = ] 'object_name'
[ , [ @futureonly = ] 'futureonly_flag' ]

Arguments
[ @rulename=] 'rule'
Is the name of a rule created by the CREATE RULE statement. rule is nvarchar(776), with no default.
[ @objname=] 'object_name'
Is the table and column, or the alias data type to which the rule is to be bound. A rule cannot be bound to a text,
ntext, image, varchar(max), nvarchar(max), varbinary(max), xml, CLR user-defined type, or
timestampcolumn. A rule cannot be bound to a computed column.
object_name is nvarchar(776) with no default. If object_name is a one-part name, it is resolved as an alias data
type. If it is a two- or three-part name, it is first resolved as a table and column; if this resolution fails, it is resolved
as an alias data type. By default, existing columns of the alias data type inherit rule unless a rule has been bound
directly to the column.

NOTE
object_name can contain the bracket [ and ] characters as delimited identifier characters. For more information, see Database
Identifiers.

NOTE
Rules created on expressions that use alias data types can be bound to columns or alias data types, but fail to compile when
they are referenced. Avoid using rules created on alias data types.

[ @futureonly= ] 'futureonly_flag'
Is used only when binding a rule to an alias data type. future_only_flag is varchar(15) with a default of NULL. This
parameter when set to futureonly prevents existing columns of an alias data type from inheriting the new rule. If
futureonly_flag is NULL, the new rule is bound to any columns of the alias data type that currently have no rule or
that are using the existing rule of the alias data type.

Return Code Values


0 (success) or 1 (failure)

Remarks
You can bind a new rule to a column (although using a CHECK constraint is preferred) or to an alias data type with
sp_bindrule without unbinding an existing rule. The old rule is overridden. If a rule is bound to a column with an
existing CHECK constraint, all restrictions are evaluated. You cannot bind a rule to a SQL Server data type.
The rule is enforced when an INSERT statement is tried, not at binding. You can bind a character rule to a column
of numeric data type, although such an INSERT operation is not valid.
Existing columns of the alias data type inherit the new rule unless futureonly_flag is specified as futureonly. New
columns defined with the alias data type always inherit the rule. However, if the ALTER COLUMN clause of an
ALTER TABLE statement changes the data type of a column to an alias data type bound to a rule, the rule bound to
the data type is not inherited by the column. The rule must be specifically bound to the column by using
sp_bindrule.
When you bind a rule to a column, related information is added to the sys.columns table. When you bind a rule to
an alias data type, related information is added to the sys.types table.

Permissions
To bind a rule to a table column, you must have ALTER permission on the table. CONTROL permission on the alias
data type, or ALTER permission on the schema to which the type belongs, is required to bind a rule to an alias data
type.

Examples
A. Binding a rule to a column
Assuming that a rule named today has been created in the current database by using the CREATE RULE
statement, the following example binds the rule to the HireDate column of the Employee table. When a row is
added to Employee , the data for the HireDate column is checked against the today rule.

USE master;
GO
EXEC sp_bindrule 'today', 'HumanResources.Employee.HireDate';

B. Binding a rule to an alias data type


Assuming the existence of a rule named rule_ssn and an alias data type named ssn , the following example binds
rule_ssn to ssn . In a CREATE TABLE statement, columns of type ssn inherit the rule_ssn rule. Existing columns
of type ssn also inherit the rule_ssn rule, unless futureonly is specified for futureonly_flag, or ssn has a rule
bound directly to it. Rules bound to columns always take precedence over those bound to data types.

USE master;
GO
EXEC sp_bindrule 'rule_ssn', 'ssn';
C. Using the futureonly_flag
The following example binds the rule_ssn rule to the alias data type ssn . Because futureonly is specified, no
existing columns of type ssn are affected.

USE master;
GO
EXEC sp_bindrule rule_ssn, 'ssn', 'futureonly';

D. Using delimited identifiers


The following example shows the use of delimited identifiers in object_name parameter.

USE master;
GO
CREATE TABLE [t.2] (c1 int) ;
-- Notice the period as part of the table name.
EXEC sp_bindrule rule1, '[t.2].c1' ;
-- The object contains two periods;
-- the first is part of the table name
-- and the second distinguishes the table name from the column name.

See Also
System Stored Procedures (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
CREATE RULE (Transact-SQL)
DROP RULE (Transact-SQL)
sp_unbindrule (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_bindsession (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Binds or unbinds a session to other sessions in the same instance of the SQL Server Database Engine. Binding
sessions allows two or more sessions to participate in the same transaction and share locks until a ROLLBACK
TRANSACTION or COMMIT TRANSACTION is issued.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use Multiple Active Results Sets (MARS) or distributed
transactions instead. For more information, see Using Multiple Active Result Sets (MARS).

Transact-SQL Syntax Conventions

Syntax
sp_bindsession { 'bind_token' | NULL }

Arguments
' bind_token '
Is the token that identifies the transaction originally obtained by using sp_getbindtoken or the Open Data
Services srv_getbindtoken function. bind_tokenis varchar(255).

Return Code Values


0 (success) or 1 (failure)

Remarks
Two sessions that are bound share only a transaction and locks. Each session retains its own isolation level, and
setting a new isolation level on one session does not affect the isolation level of the other session. Each session
remains identified by its security account and can only access the database resources to which the account has
been granted permission.
sp_bindsession uses a bind token to bind two or more existing client sessions. These client sessions must be on
the same instance of the Database Engine from which the binding token was obtained. A session is a client
executing a command. Bound database sessions share a transaction and lock space.
A bind token obtained from one instance of the Database Engine cannot be used for a client session connected to
another instance, even for DTC transactions. A bind token is valid only locally inside each instance and cannot be
shared across multiple instances. To bind client sessions on another instance of the Database Engine, you must
obtain a different bind token by executing sp_getbindtoken.
sp_bindsession will fail with an error if it uses a token that is not active.
Unbind from a session either by using sp_bindsession without specifying bind_token or by passing NULL in
bind_token.

Permissions
Requires membership in the public role.

Examples
The following example binds the specified bind token to the current session.

NOTE
The bind token shown in the example was obtained by executing sp_getbindtoken before executing sp_bindsession.

USE master;
GO
EXEC sp_bindsession 'BP9---5---->KB?-V'<>1E:H-7U-]ANZ';
GO

See Also
sp_getbindtoken (Transact-SQL)
srv_getbindtoken (Extended Stored Procedure API)
System Stored Procedures (Transact-SQL)
sp_certify_removable (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Verifies that a database is correctly configured for distribution on removable media and reports any problems to
the user.

IMPORTANT!! [!INCLUDEssNoteDepFutureAvoid instead.

Transact-SQL Syntax Conventions

Syntax
sp_certify_removable [ @dbname= ] 'dbname'
[ , [ @autofix = ] 'auto' ]

Arguments
[ @dbname=] 'dbname'
Specifies the database to be verified. dbname is sysname.
[ @autofix=] 'auto'
Gives ownership of the database and all database objects to the system administrator, and drops any user-created
database users and nondefault permissions. auto is nvarchar(4), with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
If the database is correctly configured, sp_certify_removable performs the following:
Sets the database offline so the files can be copied.
Updates statistics on all tables and reports any ownership or user problems
Marks the data filegroups as read-only so these files can be copied to read-only media.
The system administrator must be the owner of the database and all database objects. The system
administrator is a known user that exists on all servers that are running Microsoft SQL Server and can be
expected to exist when the database is later distributed and installed.
If you run sp_certify_removable without the auto value and it returns information about any of the
following conditions:
The system administrator is not the database owner.
Any user-created users exist.
The system administrator does not own all objects in the database.
Nondefault permissions have been granted.
You can correct those conditions in the following ways:
Use SQL Server tools and procedures, and then run sp_certify_removable again.
Just run sp_certify_removable with the auto value.
Note that this stored procedure only checks for users and user permissions. You can add groups to the
database and to grant permissions to those groups. For more information, see GRANT (Transact-SQL).

Permissions
Execute permissions are restricted to members of the sysadmin fixed server role.

Examples
The following example certifies that the inventory database is ready to be removed.

EXEC sp_certify_removable inventory, AUTO;

See Also
Database Detach and Attach (SQL Server)
sp_create_removable (Transact-SQL)
ALTER DATABASE (Transact-SQL)
sp_dbremove (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_clean_db_free_space (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes residual information left on database pages because of data modification routines in SQL Server.
sp_clean_db_free_space cleans all pages in all files of the database.
Transact-SQL Syntax Conventions

Syntax
sp_clean_db_free_space
[ @dbname ] = 'database_name'
[ , [ @cleaning_delay = ] 'delay_in_seconds' ] [;]

Arguments
[ @dbname= ] 'database_name'
Is the name of the database to clean. dbname is sysname and cannot be NULL.
[ @cleaning_delay= ] 'delay_in_seconds'
Specifies an interval to delay between the cleaning of pages. This helps reduce the effect on the I/O system.
delay_in_seconds is int with a default of 0.

Return Code Values


0 (success) or 1 (failure)

Remarks
Delete operations from a table or update operations that cause a row to move can immediately free up space on a
page by removing references to the row. However, under certain circumstances, the row can physically remain on
the data page as a ghost record. Ghost records are periodically removed by a background process. This residual
data is not returned by the Database Engine in response to queries. However, in environments in which the
physical security of the data or backup files is at risk, you can use sp_clean_db_free_space to clean these ghost
records.
The length of time required to run sp_clean_db_free_space depends on the size of the file, the available free space,
and the capacity of the disk. Because running sp_clean_db_free_space can significantly affect I/O activity, we
recommend that you run this procedure outside usual operation hours.
Before you run sp_clean_db_free_space, we recommend that you create a full database backup.
The related sp_clean_db_file_free_space stored procedure can clean a single file.

Permissions
Requires membership in the db_owner database role.
Examples
The following example cleans all residual information from the AdventureWorks2012 database.

USE master;
GO
EXEC sp_clean_db_free_space
@dbname = N'AdventureWorks2012' ;

See Also
Database Engine Stored Procedures (Transact-SQL)
sp_clean_db_file_free_space (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes residual information left on database pages because of data modification routines in SQL Server.
sp_clean_db_file_free_space cleans all pages in only one file of a database.
Transact-SQL Syntax Conventions

Syntax
sp_clean_db_file_free_space
[ @dbname ] = 'database_name'
, @fileid = 'file_number'
[ , [ @cleaning_delay = ] 'delay_in_seconds' ] [;]

Arguments
[ @dbname= ] 'database_name'
Is the name of the database to clean. dbname is sysname and cannot be NULL.
[ @fileid= ] 'file_number'
Is the data file id to clean. file_number is int and cannot be NULL.
[ @cleaning_delay= ] 'delay_in_seconds'
Specifies an interval to delay between the cleaning of pages. This helps reduce the effect on the I/O system.
delay_in_seconds is int with a default of 0.

Return Code Values


0 (success) or 1 (failure)

Remarks
Deletes operations from a table or update operations that cause a row to move can immediately free up space on a
page by removing references to the row. However, under certain circumstances, the row can physically remain on
the data page as a ghost record. Ghost records are periodically removed by a background process. This residual
data is not returned by the Database Engine in response to queries. However, in environments in which the
physical security of the data or backup files is at risk, you can use sp_clean_db_file_free_space to clean these ghost
records.
The length of time required to run sp_clean_db_file_free_space depends on the size of the file, the available free
space, and the capacity of the disk. Because running sp_clean_db_file_free_space can significantly affect I/O activity,
we recommend that you run this procedure outside usual operation hours.
Before you run sp_clean_db_file_free_space, we recommend that you create a full database backup.
The related sp_clean_db_free_space stored procedure cleans all files in the database.
Permissions
Requires membership in the db_owner database role.

Examples
The following example cleans all residual information from the primary data file of the AdventureWorks2012
database.

USE master;
GO
EXEC sp_clean_db_file_free_space
@dbname = N'AdventureWorks2012', @fileid = 1 ;

See Also
Database Engine Stored Procedures (Transact-SQL)
sp_configure (Transact-SQL)
11/21/2017 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Displays or changes global configuration settings for the current server.

NOTE
For database-level configuration options, see ALTER DATABASE SCOPED CONFIGURATION (Transact-SQL). To configure
Soft-NUMA, see Soft-NUMA (SQL Server).

Transact-SQL Syntax Conventions

Syntax
-- Syntax for SQL Server

sp_configure [ [ @configname = ] 'option_name'


[ , [ @configvalue = ] 'value' ] ]

-- Syntax for Parallel Data Warehouse

-- List all of the configuration options


sp_configure
[;]

-- Configure Hadoop connectivity


sp_configure [ @configname= ] 'hadoop connectivity',
[ @configvalue = ] { 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 }
[;]
RECONFIGURE
[;]

Arguments
[ @configname= ] 'option_name'
Is the name of a configuration option. option_name is varchar(35), with a default of NULL. The SQL Server
Database Engine recognizes any unique string that is part of the configuration name. If not specified, the complete
list of options is returned.
For information about the available configuration options and their settings, see Server Configuration Options
(SQL Server).
[ @configvalue= ] 'value'
Is the new configuration setting. value is int, with a default of NULL. The maximum value depends on the
individual option.
To see the maximum value for each option, see the maximum column of the sys.configurations catalog view.

Return Code Values


0 (success) or 1 (failure)

Result Sets
When executed with no parameters, sp_configure returns a result set with five columns and orders the options
alphabetically in ascending order, as shown in the following table.
The values for config_value and run_value are not automatically equivalent. After updating a configuration
setting by using sp_configure, the system administrator must update the running configuration value by using
either RECONFIGURE or RECONFIGURE WITH OVERRIDE. For more information, see the Remarks section.

COLUMN NAME DATA TYPE DESCRIPTION

name nvarchar(35) Name of the configuration option.

minimum int Minimum value of the configuration


option.

maximum int Maximum value of the configuration


option.

config_value int Value to which the configuration option


was set using sp_configure (value in
sys.configurations.value). For more
information about these options, see
Server Configuration Options (SQL
Server) and sys.configurations
(Transact-SQL).

run_value int Currently running value of the


configuration option (value in
sys.configurations.value_in_use).

For more information, see


sys.configurations (Transact-SQL).

Remarks
Use sp_configure to display or change server-level settings. To change database-level settings, use ALTER
DATABASE. To change settings that affect only the current user session, use the SET statement.

Updating the Running Configuration Value


When you specify a new value for an option, the result set shows this value in the config_value column. This
value initially differs from the value in the run_value column, which shows the currently running configuration
value. To update the running configuration value in the run_value column, the system administrator must run
either RECONFIGURE or RECONFIGURE WITH OVERRIDE.
Both RECONFIGURE and RECONFIGURE WITH OVERRIDE work with every configuration option. However, the
basic RECONFIGURE statement rejects any option value that is outside a reasonable range or that may cause
conflicts among options. For example, RECONFIGURE generates an error if the recovery interval value is larger
than 60 minutes or if the affinity mask value overlaps with the affinity I/O mask value. RECONFIGURE WITH
OVERRIDE, in contrast, accepts any option value with the correct data type and forces reconfiguration with the
specified value.
Cau t i on

An inappropriate option value can adversely affect the configuration of the server instance. Use RECONFIGURE
WITH OVERRIDE cautiously.
The RECONFIGURE statement updates some options dynamically; other options require a server stop and restart.
For example, the min server memory and max server memory server memory options are updated dynamically
in the Database Engine; therefore, you can change them without restarting the server. By contrast, reconfiguring
the running value of the fill factor option requires restarting the Database Engine.
After running RECONFIGURE on a configuration option, you can see whether the option has been updated
dynamically by executing sp_configure'option_name'. The values in the run_value and config_value columns
should match for a dynamically updated option. You can also check to see which options are dynamic by looking at
the is_dynamic column of the sys.configurations catalog view.

NOTE
If a specified value is too high for an option, the run_value column reflects the fact that the Database Engine has defaulted
to dynamic memory rather than use a setting that is not valid.

For more information, see RECONFIGURE (Transact-SQL).

Advanced Options
Some configuration options, such as affinity mask and recovery interval, are designated as advanced options.
By default, these options are not available for viewing and changing. To make them available, set the
ShowAdvancedOptions configuration option to 1.
For more information about the configuration options and their settings, see Server Configuration Options (SQL
Server).

Permissions
Execute permissions on sp_configure with no parameters or with only the first parameter are granted to all users
by default. To execute sp_configure with both parameters to change a configuration option or to run the
RECONFIGURE statement, you must be granted the ALTER SETTINGS server-level permission. The ALTER
SETTINGS permission is implicitly held by the sysadmin and serveradmin fixed server roles.

Examples
A. Listing the advanced configuration options
The following example shows how to set and list all configuration options. Advanced configuration options are
displayed by first setting show advanced option to 1 . After this option has been changed, executing sp_configure
with no parameters displays all configuration options.

USE master;
GO
EXEC sp_configure 'show advanced option', '1';

Here is the message: "Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE
statement to install."
Run RECONFIGURE and show all configuration options:

RECONFIGURE;
EXEC sp_configure;
B. Changing a configuration option
The following example sets the system recovery interval to 3 minutes.

USE master;
GO
EXEC sp_configure 'recovery interval', '3';
RECONFIGURE WITH OVERRIDE;

Examples: Parallel Data Warehouse


C. List all available configuration settings
The following example shows how to list all configuration options.

EXEC sp_configure;

The result returns the option name followed by the minimum and maximum values for the option. The
config_value is the value that SQL Data Warehouse will use when reconfiguration is complete. The run_value is
the value that is currently being used. The config_value and run_value are usually the same unless the value is in
the process of being changed.
D. List the configuration settings for one configuration name

EXEC sp_configure @configname='hadoop connectivity';

E. Set Hadoop connectivity


Setting Hadoop connectivity requires a few more steps in addition to running sp_configure. For the full procedure,
see CREATE EXTERNAL DATA SOURCE (Transact-SQL).

See Also
RECONFIGURE (Transact-SQL)
SET Statements (Transact-SQL)
Server Configuration Options (SQL Server)
ALTER DATABASE (Transact-SQL)
System Stored Procedures (Transact-SQL)
sys.configurations (Transact-SQL)
ALTER DATABASE SCOPED CONFIGURATION (Transact-SQL)
Soft-NUMA (SQL Server)
sp_control_plan_guide (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops, enables, or disables a plan guide.
Transact-SQL Syntax Conventions

Syntax
sp_control_plan_guide [ @operation = ] N'<control_option>'
[ , [ @name = ] N'plan_guide_name' ]

<control_option>::=
{
DROP
| DROP ALL
| DISABLE
| DISABLE ALL
| ENABLE
| ENABLE ALL
}

Arguments
N' plan_guide_name '
Specifies the plan guide that is being dropped, enabled, or disabled. plan_guide_name is resolved to the current
database. If not specified, plan_guide_name defaults to NULL.
DROP
Drops the plan guide specified by plan_guide_name. After a plan guide is dropped, future executions of a query
formerly matched by the plan guide are not influenced by the plan guide.
DROP ALL
Drops all plan guides in the current database. N'plan_guide_name cannot be specified when DROP ALL is
specified.
DISABLE
Disables the plan guide specified by plan_guide_name. After a plan guide is disabled, future executions of a query
formerly matched by the plan guide are not influenced by the plan guide.
DISABLE ALL
Disables all plan guides in the current database. N'plan_guide_name cannot be specified when DISABLE ALL is
specified.
ENABLE
Enables the plan guide specified by plan_guide_name. A plan guide can be matched with an eligible query after it
is enabled. By default, plan guides are enabled at the time they are created.
ENABLE ALL
Enables all plan guides in the current database. N'plan_guide_name'cannot be specified when ENABLE ALL is
specified.

Remarks
Trying to drop or modify a function, stored procedure, or DML trigger that is referenced by a plan guide, either
enabled or disabled, causes an error.
Disabling a disabled plan guide or enabling an enabled plan guide has no effect and runs without error.
Plans guides are not available in every edition of Microsoft SQL Server. For a list of features that are supported by
the editions of SQL Server, see Editions and Supported Features for SQL Server 2016. However, you can execute
sp_control_plan_guide with the DROP or DROP ALL option in any edition of SQL Server.

Permissions
To execute sp_control_plan_guide on a plan guide of type OBJECT (created specifying @type ='OBJECT' )
requires ALTER permission on the object that is referenced by the plan guide. All other plan guides require ALTER
DATABASE permission.

Examples
A. Enabling, disabling and dropping a plan guide
The following example creates a plan guide, disables it, enables it, and drops it.

--Create a procedure on which to define the plan guide.


IF OBJECT_ID(N'Sales.GetSalesOrderByCountry', N'P') IS NOT NULL
DROP PROCEDURE Sales.GetSalesOrderByCountry;
GO
CREATE PROCEDURE Sales.GetSalesOrderByCountry
(@Country nvarchar(60))
AS
BEGIN
SELECT *
FROM Sales.SalesOrderHeader AS h
INNER JOIN Sales.Customer AS c ON h.CustomerID = c.CustomerID
INNER JOIN Sales.SalesTerritory AS t ON c.TerritoryID = t.TerritoryID
WHERE t.CountryRegionCode = @Country;
END
GO
--Create the plan guide.
EXEC sp_create_plan_guide N'Guide3',
N'SELECT *
FROM Sales.SalesOrderHeader AS h
INNER JOIN Sales.Customer AS c ON h.CustomerID = c.CustomerID
INNER JOIN Sales.SalesTerritory AS t ON c.TerritoryID = t.TerritoryID
WHERE t.CountryRegionCode = @Country',
N'OBJECT',
N'Sales.GetSalesOrderByCountry',
NULL,
N'OPTION (OPTIMIZE FOR (@Country = N''US''))';
GO
--Disable the plan guide.
EXEC sp_control_plan_guide N'DISABLE', N'Guide3';
GO
--Enable the plan guide.
EXEC sp_control_plan_guide N'ENABLE', N'Guide3';
GO
--Drop the plan guide.
EXEC sp_control_plan_guide N'DROP', N'Guide3';

B. Disabling all plan guides in the current database


The following example disables all plan guides in the AdventureWorks2012 database.

USE AdventureWorks2012;
GO
EXEC sp_control_plan_guide N'DISABLE ALL';

See Also
Database Engine Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_create_plan_guide (Transact-SQL)
sys.plan_guides (Transact-SQL)
Plan Guides
sp_create_plan_guide (Transact-SQL)
11/27/2017 • 13 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a plan guide for associating query hints or actual query plans with queries in a database. For more
information about plan guides, see Plan Guides.
Transact-SQL Syntax Conventions

Syntax
sp_create_plan_guide [ @name = ] N'plan_guide_name'
, [ @stmt = ] N'statement_text'
, [ @type = ] N'{ OBJECT | SQL | TEMPLATE }'
, [ @module_or_batch = ]
{
N'[ schema_name. ] object_name'
| N'batch_text'
| NULL
}
, [ @params = ] { N'@parameter_name data_type [ ,...n ]' | NULL }
, [ @hints = ] { N'OPTION ( query_hint [ ,...n ] )'
| N'XML_showplan'
| NULL }

Arguments
[ @name = ] N'plan_guide_name'
Is the name of the plan guide. Plan guide names are scoped to the current database. plan_guide_name must
comply with the rules for identifiers and cannot start with the number sign (#). The maximum length of
plan_guide_name is 124 characters.
[ @stmt = ] N'statement_text'
Is a Transact-SQL statement against which to create a plan guide. When the SQL Server query optimizer
recognizes a query that matches statement_text, plan_guide_name takes effect. For the creation of a plan guide to
succeed, statement_text must appear in the context specified by the @type, @module_or_batch, and @params
parameters.
statement_text must be provided in a way that allows for the query optimizer to match it with the corresponding
statement supplied within the batch or module identified by @module_or_batch and @params. For more
information, see the "Remarks" section. The size of statement_text is limited only by available memory of the
server.
[@type = ]N'{ OBJECT | SQL | TEMPLATE }'
Is the type of entity in which statement_text appears. This specifies the context for matching statement_text to
plan_guide_name.
OBJECT
Indicates statement_text appears in the context of a Transact-SQL stored procedure, scalar function, multistatement
table-valued function, or Transact-SQL DML trigger in the current database.
SQL
Indicates statement_text appears in the context of a stand-alone statement or batch that can be submitted to SQL
Server through any mechanism. Transact-SQL statements submitted by common language runtime (CLR) objects
or extended stored procedures, or by using EXEC N'sql_string', are processed as batches on the server and,
therefore, should be identified as @type = 'SQL'. If SQL is specified, the query hint PARAMETERIZATION { FORCED
| SIMPLE } cannot be specified in the @hints parameter.
TEMPLATE
Indicates the plan guide applies to any query that parameterizes to the form indicated in statement_text. If
TEMPLATE is specified, only the PARAMETERIZATION { FORCED | SIMPLE } query hint can be specified in the
@hints parameter. For more information about TEMPLATE plan guides, see Specify Query Parameterization
Behavior by Using Plan Guides.
[@module_or_batch =]{ N'[ schema_name. ] object_name' | N'batch_text' | NULL }
Specifies either the name of the object in which statement_text appears, or the batch text in which statement_text
appears. The batch text cannot include a USEdatabase statement.
For a plan guide to match a batch submitted from an application, batch_text must be provided in the same format,
character-for-character, as it is submitted to SQL Server. No internal conversion is performed to facilitate this
match. For more information, see the Remarks section.
[schema_name.]object_name specifies the name of a Transact-SQL stored procedure, scalar function,
multistatement table-valued function, or Transact-SQL DML trigger that contains statement_text. If schema_name
is not specified, schema_name uses the schema of the current user. If NULL is specified and @type = 'SQL', the
value of @module_or_batch is set to the value of @stmt. If @type = 'TEMPLATE', @module_or_batch must be
NULL.
[ @params = ]{ N'@parameter_name data_type [ ,...n ]' | NULL }
Specifies the definitions of all parameters that are embedded in statement_text. @params applies only when either
of the following is true:
@type = 'SQL' or 'TEMPLATE'. If 'TEMPLATE', @params must not be NULL.
statement_text is submitted by using sp_executesql and a value for the @params parameter is specified, or
SQL Server internally submits a statement after parameterizing it. Submission of parameterized queries
from database APIs (including ODBC, OLE DB, and ADO.NET) appear to SQL Server as calls to sp_executesql
or to API server cursor routines; therefore, they can also be matched by SQL or TEMPLATE plan guides.
@parameter_name data_type must be supplied in the exact same format as it is submitted to SQL Server
either by using sp_executesql or submitted internally after parameterization. For more information, see the
Remarks section. If the batch does not contain parameters, NULL must be specified. The size of @params is
limited only by available server memory.
[@hints = ]{ N'OPTION (query_hint [ ,...n ] )' | N'XML_showplan' | NULL }
N'OPTION (query_hint [ ,...n ] )
Specifies an OPTION clause to attach to a query that matches @stmt. @hints must be syntactically the same
as an OPTION clause in a SELECT statement, and can contain any valid sequence of query hints.
N'XML_showplan'
Is the query plan in XML format to be applied as a hint.
We recommend assigning the XML Showplan to a variable; otherwise, you must escape any single
quotation marks in the Showplan by preceding them with another single quotation mark. See example E.
NULL
Indicates that any existing hint specified in the OPTION clause of the query is not applied to the query. For
more information, see OPTION Clause (Transact-SQL).
Remarks
The arguments to sp_create_plan_guide must be provided in the order that is shown. When you supply values for
the parameters of sp_create_plan_guide, all parameter names must be specified explicitly, or none at all. For
example, if @name = is specified, then @stmt = , @type =, and so on, must also be specified. Likewise, if @name
= is omitted and only the parameter value is provided, the remaining parameter names must also be omitted, and
only their values provided. Argument names are for descriptive purposes only, to help understand the syntax. SQL
Server does not verify that the specified parameter name matches the name for the parameter in the position
where the name is used.
You can create more than one OBJECT or SQL plan guide for the same query and batch or module. However, only
one plan guide can be enabled at any given time.
Plan guides of type OBJECT cannot be created for an @module_or_batch value that references a stored procedure,
function, or DML trigger that specifies the WITH ENCRYPTION clause or that is temporary.
Trying to drop or modify a function, stored procedure, or DML trigger that is referenced by a plan guide, either
enabled or disabled, causes an error. Trying to drop a table that has a trigger defined on it that is referenced by a
plan guide also causes an error.

NOTE
Plan guides cannot be used in every edition of Microsoft SQL Server. For a list of features that are supported by the editions
of SQL Server, see Features Supported by the Editions of SQL Server 2016. Plan guides are visible in any edition. You can
also attach a database that contains plan guides to any edition. Plan guides remain intact when you restore or attach a
database to an upgraded version of SQL Server. You should verify the desirability of the plan guides in each database after
performing a server upgrade.

Plan Guide Matching Requirements


For plan guides that specify @type = 'SQL' or @type = 'TEMPLATE' to successfully match a query, the values for
batch_text and @parameter_name data_type [,...n ] must be provided in exactly the same format as their
counterparts submitted by the application. This means you must provide the batch text exactly as the SQL Server
compiler receives it. To capture the actual batch and parameter text, you can use SQL Server Profiler. For more
information, see Use SQL Server Profiler to Create and Test Plan Guides.
When @type = 'SQL' and @module_or_batch is set to NULL, the value of @module_or_batch is set to the value of
@stmt. This means that the value for statement_text must be provided in exactly the same format, character-for-
character, as it is submitted to SQL Server. No internal conversion is performed to facilitate this match.
When SQL Server matches the value of statement_text to batch_text and @parameter_name data_type [,...n ], or if
@type = 'OBJECT', to the text of the corresponding query inside object_name, the following string elements are
not considered:
White space characters (tabs, spaces, carriage returns, or line feeds) inside the string.
Comments (-- or /* */).
Trailing semicolons
For example, SQL Server can match the statement_text string N'SELECT * FROM T WHERE a = 10' to the
following batch_text:
N'SELECT *

FROM T
WHERE a=10'

However, the same string would not be matched to this batch_text:


N'SELECT * FROM T WHERE b = 10'

SQL Server ignores the carriage return, line feed, and space characters inside the first query. In the second
query, the sequence WHERE b = 10 is interpreted differently from WHERE a = 10 . Matching is case- and
accent-sensitive (even when the collation of the database is case-insensitive), except in the case of
keywords, where case is insensitive. Matching is insensitive to shortened forms of keywords. For example,
the keywords EXECUTE , EXEC , and execute are considered equivalent.

Plan Guide Effect on the Plan Cache


Creating a plan guide on a module removes the query plan for that module from the plan cache. Creating a plan
guide of type OBJECT or SQL on a batch removes the query plan for a batch that has the same hash value. Creating
a plan guide of type TEMPLATE removes all single-statement batches from the plan cache within that database.

Permissions
To create a plan guide of type OBJECT, requires ALTER permission on the referenced object. To create a plan guide
of type SQL or TEMPLATE, requires ALTER permission on the current database.

Examples
A. Creating a plan guide of type OBJECT for a query in a stored procedure
The following example creates a plan guide that matches a query executed in the context of an application-based
stored procedure, and applies the OPTIMIZE FOR hint to the query.
Here is the stored procedure:

IF OBJECT_ID(N'Sales.GetSalesOrderByCountry', N'P') IS NOT NULL


DROP PROCEDURE Sales.GetSalesOrderByCountry;
GO
CREATE PROCEDURE Sales.GetSalesOrderByCountry
(@Country_region nvarchar(60))
AS
BEGIN
SELECT *
FROM Sales.SalesOrderHeader AS h
INNER JOIN Sales.Customer AS c ON h.CustomerID = c.CustomerID
INNER JOIN Sales.SalesTerritory AS t
ON c.TerritoryID = t.TerritoryID
WHERE t.CountryRegionCode = @Country_region;
END
GO

Here is the plan guide created on the query in the stored procedure:
EXEC sp_create_plan_guide
@name = N'Guide1',
@stmt = N'SELECT *
FROM Sales.SalesOrderHeader AS h
INNER JOIN Sales.Customer AS c
ON h.CustomerID = c.CustomerID
INNER JOIN Sales.SalesTerritory AS t
ON c.TerritoryID = t.TerritoryID
WHERE t.CountryRegionCode = @Country_region',
@type = N'OBJECT',
@module_or_batch = N'Sales.GetSalesOrderByCountry',
@params = NULL,
@hints = N'OPTION (OPTIMIZE FOR (@Country_region = N''US''))';

B. Creating a plan guide of type SQL for a stand-alone query


The following example creates a plan guide to match a query in a batch submitted by an application that uses the
sp_executesql system stored procedure.
Here is the batch:

SELECT TOP 1 * FROM Sales.SalesOrderHeader ORDER BY OrderDate DESC;

To prevent a parallel execution plan from being generated on this query, create the following plan guide:

EXEC sp_create_plan_guide
@name = N'Guide1',
@stmt = N'SELECT TOP 1 *
FROM Sales.SalesOrderHeader
ORDER BY OrderDate DESC',
@type = N'SQL',
@module_or_batch = NULL,
@params = NULL,
@hints = N'OPTION (MAXDOP 1)';

C. Creating a plan guide of type TEMPLATE for the parameterized form of a query
The following example creates a plan guide that matches any query that parameterizes to a specified form, and
directs SQL Server to force parameterization of the query. The following two queries are syntactically equivalent,
but differ only in their constant literal values.

SELECT * FROM AdventureWorks2012.Sales.SalesOrderHeader AS h


INNER JOIN AdventureWorks2012.Sales.SalesOrderDetail AS d
ON h.SalesOrderID = d.SalesOrderID
WHERE h.SalesOrderID = 45639;

SELECT * FROM AdventureWorks2012.Sales.SalesOrderHeader AS h


INNER JOIN AdventureWorks2012.Sales.SalesOrderDetail AS d
ON h.SalesOrderID = d.SalesOrderID
WHERE h.SalesOrderID = 45640;

Here is the plan guide on the parameterized form of the query:


EXEC sp_create_plan_guide
@name = N'TemplateGuide1',
@stmt = N'SELECT * FROM AdventureWorks2012.Sales.SalesOrderHeader AS h
INNER JOIN AdventureWorks2012.Sales.SalesOrderDetail AS d
ON h.SalesOrderID = d.SalesOrderID
WHERE h.SalesOrderID = @0',
@type = N'TEMPLATE',
@module_or_batch = NULL,
@params = N'@0 int',
@hints = N'OPTION(PARAMETERIZATION FORCED)';

In the previous example, the value for the @stmt parameter is the parameterized form of the query. The only
reliable way to obtain this value for use in sp_create_plan_guide is to use the sp_get_query_template system stored
procedure. The following script can be used both to obtain the parameterized query and then create a plan guide
on it.

DECLARE @stmt nvarchar(max);


DECLARE @params nvarchar(max);
EXEC sp_get_query_template
N'SELECT * FROM AdventureWorks2012.Sales.SalesOrderHeader AS h
INNER JOIN AdventureWorks2012.Sales.SalesOrderDetail AS d
ON h.SalesOrderID = d.SalesOrderID
WHERE h.SalesOrderID = 45639;',
@stmt OUTPUT,
@params OUTPUT
EXEC sp_create_plan_guide N'TemplateGuide1',
@stmt,
N'TEMPLATE',
NULL,
@params,
N'OPTION(PARAMETERIZATION FORCED)';

IMPORTANT
The value of the constant literals in the @stmt parameter passed to sp_get_query_template might affect the data type that
is chosen for the parameter that replaces the literal. This will affect plan guide matching. You may have to create more than
one plan guide to handle different parameter value ranges.

D. Creating a plan guide on a query submitted by using an API cursor request


Plan guides can match queries that are submitted from API server cursor routines. These routines include
sp_cursorprepare, sp_cursorprepexec, and sp_cursoropen. Applications that use the ADO, OLE DB, and ODBC APIs
frequently interact with SQL Server by using API server cursors. You can see the invocation of API server cursor
routines in SQL Server Profiler traces by viewing the RPC:Starting profiler trace event.
Suppose the following data appears in an RPC:Starting profiler trace event for a query you want to tune with a
plan guide:
DECLARE @p1 int;
SET @p1=-1;
DECLARE @p2 int;
SET @p2=0;
DECLARE @p5 int;
SET @p5=4104;
DECLARE @p6 int;
SET @p6=8193;
DECLARE @p7 int;
SET @p7=0;
EXEC sp_cursorprepexec @p1 output,@p2 output,N'@P1 varchar(255),@P2 varchar(255)',N'SELECT * FROM
Sales.SalesOrderHeader AS h INNER JOIN Sales.SalesOrderDetail AS d ON h.SalesOrderID = d.SalesOrderID WHERE
h.OrderDate BETWEEN @P1 AND @P2',@p5 OUTPUT,@p6 OUTPUT,@p7 OUTPUT,'20040101','20050101'
SELECT @p1, @p2, @p5, @p6, @p7;

You notice that the plan for the SELECT query in the call to sp_cursorprepexec is using a merge join, but you want
to use a hash join. The query submitted by using sp_cursorprepexec is parameterized, including both a query
string and a parameter string. You can create the following plan guide to change the choice of plan by using the
query and parameter strings exactly as they appear, character for character, in the call to sp_cursorprepexec .

EXEC sp_create_plan_guide
@name = N'APICursorGuide',
@stmt = N'SELECT * FROM Sales.SalesOrderHeader AS h
INNER JOIN Sales.SalesOrderDetail AS d
ON h.SalesOrderID = d.SalesOrderID
WHERE h.OrderDate BETWEEN @P1 AND @P2',
@type = N'SQL',
@module_or_batch = NULL,
@params = N'@P1 varchar(255),@P2 varchar(255)',
@hints = N'OPTION(HASH JOIN)';

Subsequent executions of this query by the application will be affected by this plan guide, and a hash join will be
used to process the query.
E. Creating a plan guide by obtaining the XML Showplan from a cached plan
The following example creates a plan guide for a simple ad hoc SQL statement. The desired query plan for this
statement is provided in the plan guide by specifying the XML Showplan for the query directly in the @hints
parameter. The example first executes the SQL statement to generate a plan in the plan cache. For the purposes of
this example, it is assumed that the generated plan is the desired plan and no additional query tuning is required.
The XML Showplan for the query is obtained by querying the sys.dm_exec_query_stats , sys.dm_exec_sql_text , and
sys.dm_exec_text_query_plan dynamic management views and is assigned to the @xml_showplan variable. The
@xml_showplan variable is then passed to the sp_create_plan_guide statement in the @hints parameter. Or, you
can create a plan guide from a query plan in the plan cache by using the sp_create_plan_guide_from_handle stored
procedure.
USE AdventureWorks2012;
GO
SELECT City, StateProvinceID, PostalCode FROM Person.Address ORDER BY PostalCode DESC;
GO
DECLARE @xml_showplan nvarchar(max);
SET @xml_showplan = (SELECT query_plan
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
CROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, DEFAULT, DEFAULT) AS qp
WHERE st.text LIKE N'SELECT City, StateProvinceID, PostalCode FROM Person.Address ORDER BY PostalCode
DESC;%');

EXEC sp_create_plan_guide
@name = N'Guide1_from_XML_showplan',
@stmt = N'SELECT City, StateProvinceID, PostalCode FROM Person.Address ORDER BY PostalCode DESC;',
@type = N'SQL',
@module_or_batch = NULL,
@params = NULL,
@hints =@xml_showplan;
GO

See Also
Plan Guides
sp_control_plan_guide (Transact-SQL)
sys.plan_guides (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sys.dm_exec_sql_text (Transact-SQL)
sys.dm_exec_cached_plans (Transact-SQL)
sys.dm_exec_query_stats (Transact-SQL)
sp_create_plan_guide_from_handle (Transact-SQL)
sys.fn_validate_plan_guide (Transact-SQL)
sp_get_query_template (Transact-SQL)
sp_create_plan_guide_from_handle (Transact-SQL)
1/2/2018 • 6 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates one or more plan guides from a query plan in the plan cache. You can use this stored procedure to ensure
the query optimizer always uses a specific query plan for a specified query. For more information about plan
guides, see Plan Guides.
Transact-SQL Syntax Conventions

Syntax
sp_create_plan_guide_from_handle [ @name = ] N'plan_guide_name'
, [ @plan_handle = ] plan_handle
, [ [ @statement_start_offset = ] { statement_start_offset | NULL } ]

Arguments
[ @name = ] N'plan_guide_name'
Is the name of the plan guide. Plan guide names are scoped to the current database. plan_guide_name must
comply with the rules for identifiers and cannot start with the number sign (#). The maximum length of
plan_guide_name is 124 characters.
[ @plan_handle = ] plan_handle
Identifies a batch in the plan cache. plan_handle is varbinary(64). plan_handle can be obtained from the
sys.dm_exec_query_stats dynamic management view.
[ @statement_start_offset = ] { statement_start_offset | NULL } ]
Identifies the starting position of the statement within the batch of the specified plan_handle.
statement_start_offset is int, with a default of NULL.
The statement offset corresponds to the statement_start_offset column in the sys.dm_exec_query_stats dynamic
management view.
When NULL is specified or a statement offset is not specified, a plan guide is created for each statement in the
batch using the query plan for the specified plan handle. The resulting plan guides are equivalent to plan guides
that use the USE PLAN query hint to force the use of a specific plan.

Remarks
A plan guide cannot be created for all statement types. If a plan guide cannot be created for a statement in the
batch, the stored procedure ignores the statement and continues to the next statement in the batch. If a statement
occurs multiple times in the same batch, the plan for the last occurrence is enabled and previous plans for the
statement are disabled. If no statements in the batch can be used in a plan guide, error 10532 is raised and the
statement fails. We recommend that you always obtain the plan handle from the sys.dm_exec_query_stats
dynamic management view to help avoid the possibility of this error.
IMPORTANT
sp_create_plan_guide_from_handle creates plan guides based on plans as they appear in the plan cache. This means that the
batch text, Transact-SQL statements, and XML Showplan are taken character-by-character (including any literal values
passed to the query) from the plan cache into the resulting plan guide. These text strings may contain sensitive information
that is then stored in the metadata of the database. Users with appropriate permissions can view this information by using
the sys.plan_guides catalog view and the Plan Guide Properties dialog box in SQL Server Management Studio. To ensure
that sensitive information is not disclosed through a plan guide, we recommend reviewing the plan guides created from the
plan cache.

Creating Plan Guides for Multiple Statements Within a Query Plan


Like sp_create_plan_guide, sp_create_plan_guide_from_handle removes the query plan for the targeted batch or
module from the plan cache. This is done to ensure that all users begin using the new plan guide. When creating a
plan guide for multiple statements within a single query plan, you can postpone the removal of the plan from the
cache by creating all the plan guides in an explicit transaction. This method allows the plan to remain in the cache
until the transaction is complete and a plan guide for each specified statement is created. See Example B.

Permissions
Requires VIEW SERVER STATE permission. In addition, individual permissions are required for each plan guide that
is created by using sp_create_plan_guide_from_handle. To create a plan guide of type OBJECT requires ALTER
permission on the referenced object. To create a plan guide of type SQL or TEMPLATE requires ALTER permission
on the current database. To determine the plan guide type that will be created, run the following query:

SELECT cp.plan_handle, sql_handle, st.text, objtype


FROM sys.dm_exec_cached_plans AS cp
JOIN sys.dm_exec_query_stats AS qs ON cp.plan_handle = qs.plan_handle
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS st;

In the row that contains the statement for which you are creating the plan guide, examine the objtype column in
the result set. A value of Proc indicates the plan guide is of type OBJECT. Other values such as AdHoc or
Prepared indicate the plan guide is of type SQL.

Examples
A. Creating a plan guide from a query plan in the plan cache
The following example creates a plan guide for a single SELECT statement by specifying a query plan from the plan
cache. The example begins by executing a simple SELECT statement for which the plan guide will be created. The
plan for this query is examined by using the sys.dm_exec_sql_text and sys.dm_exec_text_query_plan dynamic
management views. The plan guide is then created for the query by specifying the query plan in the plan cache
that is associated with the query. The final statement in the example verifies that the plan guide exists.
USE AdventureWorks2012;
GO
SELECT WorkOrderID, p.Name, OrderQty, DueDate
FROM Production.WorkOrder AS w
JOIN Production.Product AS p ON w.ProductID = p.ProductID
WHERE p.ProductSubcategoryID > 4
ORDER BY p.Name, DueDate;
GO
-- Inspect the query plan by using dynamic management views.
SELECT * FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(sql_handle)
CROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, qs.statement_start_offset, qs.statement_end_offset) AS
qp
WHERE text LIKE N'SELECT WorkOrderID, p.Name, OrderQty, DueDate%';
GO
-- Create a plan guide for the query by specifying the query plan in the plan cache.
DECLARE @plan_handle varbinary(64);
DECLARE @offset int;
SELECT @plan_handle = plan_handle, @offset = qs.statement_start_offset
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS st
CROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, qs.statement_start_offset, qs.statement_end_offset) AS
qp
WHERE text LIKE N'SELECT WorkOrderID, p.Name, OrderQty, DueDate%';

EXECUTE sp_create_plan_guide_from_handle
@name = N'Guide1',
@plan_handle = @plan_handle,
@statement_start_offset = @offset;
GO
-- Verify that the plan guide is created.
SELECT * FROM sys.plan_guides
WHERE scope_batch LIKE N'SELECT WorkOrderID, p.Name, OrderQty, DueDate%';
GO

B. Creating multiple plan guides for a multistatement batch


The following example creates a plan guide for two statements within a multistatement batch. The plan guides are
created within an explicit transaction so that the query plan for the batch is not removed from the plan cache after
the first plan guide is created. The example begins by executing a multistatement batch. The plan for the batch is
examined by using dynamic management views. Notice that a row for each statement in the batch is returned. A
plan guide is then created for the first and third statements in the batch by specifying the @statement_start_offset
parameter. The final statement in the example verifies that the plan guides exist.
USE AdventureWorks2012;
GO
SELECT * FROM Production.Product WHERE ProductSubcategoryID > 4;
SELECT * FROM Person.Address;
SELECT * FROM Production.Product WHERE ProductSubcategoryID > 10;
GO

-- Examine the query plans for this batch


SELECT * FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(sql_handle)
CROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, qs.statement_start_offset, qs.statement_end_offset) AS
qp
WHERE text LIKE N'SELECT * FROM Production.Product WHERE ProductSubcategoryID > 4%';
GO

-- Create plan guides for the first and third statements in the batch by specifying the statement offsets.
BEGIN TRANSACTION

DECLARE @plan_handle varbinary(64);


DECLARE @offset int;

SELECT @plan_handle = plan_handle, @offset = qs.statement_start_offset


FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS st
CROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, qs.statement_start_offset, qs.statement_end_offset) AS
qp
WHERE text LIKE N'SELECT * FROM Production.Product WHERE ProductSubcategoryID > 4%'
AND SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,
((CASE statement_end_offset
WHEN -1 THEN DATALENGTH(st.text)
ELSE qs.statement_end_offset END
- qs.statement_start_offset)/2) + 1) like 'SELECT * FROM Production.Product
WHERE ProductSubcategoryID > 4%'

EXECUTE sp_create_plan_guide_from_handle
@name = N'Guide_Statement1_only',
@plan_handle = @plan_handle,
@statement_start_offset = @offset;

SELECT @plan_handle = plan_handle, @offset = qs.statement_start_offset


FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS st
CROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, qs.statement_start_offset, qs.statement_end_offset) AS
qp
WHERE text LIKE N'SELECT * FROM Production.Product WHERE ProductSubcategoryID > 4%'
AND SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,
((CASE statement_end_offset
WHEN -1 THEN DATALENGTH(st.text)
ELSE qs.statement_end_offset END
- qs.statement_start_offset)/2) + 1) like 'SELECT * FROM Production.Product
WHERE ProductSubcategoryID > 10%'

EXECUTE sp_create_plan_guide_from_handle
@name = N'Guide_Statement3_only',
@plan_handle = @plan_handle,
@statement_start_offset = @offset;

COMMIT TRANSACTION
GO

-- Verify the plan guides are created.


SELECT * FROM sys.plan_guides;
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
sys.dm_exec_query_stats (Transact-SQL)
Plan Guides
sp_create_plan_guide (Transact-SQL)
sys.dm_exec_sql_text (Transact-SQL)
sys.dm_exec_text_query_plan (Transact-SQL)
sp_control_plan_guide (Transact-SQL)
sp_create_removable (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a removable media database. Creates three or more files (one for the system catalog tables, one for the
transaction log, and one or more for the data tables) and places the database on those files.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. We recommend that you use CREATE DATABASE instead.

Transact-SQL Syntax Conventions

Syntax
sp_create_removable
[ @dbname = ] 'dbname',
[ @syslogical= ] 'syslogical',
[ @sysphysical = ] 'sysphysical',
[ @syssize = ] syssize,
[ @loglogical = ] 'loglogical',
[ @logphysical = ] 'logphysical',
[ @logsize = ] logsize,
[ @datalogical1 = ] 'datalogical1',
[ @dataphysical1 = ] 'dataphysical1',
[ @datasize1 = ] datasize1 ,
[ @datalogical16 = ] 'datalogical16',
[ @dataphysical16 = ] 'dataphysical16',
[ @datasize16 = ] datasize16 ]

Arguments
[ @dbname= ] 'dbname'
Is the name of the database to create for use on removable media. dbname is sysname.
[ @syslogical= ] 'syslogical'
Is the logical name of the file that contains the system catalog tables. syslogical is sysname.
[ @sysphysical= ] 'sysphysical'
Is the physical name. This includes a fully qualified path, of the file that holds the system catalog tables. sysphysical
is nvarchar(260).
[ @syssize= ] syssize
Is the size, in megabytes, of the file that holds the system catalog tables. syssize is int. The minimum syssize is 1.
[ @loglogical= ] 'loglogical'
Is the logical name of the file that contains the transaction log. loglogical is sysname.
[ @logphysical= ] 'logphysical'
Is the physical name. This includes a fully qualified path, of the file that contains the transaction log. logphysical is
nvarchar(260).
[ @logsize= ] logsize
Is the size, in megabytes, of the file that contains the transaction log. logsize is int. The minimum logsize is 1.
[ @datalogical1= ] 'datalogical'
Is the logical name of a file that contains the data tables. datalogical is sysname.
There must be from 1 through 16 data files. Typically, more than one data file is created when the database is
expected to be large and must be distributed on multiple disks.
[ @dataphysical1= ] 'dataphysical'
Is the physical name. This includes a fully qualified path, of a file that contains data tables. dataphysical is
nvarchar(260).
[ @datasize1= ] 'datasize'
Is the size, in megabytes, of a file that contains data tables. datasize is int. The minimum datasize is 1.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
If you want to make a copy of your database on removable media, such as a compact disc, and distribute the
database to other users, use this stored procedure.

Permissions
Requires CREATE DATABASE, CREATE ANY DATABASE, or ALTER ANY DATABASE permission.
To maintain control over disk use on an instance of SQL Server, permission to create databases is typically limited
to a few login accounts.
Permissions on Data and Log Files
Whenever certain operations are performed on a database, corresponding permissions are set on its data and log
files. The permissions prevent the files from being accidentally tampered with if they reside in a directory that has
open permissions.

OPERATION ON DATABASE PERMISSIONS SET ON FILES

Modified to add a new file Created

Backed up Attached

Restored Detached

NOTE
SQL Server does not set data and log file permissions.
Examples
The following example creates the database inventory as a removable database.

EXEC sp_create_removable 'inventory',


'invsys',
'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\invsys.mdf'
, 2,
'invlog',
'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\invlog.ldf', 4,
'invdata',
'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\invdata.ndf',
10;

See Also
Database Detach and Attach (SQL Server)
sp_certify_removable (Transact-SQL)
ALTER DATABASE (Transact-SQL)
sp_dbremove (Transact-SQL)
sp_detach_db (Transact-SQL)
sp_helpfile (Transact-SQL)
sp_helpfilegroup (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_createstats (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Calls the CREATE STATISTICS statement to create single-column statistics on columns that are not already the first
column in a statistics object. Creating single-column statistics increases the number of histograms, which can
improve cardinality estimates, query plans, and query performance. The first column of a statistics object has a
histogram; other columns do not have a histogram.
sp_createstats is useful for applications such as benchmarking when query execution times are critical and cannot
wait for the query optimizer to generate single-column statistics. In most cases, it is not necessary to use
sp_createstats; the query optimizer generates single-column statistics as necessary to improve query plans when
the AUTO_CREATE_STATISTICS option is on.
For more information about statistics, see Statistics. For more information about generating single-column
statistics, see the AUTO_CREATE_STATISTICS option in ALTER DATABASE SET Options (Transact-SQL).
Transact-SQL Syntax Conventions

Syntax
sp_createstats
[ [ @indexonly = ] { 'indexonly' | 'NO' } ]
[ , [ @fullscan = ] { 'fullscan' | 'NO' } ]
[ , [ @norecompute = ] { 'norecompute' | 'NO' } ]
[ , [ @incremental = ] { 'incremental' | 'NO' } ]

Arguments
[ @indexonly= ] 'indexonly'
Creates statistics only on columns that are in an existing index and are not the first column in any index definition.
indexonly is char(9). The default is NO.
[ @fullscan= ] 'fullscan'
Uses the CREATE STATISTICS statement with the FULLSCAN option. fullscan is char(9). The default is NO.
[ @norecompute= ] 'norecompute'
Uses the CREATE STATISTICS statement with the NORECOMPUTE option. norecompute is char(12). The default
is NO.
[ @incremental= ] 'incremental'
Uses the CREATE STATISTICS statement with the INCREMENTAL = ON option. Incremental is char(12). The
default is NO.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Each new statistics object has the same name as the column it is created on.

Remarks
sp_createstats does not create or update statistics on columns that are the first column in an existing statistics
object; This includes the first column of statistics created for indexes, columns with single-column statistics
generated with AUTO_CREATE_STATISTICS option, and the first column of statistics created with the CREATE
STATISTICS statement. sp_createstats does not create statistics on the first columns of disabled indexes unless that
column is used in another enabled index. sp_createstats does not create statistics on tables with a disabled
clustered index.
When the table contains a column set, sp_createstats does not create statistics on sparse columns. For more
information about column sets and sparse columns, see Use Column Sets and Use Sparse Columns.

Permissions
Requires membership in the db_owner fixed database role.

Examples
A. Create single -column statistics on all eligible columns
The following example creates single-column statistics on all eligible columns in the current database.

EXEC sp_createstats;
GO

B. Create single -column statistics on all eligible index columns


The following example creates single-column statistics on all eligible columns that are already in an index and are
not the first column in the index.

EXEC sp_createstats 'indexonly';


GO

See Also
Statistics
CREATE STATISTICS (Transact-SQL)
ALTER DATABASE SET Options (Transact-SQL)
DBCC SHOW_STATISTICS (Transact-SQL)
DROP STATISTICS (Transact-SQL)
UPDATE STATISTICS (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_datatype_info (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns information about the data types supported by the current environment.
Transact-SQL Syntax Conventions

Syntax
sp_datatype_info [ [ @data_type = ] data_type ]
[ , [ @ODBCVer = ] odbc_version ]

Arguments
[ @data_type= ] data_type
Is the code number for the specified data type. To obtain a list of all data types, omit this parameter. data_type is
int, with a default of 0.
[ @ODBCVer= ] odbc_version
Is the version of ODBC that is used. odbc_version is tinyint, with a default of 2.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TYPE_NAME sysname DBMS-dependent data type.

DATA_TYPE smallint Code for the ODBC type to which all


columns of this type are mapped.

PRECISION int Maximum precision of the data type on


the data source. NULL is returned for
data types for which precision is not
applicable. The return value for the
PRECISION column is in base 10.

LITERAL_PREFIX varchar(32) Character or characters used before a


constant. For example, a single
quotation mark (') for character types
and 0x for binary.
COLUMN NAME DATA TYPE DESCRIPTION

LITERAL_SUFFIX varchar(32) Character or characters used to


terminate a constant. For example, a
single quotation mark (') for character
types and no quotation marks for
binary.

CREATE_PARAMS varchar(32) Description of the creation parameters


for this data type. For example, decimal
is "precision, scale", float is NULL, and
varchar is "max_length".

NULLABLE smallint Specifies nullability.

1 = Allows null values.

0 = Does not allow null values.

CASE_SENSITIVE smallint Specifies case sensitivity.

1 = All columns of this type are case-


sensitive (for collations).

0 = All columns of this type are case-


insensitive.

SEARCHABLE smallint Specifies the search capability of the


column type:

1 = Cannot be searched.

2 = Searchable with LIKE.

3 = Searchable with WHERE.

4 = Searchable with WHERE or LIKE.

UNSIGNED_ATTRIBUTE smallint Specifies the sign of the data type.

1 = Data type unsigned.

0 = Data type signed.

MONEY smallint Specifies the money data type.

1 = money data type.

0 = Not a money data type.


COLUMN NAME DATA TYPE DESCRIPTION

AUTO_INCREMENT smallint Specifies autoincrementing.

1 = Autoincrementing.

0 = Not autoincrementing.

NULL = Attribute not applicable.

An application can insert values into a


column that has this attribute, but the
application cannot update the values in
the column. With the exception of the
bit data type, AUTO_INCREMENT is
valid only for data types that belong to
the Exact Numeric and Approximate
Numeric data type categories.

LOCAL_TYPE_NAME sysname Localized version of the data source-


dependent name of the data type. For
example, DECIMAL is DECIMALE in
French. NULL is returned if a localized
name is not supported by the data
source.

MINIMUM_SCALE smallint Minimum scale of the data type on the


data source. If a data type has a fixed
scale, the MINIMUM_SCALE and
MAXIMUM_SCALE columns both
contain this value. NULL is returned
where scale is not applicable.

MAXIMUM_SCALE smallint Maximum scale of the data type on the


data source. If the maximum scale is not
defined separately on the data source,
but is instead defined to be the same as
the maximum precision, this column
contains the same value as the
PRECISION column.

SQL_DATA_TYPE smallint Value of the SQL data type as it appears


in the TYPE field of the descriptor. This
column is the same as the DATA_TYPE
column, except for the datetime and
ANSI interval data types. This field
always returns a value.

SQL_DATETIME_SUB smallint datetime or ANSI interval subcode if


the value of SQL_DATA_TYPE is
SQL_DATETIME or SQL_INTERVAL. For
data types other than datetime and
ANSI interval, this field is NULL.
COLUMN NAME DATA TYPE DESCRIPTION

NUM_PREC_RADIX int Number of bits or digits for calculating


the maximum number that a column
can hold. If the data type is an
approximate numeric data type, this
column contains the value 2 to indicate
several bits. For exact numeric types,
this column contains the value 10 to
indicate several decimal digits.
Otherwise, this column is NULL. By
combining the precision with radix, the
application can calculate the maximum
number that the column can hold.

INTERVAL_PRECISION smallint Value of interval leading precision if


data_type is interval; otherwise NULL.

USERTYPE smallint usertype value from the systypes table.

Remarks
sp_datatype_info is equivalent to SQLGetTypeInfo in ODBC. The results returned are ordered by DATA_TYPE and
then by how closely the data type maps to the corresponding ODBC SQL data type.

Permissions
Requires membership in the public role.

Examples
The following example retrieves information for the sysname and nvarchar data types by specifying the
data_type value of -9 .

USE master;
GO
EXEC sp_datatype_info -9;
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
Data Types (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_db_increased_partitions
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Enables or disables support for up to 15,000 partitions for the specified database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature.

Transact-SQL Syntax Conventions

Syntax
sp_dp_increased_partitions
[ @dbname ] = 'database_name'
[ , [ @increased_partitions = ] 'increased_partitions' ] [;]

Arguments
[ @dbname= ] 'database_name'
Is the name of the database. dbname is sysname with a default value of NULL. If dbname is not specified, the
current database is used.
[ @increased_partitions= ] 'increased_partitions'
Enables or disables support for 15,000 partitions on the specified database. increased_partitions is varchar(6) with
a default of NULL. Accepted values are 'ON' or 'TRUE' to enable support and 'OFF' or 'FALSE' to disable support. If
increased_partitions is not specified, the procedure returns 1 to indicate support is enabled for the specified
database or 0 to indicate support is disabled.

Return Code Values


0 (success) or 1 (failure)

Permissions
Requires ALTER DATABASE permission on the specified database.
sp_db_vardecimal_storage_format (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the current vardecimal storage format state of a database or enables a database for vardecimal storage
format. Starting with SQL Server 2008, user databases are always enabled. Enabling databases for the vardecimal
storage format is only necessary in SQL Server 2005.

IMPORTANT
Changing the vardecimal storage format state of a database can affect backup and recovery, database mirroring,
sp_attach_db, log shipping, and replication.

Syntax
sp_db_vardecimal_storage_format [ [ @dbname = ] 'database_name']
[ , [ @vardecimal_storage_format = ] { 'ON' | 'OFF' } ]
[;]

Arguments
[ @dbname= ] 'database_name'
Is the name of the database for which the storage format is to be changed. database_name is sysname, with no
default. If the database name is omitted, the vardecimal storage format status of all the databases in the instance of
SQL Server are returned.
[ @vardecimal_storage_format= ] {'ON'|'OFF'}
Specifies whether the vardecimal storage format is enabled. @vardecimal_storage_format can be ON or OFF. The
parameter is varchar(3), with no default. If a database name is provided but @vardecimal_storage_format is
omitted, the current setting of the specified database is returned. This argument has no effect on SQL Server 2008
or later versions.

Return Code Values


0 (success) or 1 (failure)

Result Sets
If the database storage format cannot be changed, sp_db_vardecimal_storage_format returns an error. If the
database is already in the specified state, the stored procedure has no effect.
If the @vardecimal_storage_format argument is not provided, returns the columns Database Name and the
Vardecimal State.

Remarks
sp_db_vardecimal_storage_format returns the vardecimal state but cannot change the vardecimal state.
sp_db_vardecimal_storage_format will fail in the following circumstances:
There are active users in the database.
The database is enabled for mirroring.
The edition of SQL Server does not support vardecimal storage format.
To change the vardecimal storage format state to OFF, a database must be set to simple recovery mode.
When a database is set to simple recovery mode, the log chain is broken. Perform a full database backup
after you set the vardecimal storage format state to OFF.
Changing the state to OFF will fail if there are tables using vardecimal database compression. To change the
storage format of a table, use sp_tableoption. To determine which tables in a database are using vardecimal
storage format, use the OBJECTPROPERTY function and search for the TableHasVarDecimalStorageFormat
property, as shown in the following example.

USE AdventureWorks2012 ;
GO
SELECT name, object_id, type_desc
FROM sys.objects
WHERE OBJECTPROPERTY(object_id,
N'TableHasVarDecimalStorageFormat') = 1 ;
GO

Examples
The following code enables compression in the AdventureWorks2012 database, confirms the state, and then
compresses decimal and numeric columns in the Sales.SalesOrderDetail table.

USE master ;
GO

EXEC sp_db_vardecimal_storage_format 'AdventureWorks2012', 'ON' ;


GO

-- Check the vardecimal storage format state for


-- all databases in the instance.
EXEC sp_db_vardecimal_storage_format ;
GO

USE AdventureWorks2012 ;
GO

EXEC sp_tableoption 'Sales.SalesOrderDetail', 'vardecimal storage format', 1 ;


GO

See Also
Database Engine Stored Procedures (Transact-SQL)
sp_dbcmptlevel (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Sets certain database behaviors to be compatible with the specified version of SQL Server.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Do not use this feature in new development work,
and modify applications that currently use this feature as soon as possible. Use ALTER DATABASE Compatibility Levelinstead.

Transact-SQL Syntax Conventions

Syntax
sp_dbcmptlevel [ [ @dbname = ] name ]
[ , [ @new_cmptlevel = ] version ]

Arguments
[ @dbname= ] name
Is the name of the database for which the compatibility level is to be changed. Database names must conform to
the rules for identifiers. name is sysname, with a default of NULL.
[ @new_cmptlevel= ] version
Is the version of SQL Server with which the database is to be made compatible. version is tinyint, with a default of
NULL. The value must be one of the following:
90 = SQL Server 2005
100 = SQL Server 2008
110 = SQL Server 2012
120 = SQL Server 2014
130 = SQL Server 2016

Return Code Values


0 (success) or 1 (failure)

Result Sets
If no parameters are specified or if the name parameter is not specified, sp_dbcmptlevel returns an error.
If name is specified without version, the Database Engine returns a message displaying the current compatibility
level of the specified database.
Remarks
For a description of compatibilities levels, see ALTER DATABASE Compatibility Level (Transact-SQL).

Permissions
Only the database owner, members of the sysadmin fixed server role, and the db_owner fixed database role (if
you are changing the current database) can execute this procedure.

See Also
Database Engine Stored Procedures (Transact-SQL)
ALTER DATABASE (Transact-SQL)
Reserved Keywords (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_dbmmonitoraddmonitoring (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored
database on the server instance.
Transact-SQL Syntax Conventions

Syntax
sp_dbmmonitoraddmonitoring [ update_period ]

Arguments
update_period
Specifies the interval between updates in minutes. This value can be from 1 to 120 minutes. The default is 1
minute.

NOTE
If update period is set too low, the response time might increase for clients.

Return Code Values


None

Result Sets
None

Remarks
This procedure requires that SQL Server Agent is allowed to run on the server instance, and for the database
mirroring monitor job to run, Agent must be running.
If database mirroring is started from SQL Server Management Studio, the sp_dbmmonitoraddmonitoring
procedure is run automatically. If you start mirroring up manually using ALTER DATABASE statements, to monitor
mirrored database on the server instance, you must run sp_dbmmonitoraddmonitoring manually.

NOTE
If you run sp_dbmmonitoraddmonitoring before you set up database mirroring, the monitoring job will run but will not
update the status table in which database mirroring monitor history is stored.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example starts monitoring with an update period of 3 minutes.

EXEC sp_dbmmonitoraddmonitoring 3;

See Also
Monitoring Database Mirroring (SQL Server)
sp_dbmmonitorchangemonitoring (Transact-SQL)
sp_dbmmonitordropmonitoring (Transact-SQL)
sp_dbmmonitorhelpmonitoring (Transact-SQL)
sp_dbmmonitorresults (Transact-SQL)
sp_dbmmonitorchangealert (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds or changes warning threshold for a specified mirroring performance metric.
Transact-SQL Syntax Conventions

Syntax
sp_dbmmonitorchangealert database_name
, alert_id
, alert_threshold
, enabled

Arguments
database_name
Specifies the database for which to add or change the specified warning threshold.
alert_id
An integer value that identifies the warning to be added or changed. Specify one of the following values:

VALUE PERFORMANCE METRIC WARNING THRESHOLD

1 Oldest unsent transaction Specifies the number of minutes worth


of transactions that can accumulate in
the send queue before a warning is
generated on the principal server
instance. This warning helps measure
the potential for data loss in terms of
time, and it is particularly relevant for
high-performance mode. However, the
warning is also relevant for high-safety
mode when mirroring is paused or
suspended because the partners
become disconnected.

2 Unsent log Specifies how many kilobytes (KB) of


unsent log generate a warning on the
principal server instance. This warning
helps measure the potential for data
loss in terms of KB, and it is particularly
relevant for high-performance mode.
However, the warning is also relevant
for high-safety mode when mirroring is
paused or suspended because the
partners become disconnected.
VALUE PERFORMANCE METRIC WARNING THRESHOLD

3 Unrestored log Specifies how many KB of unrestored


log generate a warning on the mirror
server instance. This warning helps
measure failover time. Failover time
consists mainly of the time that the
former mirror server requires to roll
forward any log remaining in its redo
queue, plus a short additional time.

4 Mirror commit overhead Specifies the number of milliseconds of


average delay per transaction that are
tolerated before a warning is generated
on the principal server. This delay is the
amount of overhead incurred while the
principal server instance waits for the
mirror server instance to write the
transaction's log record into the redo
queue. This value is relevant only in
high-safety mode.

5 Retention period Metadata that controls how long rows


in the database mirroring status table
are preserved.

For information about the event IDs corresponding to the warnings, see Use Warning Thresholds and Alerts on
Mirroring Performance Metrics (SQL Server).
alert_threshold
The threshold value for the warning. If a value above this threshold is returned when the mirroring status is
updated, an entry is entered into the Windows event log. This value represents KB, minutes, or milliseconds,
depending on the performance metric.

NOTE
To view the current values, run the sp_dbmmonitorresults stored procedure.

enabled
Is the warning enabled?
0 = Warning is disabled.
1 = Warning is enabled.

NOTE
Retention period is always enabled.

Return Code Values


None

Result Sets
None
Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example sets thresholds for each of the performance metrics and the retention period for the
AdventureWorks2012 database. The following table shows the values used in the example.

ALERT_ID PERFORMANCE METRIC WARNING THRESHOLD IS THE WARNING ENABLED?

1 Oldest unsent transaction 30 minutes Yes

2 Unsent log 10,000 KB Yes

3 Unrestored log 10,000 KB Yes

4 Mirror commit overhead 1,000 milliseconds No

5 Retention period 8 hours Yes

EXEC sp_dbmmonitorchangealert AdventureWorks2012, 1, 30, 1 ;


EXEC sp_dbmmonitorchangealert AdventureWorks2012, 2, 10000, 1 ;
EXEC sp_dbmmonitorchangealert AdventureWorks2012, 3, 10000, 1 ;
EXEC sp_dbmmonitorchangealert AdventureWorks2012, 4, 1000, 0 ;
EXEC sp_dbmmonitorchangealert AdventureWorks2012, 5, 8, 1 ;

See Also
Monitoring Database Mirroring (SQL Server)
sp_dbmmonitorhelpalert (Transact-SQL)
sp_dbmmonitordropalert (Transact-SQL)
sp_dbmmonitorchangemonitoring (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the value of a database mirroring monitoring parameter.
Transact-SQL Syntax Conventions

Syntax
sp_dbmmonitorchangemonitoring parameter
, value

Arguments
parameter
Specifies the identifier of the parameter to be changed. Currently, only the following parameter is available:
1 = Update period
The number of minutes between updates to the database mirroring status table. The default interval is 1 minute.
value
Specifies the new value for the parameter that is being changed.

PARAMETER DESCRIPTION OF VALUE

1 An integer in the range of 1 to 120 that specifies a new


update period in minutes.

Return Code Values


None

Result Sets
None

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example changes the update period to 5 minutes.

EXEC sp_dbmmonitorchangemonitoring 1, 5 ;
See Also
Monitoring Database Mirroring (SQL Server)
sp_dbmmonitoraddmonitoring (Transact-SQL)
sp_dbmmonitordropmonitoring (Transact-SQL)
sp_dbmmonitorhelpmonitoring (Transact-SQL)
sp_dbmmonitorresults (Transact-SQL)
sp_dbmmonitordropalert (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops the warning for a specified performance metric, by setting the threshold to NULL.
Transact-SQL Syntax Conventions

Syntax
sp_dbmmonitordropalert database_name
[ , alert_id ]

Arguments
database_name
Specifies the database for which to drop the specified warning threshold.
alert_id
An integer value that identifies the warning to be dropped. If this argument is omitted, all warnings on the
database are dropped. To drop the warning for a specific performance metric, specify one of the following values:

VALUE PERFORMANCE METRIC WARNING THRESHOLD

1 Oldest unsent transaction Specifies the number of minutes worth


of transactions that can accumulate in
the send queue before a warning is
generated on the principal server
instance. This warning helps measure
the potential for data loss in terms of
time, and it is particularly relevant for
high-performance mode. However, the
warning is also relevant for high-safety
mode when mirroring is paused or
suspended because the partners
become disconnected.

2 Unsent log Specifies how many kilobytes (KB) of


unsent log generate a warning on the
principal server instance. This warning
helps measure the potential for data
loss in terms of KB, and it is particularly
relevant for high-performance mode.
However, the warning is also relevant
for high-safety mode when mirroring is
paused or suspended because the
partners become disconnected.
VALUE PERFORMANCE METRIC WARNING THRESHOLD

3 Unrestored log Specifies how many KB of unrestored


log generate a warning on the mirror
server instance. This warning helps
measure failover time. Failover time
consists mainly of the time that the
former mirror server requires to roll
forward any log remaining in its redo
queue, plus a short additional time.

4 Mirror commit overhead Specifies the number of milliseconds of


average delay per transaction that are
tolerated before a warning is generated
on the principal server. This delay is the
amount of overhead incurred while the
principal server instance waits for the
mirror server instance to write the
transaction's log record into the redo
queue. This value is relevant only in
high-safety mode.

5 Retention period Metadata that controls how long rows


in the database mirroring status table
are preserved.

NOTE
This procedure drops warning thresholds, regardless of whether they were specified using sp_dbmmonitorchangealert or
Database Mirroring Monitor.

For information about the event IDs corresponding to the warnings, see Use Warning Thresholds and Alerts on
Mirroring Performance Metrics (SQL Server).

Return Code Values


None

Result Sets
None

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example drops the retention period setting of the AdventureWorks2012 database.

EXEC sp_dbmmonitordropalert AdventureWorks2012, 5;

The following example drops all of the warning thresholds and the retention period of the AdventureWorks2012
database.
EXEC sp_dbmmonitordropalert AdventureWorks2012 ;

See Also
Monitoring Database Mirroring (SQL Server)
sp_dbmmonitorchangealert (Transact-SQL)
sp_dbmmonitordropmonitoring (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Stops and deletes the mirroring monitor job for all the databases on the server instance.
Transact-SQL Syntax Conventions

Syntax
sp_dbmmonitordropmonitoring

Arguments
None

Return Code Values


None

Result Sets
None

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example drops database mirroring monitoring on all of the mirrored databases on the server
instance.

EXEC sp_dbmmonitordropmonitoring ;

See Also
Monitoring Database Mirroring (SQL Server)
sp_dbmmonitorchangemonitoring (Transact-SQL)
sp_dbmmonitoraddmonitoring (Transact-SQL)
sp_dbmmonitorhelpmonitoring (Transact-SQL)
sp_dbmmonitorresults (Transact-SQL)
sp_dbmmonitorhelpalert (Transact-SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about warning thresholds on one or all of several key database mirroring monitor
performance metrics.
Transact-SQL Syntax Conventions

Syntax
sp_dbmmonitorhelpalert database_name
[ , alert_id ]

Arguments
database_name
Specifies the database.
[ alert_id ]
An integer value that identifies the warning to be returned. If this argument is omitted, all the warnings are
returned, but not the retention period.
To return a specific warning, specify one of the following values:

VALUE PERFORMANCE METRIC WARNING THRESHOLD

1 Oldest unsent transaction Specifies the number of minutes worth


of transactions that can accumulate in
the send queue before a warning is
generated on the principal server
instance. This warning helps measure
the potential for data loss in terms of
time, and it is particularly relevant for
high-performance mode. However, the
warning is also relevant for high-safety
mode when mirroring is paused or
suspended because the partners
become disconnected.

2 Unsent log Specifies how many kilobytes (KB) of


unsent log generate a warning on the
principal server instance. This warning
helps measure the potential for data
loss in terms of KB, and it is particularly
relevant for high-performance mode.
However, the warning is also relevant
for high-safety mode when mirroring is
paused or suspended because the
partners become disconnected.
VALUE PERFORMANCE METRIC WARNING THRESHOLD

3 Unrestored log Specifies how many KB of unrestored


log generate a warning on the mirror
server instance. This warning helps
measure failover time. Failover time
consists mainly of the time that the
former mirror server requires to roll
forward any log remaining in its redo
queue, plus a short additional time.

4 Mirror commit overhead Specifies the number of milliseconds of


average delay per transaction that are
tolerated before a warning is generated
on the principal server. This delay is the
amount of overhead incurred while the
principal server instance waits for the
mirror server instance to write the
transaction's log record into the redo
queue. This value is relevant only in
high-safety mode.

5 Retention period Metadata that controls how long rows


in the database mirroring status table
are preserved.

For information about the event IDs corresponding to the warnings, see Use Warning Thresholds and Alerts on
Mirroring Performance Metrics (SQL Server).

Return Code Values


None

Result Sets
For each returned alert, returns a row containing the following columns:

COLUMN DATA TYPE DESCRIPTION

alert_id int The table below lists the alert_id value


for each performance metric and the
unit of measurement of the metric
displayed in the
sp_dbmmonitorresults result set:

threshold int The threshold value for the warning. If a


value above this threshold is returned
when the mirroring status is updated,
an entry is entered into the Windows
event log. This value represents KB,
minutes, or milliseconds, depending on
the warning. If the threshold is currently
not set, the value is NULL.

Note: To view the current values, run


the sp_dbmmonitorresults stored
procedure.
COLUMN DATA TYPE DESCRIPTION

enabled bit 0 = Event is disabled.

1 = Event is enabled.

Note: Retention period is always


enabled.

VALUE PERFORMANCE METRIC UNIT

1 Oldest unsent transaction Minutes

2 Unsent log KB

3 Unrestored log KB

4 Mirror commit overhead Milliseconds

5 Retention period Hours

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example returns a row that indicates whether a warning is enabled for the oldest unsent transaction
performance metric on the AdventureWorks2012 database.

EXEC sp_dbmmonitorhelpalert AdventureWorks2012, 1 ;

The following example returns a row for each performance metric that indicates whether it is enabled on the
AdventureWorks2012 database.

EXEC sp_dbmmonitorhelpalert AdventureWorks2012;

See Also
Monitoring Database Mirroring (SQL Server)
sp_dbmmonitorchangealert (Transact-SQL)
sp_dbmmonitorchangemonitoring (Transact-SQL)
sp_dbmmonitordropalert (Transact-SQL)
sp_dbmmonitorupdate (Transact-SQL)
sp_dbmmonitorhelpmonitoring (Transact-SQL)
sp_dbmmonitorresults (Transact-SQL)
sp_dbmmonitorhelpmonitoring (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the current update period.
Transact-SQL Syntax Conventions

Syntax
sp_dbmmonitorhelpmonitoring

Arguments
None

Return Code Values


None

Result Sets
Returns the current update period, that is, the number of minutes between updates of database mirroring status
table. This value ranges from 1 to 120 minutes.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example returns the current update period.

EXEC sp_dbmmonitorhelpmonitoring;

See Also
Monitoring Database Mirroring (SQL Server)
sp_dbmmonitorresults (Transact-SQL)
sp_dbmmonitorresults (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns status rows for a monitored database from the status table in which database mirroring monitoring
history is stored and allows you to choose whether the procedure obtains the latest status beforehand.
Transact-SQL Syntax Conventions

Syntax
sp_dbmmonitorresults database_name
, rows_to_return
, update_status

Arguments
database_name
Specifies the database for which to return mirroring status.
rows_to_return
Specifies the quantity of rows returned:
0 = Last row
1 = Rows last two hours
2 = Rows last four hours
3 = Rows last eight hours
4 = Rows last day
5 = Rows last two days
6 = Last 100 rows
7 = Last 500 rows
8 = Last 1,000 rows
9 = Last 1,000,000 rows
update_status
Specifies that before returning results the procedure:
0 = Does not update the status for the database. The results are computed using just the last two rows, the age of
which depends on when the status table was refreshed.
1 = Updates the status for the database by calling sp_dbmmonitorupdate before computing the results.
However, if the status table has been updated within the previous 15 seconds, or the user is not a member of the
sysadmin fixed server role, sp_dbmmonitorresults runs without updating the status.
Return Code Values
None

Result Sets
Returns the requested number of rows of history status for the specified database. Each row contains the
following information:

COLUMN NAME DATA TYPE DESCRIPTION

database_name sysname Name of a mirrored database.

role int Current mirroring role of the server


instance:

1 = Principal

2 = Mirror

mirroring_state int State of the database:

0 = Suspended

1 = Disconnected

2 = Synchronizing

3 = Pending Failover

4 = Synchronized

witness_status int Connection status of the witness in the


database mirroring session of the
database, can be:

0 = Unknown

1 = Connected

2 = Disconnected

log_generation_rate int Amount of log generated since


preceding update of the mirroring
status of this database in kilobytes/sec.

unsent_log int Size of the unsent log in the send


queue on the principal in kilobytes.

send_rate int Send rate of log from the principal to


the mirror in kilobytes/sec.

unrestored_log int Size of the redo queue on the mirror in


kilobytes.

recovery_rate int Redo rate on the mirror in


kilobytes/sec.
COLUMN NAME DATA TYPE DESCRIPTION

transaction_delay int Total delay for all transactions in


milliseconds.

transactions_per_sec int Number of transactions that are


occurring per second on the principal
server instance.

average_delay int Average delay on the principal server


instance for each transaction because
of database mirroring. In high-
performance mode (that is, when the
SAFETY property is set to OFF), this
value is generally 0.

time_recorded datetime Time at which the row was recorded by


the database mirroring monitor. This is
the system clock time of the principal.

time_behind datetime Approximate system-clock time of the


principal to which the mirror database
is currently caught up. This value is
meaningful only on the principal server
instance.

local_time datetime System clock time on the local server


instance when this row was updated.

Remarks
sp_dbmmonitorresults can be executed only in the context of the msdb database.

Permissions
Requires membership in the sysadmin fixed server role or in the dbm_monitor fixed database role in the msdb
database. The dbm_monitor role enables its members to view database mirroring status, but not update it but
not view or configure database mirroring events.

NOTE
The first time that sp_dbmmonitorupdate executes, it creates the dbm_monitor fixed database role in the msdb
database. Members of the sysadmin fixed server role can add any user to the dbm_monitor fixed database role.

Examples
The following example returns the rows recorded during the preceding two hours without updating the status of
the database.

USE msdb;
EXEC sp_dbmmonitorresults AdventureWorks2012, 2, 0;

See Also
Monitoring Database Mirroring (SQL Server)
sp_dbmmonitorchangemonitoring (Transact-SQL)
sp_dbmmonitoraddmonitoring (Transact-SQL)
sp_dbmmonitordropmonitoring (Transact-SQL)
sp_dbmmonitorhelpmonitoring (Transact-SQL)
sp_dbmmonitorupdate (Transact-SQL)
sp_dbmmonitorupdate (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates the database mirroring monitor status table by inserting a new table row for each mirrored database, and
truncates rows older than the current retention period. The default retention period is 7 days (168 hours). When
updating the table, sp_dbmmonitorupdate evaluates the performance metrics.

NOTE
The first time sp_dbmmonitorupdate runs, it creates the database mirroring status table and the dbm_monitor fixed
database role in the msdb database.

Transact-SQL Syntax Conventions

Syntax
sp_dbmmonitorupdate [ database_name ]

Arguments
database_name
The name of the database for which to update mirroring status. If database_name is not specified, the procedure
updates the status table for every mirrored database on the server instance.

Return Code Values


None

Result Sets
None

Remarks
sp_dbmmonitorupdate can be executed only in the context of the msdb database.
If a column of the status table does not apply to the role of a partner, the value is NULL on that partner. A column
would also have a NULL value if the relevant information is unavailable, such as during a failover or server restart.
After sp_dbmmonitorupdate creates the dbm_monitor fixed database role in the msdb database, members of
the sysadmin fixed server role can add any user to the dbm_monitor fixed database role. The dbm_monitor role
enables its members to view database mirroring status, but not update it but not view or configure database
mirroring events.
When updating the mirroring status of a database, sp_dbmmonitorupdate inspects the latest value of any
mirroring performance metric for which a warning threshold has been specified. If the value exceeds the threshold,
the procedure adds an informational event to the event log. All rates are averages since the last update. For more
information, see Use Warning Thresholds and Alerts on Mirroring Performance Metrics (SQL Server).

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example updates the mirroring status for just the AdventureWorks2012 database.

USE msdb;
EXEC sp_dbmmonitorupdate AdventureWorks2012 ;

See Also
Monitoring Database Mirroring (SQL Server)
sp_dbmmonitorchangealert (Transact-SQL)
sp_dbmmonitorchangemonitoring (Transact-SQL)
sp_dbmmonitordropalert (Transact-SQL)
sp_dbmmonitorhelpalert (Transact-SQL)
sp_dbmmonitorhelpmonitoring (Transact-SQL)
sp_dbmmonitorresults (Transact-SQL)
sp_dbremove (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a database and all files associated with that database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. We recommend that you use DROP DATABASE instead.

Transact-SQL Syntax Conventions

Syntax
sp_dbremove [ @dbname = ] 'database' [ , [ @dropdev = ] 'dropdev' ]

Arguments
[ @dbname= ] 'database'
Is the name of the database to be removed. database is sysname, with a default value of NULL.
[ @dropdev= ] 'dropdev'
Is a flag provided for backward compatibility only and is currently ignored. dropdev has the value dropdev.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example removes a database named sales and all files associated with it.

EXEC sp_dbremove sales;

See Also
ALTER DATABASE (Transact-SQL)
CREATE DATABASE (SQL Server Transact-SQL)
DBCC (Transact-SQL)
sp_detach_db (Transact-SQL)
sp_delete_backuphistory (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Reduces the size of the backup and restore history tables by deleting the entries for backup sets older than the
specified date. Additional rows are added to the backup and restore history tables after each backup or restore
operation is performed; therefore, we recommend that you periodically execute sp_delete_backuphistory.

NOTE
The backup and restore history tables reside in the msdb database.

Transact-SQL Syntax Conventions

Syntax
sp_delete_backuphistory [ @oldest_date = ] 'oldest_date'

Arguments
[ @oldest_date= ] 'oldest_date'
Is the oldest date retained in the backup and restore history tables. oldest_date is datetime, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_delete_backuphistory must be run from the msdb database and affects the following tables:
backupfile
backupfilegroup
backupmediafamily
backupmediaset
backupset
restorefile
restorefilegroup
restorehistory
The physical backup files are preserved, even if all the history is deleted.

Permissions
Requires membership in the sysadmin fixed server role, but permissions can be granted to other users.

Examples
The following example deletes all entries that are older than January 14, 2010, 12:00 A.M. in the backup and
restore history tables.

USE msdb;
GO
EXEC sp_delete_backuphistory @oldest_date = '01/14/2010';

See Also
sp_delete_database_backuphistory (Transact-SQL)
Backup History and Header Information (SQL Server)
sp_delete_database_backuphistory (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes information about the specified database from the backup and restore history tables.
Transact-SQL Syntax Conventions

Syntax
sp_delete_database_backuphistory [ @database_name = ] 'database_name'

Arguments
[ @database_name= ] database_name
Specifies the name of the database involved in backup and restore operations. database_name is sysname, with
no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_delete_database_backuphistory must be run from the msdb database.
This stored procedure affects the following tables:
backupfile
backupfilegroup
backupmediafamily
backupmediaset
backupset
restorefile
restorefilegroup
restorehistory

Permissions
Requires membership in the sysadmin fixed server role.
Examples
The following example deletes all entries for the AdventureWorks2012 database in the backup-and-restore
history tables.

USE msdb;
GO
EXEC sp_delete_database_backuphistory @database_name = 'AdventureWorks2012';

See Also
sp_delete_backuphistory (Transact-SQL)
Backup History and Header Information (SQL Server)
sp_depends (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Displays information about database object dependencies, such as the views and procedures that depend on a
table or view, and the tables and views that are depended on by the view or procedure. References to objects
outside the current database are not reported.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use sys.dm_sql_referencing_entities and
sys.dm_sql_referenced_entities instead.

Transact-SQL Syntax Conventions

Syntax
sp_depends [ @objname = ] '<object>'

<object> ::=
{
[ database_name. [ schema_name ] . | schema_name.
object_name
}

Arguments
database_name
Is the name of the database.
schema_name
Is the name of the schema to which the object belongs.
object_name
Is the database object to examine for dependencies. The object can be a table, view, stored procedure, user-defined
function, or trigger. object_name is nvarchar(776), with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
sp_depends displays two result sets.
The following result set shows the objects on which <object> depends.
COLUMN NAME DATA TYPE DESCRIPTION

name nvarchar(257 ) Name of the item for which a


dependency exists.

type nvarchar(16) Type of the item.

updated nvarchar(7) Whether the item is updated.

selected nvarchar(8) Whether the item is used in a SELECT


statement.

column sysname Column or parameter on which the


dependency exists.

The following result set shows the objects that depend on <object>.

COLUMN NAME DATA TYPE DESCRIPTION

name nvarchar(257 ) Name of the item for which a


dependency exists.

type nvarchar(16) Type of the item.

Permissions
Requires membership in the public role.

Examples
A. Listing dependencies on a table
The following example lists the database objects that depend on the Sales.Customer table in the
AdventureWorks2012 database. Both the schema name and table name are specified.

USE AdventureWorks2012;
GO
EXEC sp_depends @objname = N'Sales.Customer' ;

B. Listing dependencies on a trigger


The following example lists the database objects on which the trigger iWorkOrder depends.

EXEC sp_depends @objname = N'AdventureWorks2012.Production.iWorkOrder' ;

See Also
Database Engine Stored Procedures (Transact-SQL)
EXECUTE (Transact-SQL)
sp_help (Transact-SQL)
System Stored Procedures (Transact-SQL)
sys.sql_dependencies (Transact-SQL)
sp_describe_first_result_set (Transact-SQL)
1/2/2018 • 14 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the metadata for the first possible result set of the Transact-SQL batch. Returns an empty result set if the
batch returns no results. Raises an error if the Database Engine cannot determine the metadata for the first query
that will be executed by performing a static analysis. The dynamic management view
sys.dm_exec_describe_first_result_set (Transact-SQL) returns the same information.
Transact-SQL Syntax Conventions

Syntax
sp_describe_first_result_set [ @tsql = ] N'Transact-SQL_batch'
[ , [ @params = ] N'parameters' ]
[ , [ @browse_information_mode = ] <tinyint> ] ]

Arguments
[ @tsql = ] 'Transact-SQL_batch'
One or more Transact-SQL statements. Transact-SQL_batch may be nvarchar(n) or nvarchar(max).
[ @params = ] N'parameters'
@params provides a declaration string for parameters for the Transact-SQL batch, which is similar to
sp_executesql. Parameters may be nvarchar(n) or nvarchar(max).
Is one string that contains the definitions of all parameters that have been embedded in the Transact-SQL_batch.
The string must be either a Unicode constant or a Unicode variable. Each parameter definition consists of a
parameter name and a data type. n is a placeholder that indicates additional parameter definitions. Every
parameter specified in the statement must be defined in @params. If the Transact-SQL statement or batch in the
statement does not contain parameters, @params is not required. NULL is the default value for this parameter.
[ @browse_information_mode = ] tinyint
Specifies if additional key columns and source table information are returned. If set to 1, each query is analyzed as
if it includes a FOR BROWSE option on the query. Additional key columns and source table information are
returned.
If set to 0, no information is returned.
If set to 1, each query is analyzed as if it includes a FOR BROWSE option on the query. This will return base
table names as the source column information.
If set to 2, each query is analyzed as if it would be used in preparing or executing a cursor. This will return
view names as source column information.

Return Code Values


sp_describe_first_result_set always returns a status of zero on success. If the procedure throws an error and the
procedure is called as an RPC, return status is populated by the type of error described in the error_type column of
sys.dm_exec_describe_first_result_set. If the procedure is called from Transact-SQL, the return value is always zero,
even when there is an error.

Result Sets
This common metadata is returned as a result set with one row for each column in the results metadata. Each row
describes the type and nullability of the column in the format described in the following section. If the first
statement does not exist for every control path, a result set with zero rows is returned.

COLUMN NAME DATA TYPE DESCRIPTION

is_hidden bit NOT NULL Indicates that the column is an extra


column added for browsing information
purposes and that it does not actually
appear in the result set.

column_ordinal int NOT NULL Contains the ordinal position of the


column in the result set. The first
column’s position will be specified as 1.

name sysname NULL Contains the name of the column if a


name can be determined. Otherwise, it
will contain NULL.

is_nullable bit NOT NULL Contains the value 1 if the column


allows NULLs, 0 if the column does not
allow NULLs, and 1 if it cannot be
determined if the column allows NULLs.

system_type_id int NOT NULL Contains the system_type_id of the


data type of the column as specified in
sys.types. For CLR types, even though
the system_type_name column will
return NULL, this column will return the
value 240.

system_type_name nvarchar(256) NULL Contains the name and arguments


(such as length, precision, scale),
specified for the data type of the
column. If the data type is a user-
defined alias type, the underlying
system type is specified here. If it is a
CLR user-defined type, NULL is
returned in this column.

max_length smallint NOT NULL Maximum length (in bytes) of the


column.

-1 = Column data type is


varchar(max), nvarchar(max),
varbinary(max), or xml.

For text columns, the max_length


value will be 16 or the value set by
sp_tableoption 'text in row'.

precision tinyint NOT NULL Precision of the column if numeric-


based. Otherwise returns 0.
COLUMN NAME DATA TYPE DESCRIPTION

scale tinyint NOT NULL Scale of column if numeric-based.


Otherwise returns 0.

collation_name sysname NULL Name of the collation of the column if


character-based. Otherwise returns
NULL.

user_type_id int NULL For CLR and alias types, contains the
user_type_id of the data type of the
column as specified in sys.types.
Otherwise is NULL.

user_type_database sysname NULL For CLR and alias types, contains the
name of the database in which the type
is defined. Otherwise is NULL.

user_type_schema sysname NULL For CLR and alias types, contains the
name of the schema in which the type
is defined. Otherwise is NULL.

user_type_name sysname NULL For CLR and alias types, contains the
name of the type. Otherwise is NULL.

assembly_qualified_type_name nvarchar(4000) For CLR types, returns the name of the


assembly and class defining the type.
Otherwise is NULL.

xml_collection_id int NULL Contains the xml_collection_id of the


data type of the column as specified in
sys.columns. This column will return
NULL if the type returned is not
associated with an XML schema
collection.

xml_collection_database sysname NULL Contains the database in which the


XML schema collection associated with
this type is defined. This column will
return NULL if the type returned is not
associated with an XML schema
collection.

xml_collection_schema sysname NULL Contains the schema in which the XML


schema collection associated with this
type is defined. This column will return
NULL if the type returned is not
associated with an XML schema
collection.

xml_collection_name sysname NULL Contains the name of the XML schema


collection associated with this type. This
column will return NULL if the type
returned is not associated with an XML
schema collection.
COLUMN NAME DATA TYPE DESCRIPTION

is_xml_document bit NOT NULL Returns 1 if the returned data type is


XML and that type is guaranteed to be
a complete XML document (including a
root node), as opposed to an XML
fragment). Otherwise returns 0.

is_case_sensitive bit NOT NULL Returns 1 if the column is a case-


sensitive string type and 0 if it is not.

is_fixed_length_clr_type bit NOT NULL Returns 1 if the column is a fixed-length


CLR type and 0 if it is not.

source_server sysname Name of the originating server returned


by the column in this result (if it
originates from a remote server). The
name is given as it appears in
sys.servers. Returns NULL if the column
originates on the local server or if it
cannot be determined which server it
originates on. Is only populated if
browsing information is requested.

source_database sysname Name of the originating database


returned by the column in this result.
Returns NULL if the database cannot be
determined. Is only populated if
browsing information is requested.

source_schema sysname Name of the originating schema


returned by the column in this result.
Returns NULL if the schema cannot be
determined. Is only populated if
browsing information is requested.

source_table sysname Name of the originating table returned


by the column in this result. Returns
NULL if the table cannot be determined.
Is only populated if browsing
information is requested.

source_column sysname Name of the originating column


returned by the result column. Returns
NULL if the column cannot be
determined. Is only populated if
browsing information is requested.

is_identity_column bit NULL Returns 1 if the column is an identity


column and 0 if not. Returns NULL if it
cannot be determined that the column
is an identity column.
COLUMN NAME DATA TYPE DESCRIPTION

is_part_of_unique_key bit NULL Returns 1 if the column is part of a


unique index (including unique and
primary constraint) and 0 if not. Returns
NULL if it cannot be determined that
the column is part of a unique index.
Only populated if browsing information
is requested.

is_updateable bit NULL Returns 1 if the column is updateable


and 0 if not. Returns NULL if it cannot
be determined that the column is
updateable.

is_computed_column bit NULL Returns 1 if the column is a computed


column and 0 if not. Returns NULL if it
cannot be determined that the column
is a computed column.

is_sparse_column_set bit NULL Returns 1 if the column is a sparse


column and 0 if not. Returns NULL if it
cannot be determined that the column
is part of a sparse column set.

ordinal_in_order_by_list smallint NULL Position of this column in ORDER BY


list. Returns NULL if the column does
not appear in the ORDER BY list or if
the ORDER BY list cannot be uniquely
determined.

order_by_list_length smallint NULL Length of the ORDER BY list. Returns


NULL if there is no ORDER BY list or if
the ORDER BY list cannot be uniquely
determined. Note that this value will be
the same for all rows returned by
sp_describe_first_result_set.

order_by_is_descending smallint NULL If the ordinal_in_order_by_list is not


NULL, the order_by_is_descending
column reports the direction of the
ORDER BY clause for this column.
Otherwise it reports NULL.

tds_type_id int NOT NULL For internal use.

tds_length int NOT NULL For internal use.

tds_collation_id int NULL For internal use.

tds_collation_sort_id tinyint NULL For internal use.

Remarks
sp_describe_first_result_set guarantees that if the procedure returns the first result-set metadata for (a
hypothetical) batch A and if that batch (A) is subsequently executed then the batch will either (1) raises an
optimization-time error, (2) raises a run-time error, (3) returns no result set, or (4) returns a first result set with the
same metadata described by sp_describe_first_result_set.
The name, nullability, and data type can differ. If sp_describe_first_result_set returns an empty result set, the
guarantee is that the batch execution will return no-result sets.
This guarantee presumes there are are no relevant schema changes on the server. Relevant schema changes on the
server do not include creating a temporary tables or table variables in the batch A between the time that
sp_describe_first_result_set is called and the time that the result set is returned during execution, including
schema changes made by batch B.
sp_describe_first_result_set returns an error in any of the following cases.
If the input @tsql is not a valid Transact-SQL batch. Validity is determined by parsing and analyzing the
Transact-SQL batch. Any errors caused by the batch during query optimization or during execution are not
considered when determining whether the Transact-SQL batch is valid.
If @params is not NULL and contains a string that is not a syntactically valid declaration string for
parameters, or if it contains a string that declares any parameter more than one time.
If the input Transact-SQL batch declares a local variable of the same name as a parameter declared in
@params.
If the statement uses a temporary table.
The query includes the creation of a permanent table that is then queried.
If all other checks succeed, all possible control flow paths inside the input batch are considered. This takes
into account all control flow statements (GOTO, IF/ELSE, WHILE, and Transact-SQL TRY/CATCH blocks) as
well as any procedures, dynamic Transact-SQL batches, or triggers invoked from the input batch by an EXEC
statement, a DDL statement that causes DDL triggers to be fired, or a DML statement that causes triggers to
be fired on a target table or on a table that is modified because of cascading action on a foreign key
constraint. In the case of many possible control paths, at some point an algorithm stops.
For each control flow path, the first statement (if any) that returns a result set is determined by
sp_describe_first_result_set.
When multiple possible first statements are found in a batch, their results can differ in number of columns,
column name, nullability, and data type. How these differences are handled is described in more detail here:
If the number of columns differs, an error is thrown and no result is returned.
If the column name differs, the column name returned is set to NULL.
It the nullability differs, the nullability returned will allow NULLs.
If the data type differs, an error will be thrown and no result is returned except for the following cases:
varchar(a) to varchar(a') where a' > a.
varchar(a) to varchar(max)
nvarchar(a) to nvarchar(a') where a' > a.
nvarchar(a) to nvarchar(max)
varbinary(a) to varbinary(a') where a' > a.
varbinary(a) to varbinary(max)
sp_describe_first_result_set does not support indirect recursion.
Permissions
Requires permission to execute the @tsql argument.

Examples
Typical Examples
A. Simple Example
The following example describes the result set returned from a single query.

sp_describe_first_result_set @tsql = N'SELECT object_id, name, type_desc FROM sys.indexes'

The following example shows the result set returned from a single query that contains a parameter.

sp_describe_first_result_set @tsql =
N'SELECT object_id, name, type_desc
FROM sys.indexes
WHERE object_id = @id1'
, @params = N'@id1 int'

B. Browse Mode Examples


The following three examples illustrate the key difference between the different browse information modes. Only
the relevant columns have been included in the query results.
Example using 0 indicating no information is returned.

CREATE TABLE dbo.t (a int PRIMARY KEY, b1 int);


GO
CREATE VIEW dbo.v AS SELECT b1 AS b2 FROM dbo.t;
GO
EXEC sp_describe_first_result_set N'SELECT b2 AS b3 FROM dbo.v', null, 0;

Here is the result set.

COLUMN_ORDI SOURCE_SCHE SOURCE_COLU IS_PART_OF_UN


IS_HIDDEN NAL NAME MA SOURCE_TABLE MN IQUE_KEY

0 1 b3 NULL NULL NULL NULL

Example using 1 indicating it returns information as if it includes a FOR BROWSE option on the query.

EXEC sp_describe_first_result_set N'SELECT b2 AS b3 FROM v', null, 1

Here is the result set.

COLUMN_ORDI SOURCE_SCHE SOURCE_COLU IS_PART_OF_UN


IS_HIDDEN NAL NAME MA SOURCE_TABLE MN IQUE_KEY

0 1 b3 dbo t B1 0

1 2 a dbo t a 1

Example using 2 indicating analyzed as if you are preparing a cursor.


EXEC sp_describe_first_result_set N'SELECT b2 AS b3 FROM v', null, 2

Here is the result set.

COLUMN_ORDI SOURCE_SCHE SOURCE_COLU IS_PART_OF_UN


IS_HIDDEN NAL NAME MA SOURCE_TABLE MN IQUE_KEY

0 1 B3 dbo v B2 0

1 2 ROWSTAT NULL NULL NULL 0

Examples of problems
The following examples use two tables for all examples. Execute the following statements to create the example
tables.

CREATE TABLE dbo.t1 (a int NULL, b varchar(10) NULL, c nvarchar(10) NULL);


CREATE TABLE dbo.t2 (a smallint NOT NULL, d varchar(20) NOT NULL, e int NOT NULL);

Error because the number of columns differ


Number of columns in possible first result sets differ in this example.

sp_describe_first_result_set @tsql =
N'
IF(1=1)
SELECT a FROM t1;
ELSE
SELECT a, b FROM t1;
SELECT * FROM t; -- Ignored, not a possible first result set.'

Error because the data types differ


Columns types differ in different possible first result sets.

sp_describe_first_result_set @tsql =
N'
IF(1=1)
SELECT a FROM t1;
ELSE
SELECT a FROM t2;

Result: Error, mismatching types (int vs. smallint).


Column name cannot be determined
Columns in possible first result sets differ by length for same variable length type, nullability, and column names:

sp_describe_first_result_set @tsql =
N'
IF(1=1)
SELECT b FROM t1;
ELSE
SELECT d FROM t2; '

Result: <Unknown Column Name> varchar(20) NULL


Column name forced to be identical through aliasing
Same as previous, but columns have the same name through column aliasing.
sp_describe_first_result_set @tsql =
N'
IF(1=1)
SELECT b FROM t1;
ELSE
SELECT d AS b FROM t2;'

Result: b varchar(20)NULL
Error because column types cannot be matched
The columns types differ in different possible first result sets.

sp_describe_first_result_set @tsql =
N'
IF(1=1)
SELECT b FROM t1;
ELSE
SELECT c FROM t1;'

Result: Error, mismatching types (varchar(10) vs. nvarchar(10)).


Result set can return an error
First result set is either error or result set.

sp_describe_first_result_set @tsql =
N'
IF(1=1)
RAISERROR(''Some Error'', 16, 1);

ELSE
SELECT a FROM t1;
SELECT e FROM t2; -- Ignored, not a possible first result set.;'

Result: a intNULL
Some code paths return no results
First result set is either null or a result set.

sp_describe_first_result_set @tsql =
N'
IF(1=1)
RETURN;
SELECT a FROM t1;'

Result: a intNULL
Result from dynamic SQL
First result set is dynamic SQL that is discoverable because it is a literal string.

sp_describe_first_result_set @tsql =
N'EXEC(N''SELECT a FROM t1'');'

Result: a INT NULL


Result failure from dynamic SQL
First result set is undefined because of dynamic SQL.
sp_describe_first_result_set @tsql =
N'
DECLARE @SQL NVARCHAR(max);
SET @SQL = N''SELECT a FROM t1 WHERE 1 = 1 '';
IF(1=1)
SET @SQL += N'' AND e > 10 '';
EXEC(@SQL); '

Result: Error. Result is not discoverable because of the dynamic SQL.


Result set specified by user
First result set is specified manually by user.

sp_describe_first_result_set @tsql =
N'
DECLARE @SQL NVARCHAR(max);
SET @SQL = N''SELECT a FROM t1 WHERE 1 = 1 '';
IF(1=1)
SET @SQL += N'' AND e > 10 '';
EXEC(@SQL)
WITH RESULT SETS(
(Column1 BIGINT NOT NULL)
); '

Result: Column1 bigint NOT NULL


Error caused by a ambiguous result set
This example assumes that another user named user1 has a table named t1 in the default schema s1 with columns
(a int NOT NULL).

sp_describe_first_result_set @tsql =
N'
IF(@p > 0)
EXECUTE AS USER = ''user1'';
SELECT * FROM t1;'
, @params = N'@p int'

Result: Error. t1 can be either dbo.t1 or s1.t1, each with a different number of columns.
Result even with ambiguous result set
Use the same assumptions as the previous example.

sp_describe_first_result_set @tsql =
N'
IF(@p > 0)
EXECUTE AS USER = ''user1'';
SELECT a FROM t1;'

Result: a int NULL because both dbo.t1.a and s1.t1.a have type int and different nullability.

See Also
sp_describe_undeclared_parameters (Transact-SQL)
sys.dm_exec_describe_first_result_set (Transact-SQL)
sys.dm_exec_describe_first_result_set_for_object (Transact-SQL)
sp_describe_undeclared_parameters (Transact-SQL)
11/27/2017 • 12 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns a result set that contains metadata about undeclared parameters in a Transact-SQL batch. Considers each
parameter that is used in the @tsql batch, but not declared in @params. A result set is returned that contains one
row for each such parameter, with the deduced type information for that parameter. The procedure returns an
empty result set if the @tsql input batch has no parameters except those declared in @params.
Transact-SQL Syntax Conventions

Syntax
sp_describe_undeclared_parameters
[ @tsql = ] 'Transact-SQL_batch'
[ , [ @params = ] N'parameters' data type ] [, ...n]

Arguments
[ @tsql = ] 'Transact-SQL_batch'
One or more Transact-SQL statements. Transact-SQL_batch may be nvarchar(n) or nvarchar(max).
[ @params = ] N'parameters'
@params provides a declaration string for parameters for the Transact-SQL batch, similarly to the way
sp_executesql works. Parameters may be nvarchar(n) or nvarchar(max).
Is one string that contains the definitions of all parameters that have been embedded in Transact-SQL_batch. The
string must be either a Unicode constant or a Unicode variable. Each parameter definition consists of a parameter
name and a data type. n is a placeholder that indicates additional parameter definitions. If the Transact-SQL
statement or batch in the statement does not contain parameters, @params is not required. The default value for
this parameter is NULL.
Datatype
The data type of the parameter.

Return Code Values


sp_describe_undeclared_parameters always returns return status of zero on success. If the procedure throws an
error and the procedure is called as an RPC, the return status is populated by the type of error as described in the
error_type column of sys.dm_exec_describe_first_result_set. If the procedure is called from Transact-SQL, the
return value is always zero, even in error cases.

Result Sets
sp_describe_undeclared_parameters returns the following result set.
COLUMN NAME DATA TYPE DESCRIPTION

parameter_ordinal int NOT NULL Contains the ordinal position of the


parameter in the result set. Position of
the first parameter will be specified as 1.

name sysname NOT NULL Contains the name of the parameter.

suggested_system_type_id int NOT NULL Contains the system_type_id of the


data type of the parameter as specified
in sys.types.

For CLR types, even though the


system_type_name column will return
NULL, this column will return the value
240.

suggested_system_type_name nvarchar (256) NULL Contains the data type name. Includes
arguments (such as length, precision,
scale) specified for the data type of the
parameter. If the data type is a user-
defined alias type, the underlying
system type is specified here. If it is a
CLR user-defined data type, NULL is
returned in this column. If the type of
the parameter cannot be deduced,
NULL is returned.

suggested_max_length smallint NOT NULL See sys.columns. for max_length


column description.

suggested_precision tinyint NOT NULL See sys.columns. for precision column


description.

suggested_scale tinyint NOT NULL See sys.columns. for scale column


description.

suggested_user_type_id int NULL For CLR and alias types, contains the
user_type_id of the data type of the
column as specified in sys.types.
Otherwise is NULL.

suggested_user_type_database sysname NULL For CLR and alias types, contains the
name of the database in which the type
is defined. Otherwise is NULL.

suggested_user_type_schema sysname NULL For CLR and alias types, contains the
name of the schema in which the type
is defined. Otherwise is NULL.

suggested_user_type_name sysname NULL For CLR and alias types, contains the
name of the type. Otherwise is NULL.

suggested_assembly_qualified_type_ nvarchar (4000) NULL For CLR types, returns the name of the
name assembly and class that defines the
type. Otherwise is NULL.
COLUMN NAME DATA TYPE DESCRIPTION

suggested_xml_collection_id int NULL Contains the xml_collection_id of the


data type of the parameter as specified
in sys.columns. This column will return
NULL if the type returned is not
associated with an XML schema
collection.

suggested_xml_collection_database sysname NULL Contains the database in which the


XML schema collection associated with
this type is defined. This column will
return NULL if the type returned is not
associated with an XML schema
collection.

suggested_xml_collection_schema sysname NULL Contains the schema in which the XML


schema collection associated with this
type is defined. This column will return
NULL if the type returned is not
associated with an XML schema
collection.

suggested_xml_collection_name sysname NULL Contains the name of the XML schema


collection associated with this type. This
column will return NULL if the type
returned is not associated with an XML
schema collection.

suggested_is_xml_document bit NOT NULL Returns 1 if the type being returned is


XML and that type is guaranteed to be
an XML document. Otherwise returns 0.

suggested_is_case_sensitive bit NOT NULL Returns 1 if the column is of a case-


sensitive string type and 0 if it is not.

suggested_is_fixed_length_clr_type bit NOT NULL Returns 1 if the column is of a fixed-


length CLR type and 0 if it is not.

suggested_is_input bit NOT NULL Returns 1 if the parameter is used


anywhere other than left side of an
assignment. Otherwise returns 0.

suggested_is_output bit NOT NULL Returns 1 if the parameter is used on


the left side of an assignment or is
passed to an output parameter of a
stored procedure. Otherwise returns 0.

formal_parameter_name sysname NULL If the parameter is an argument to a


stored procedure or a user-defined
function, returns the name of the
corresponding formal parameter.
Otherwise returns NULL.

suggested_tds_type_id int NOT NULL For internal use.

suggested_tds_length int NOT NULL For internal use.


Remarks
sp_describe_undeclared_parameters always returns return status of zero.
The most common use is when an application is given a Transact-SQL statement that might contain parameters
and must process them in some way. An example is a user interface (such as ODBCTest or RowsetViewer) where
the user provides a query with ODBC parameter syntax. The application must dynamically discover the number of
parameters and prompt the user for each one.
Another example is when without user input, an application must loop over the parameters and obtain the data for
them from some other location (such as a table). In this case, the application does not have to pass all the
parameter information at once. Instead, the application can get all the parameters information from the provider
and obtain the data itself from the table. Code using sp_describe_undeclared_parameters is more generic and is
less likely to require modification if the data structure changes later.
sp_describe_undeclared_parameters returns an error in any of the following cases.
If the input @tsql is not a valid Transact-SQL batch. Validity is determined by parsing and analyzing the
Transact-SQL batch. Any errors caused by the batch during query optimization or during execution are not
considered when determining whether the Transact-SQL batch is valid.
If @params is not NULL and contains a string that is not a syntactically valid declaration string for
parameters, or if it contains a string that declares any parameter more than one time.
If the input Transact-SQL batch declares a local variable of the same name as a parameter declared in
@params.
If the statement creates any temporary tables.
If @tsql has no parameters, other than those declared in @params, the procedure returns an empty result
set.

Parameter Selection Algorithm


For a query with undeclared parameters, data type deduction for undeclared parameters proceeds in three steps.
Step 1
The first step in data type deduction for a query with undeclared parameters is to find the data types of all the sub-
expressions whose data types do not depend on the undeclared parameters. The type can be determined for the
following expressions:
Columns, constants, variables, and declared parameters.
Results of a call to a user-defined function (UDF).
An expression with data types that do not depend on the undeclared parameters for all inputs.
For example, consider the query SELECT dbo.tbl(@p1) + c1 FROM t1 WHERE c2 = @p2 + 2 . The expressions
dbo.tbl(@p1) + c1 and c2 have data types, and expression @p1 and @p2 + 2 do not.
After this step, if any expression (other than a call to a UDF) has two arguments without data types, type
deduction fails with an error. For example, the following all produce errors:

SELECT * FROM t1 WHERE @p1 = @p2


SELECT * FROM t1 WHERE c1 = @p1 + @p2
SELECT * FROM t1 WHERE @p1 = SUBSTRING(@p2, 2, 3)

The following example does not produce an error:


SELECT * FROM t1 WHERE @p1 = dbo.tbl(c1, @p2, @p3)

Step 2
For a given undeclared parameter @p, the type deduction algorithm finds the innermost expression E(@p) that
contains @p and is one of the following:
An argument to a comparison or assignment operator.
An argument to a user-defined function (including table-valued UDF), procedure, or method.
An argument to a VALUES clause of an INSERT statement.
An argument to a CAST or CONVERT.
The type deduction algorithm finds a target data type TT(@p) for E(@p). Target data types for the previous
examples are as follows:
The data type of the other side of the comparison or assignment.
The declared data type of the parameter to which this argument is passed.
The data type of the column into which this value is inserted.
The data type to which the statement is casting or converting.
For example, consider the query SELECT * FROM t WHERE @p1 = dbo.tbl(@p2 + c1) . Then E(@p1) = @p1,
E(@p2) = @p2 + c1, TT(@p1) is the declared return data type of dbo.tbl, and TT(@p2) is the declared
parameter data type for dbo.tbl.
If @p is not contained in any expression listed at the beginning of step 2, the type deduction algorithm
determines that E(@p) is the largest scalar expression that contains @p, and the type deduction algorithm
does not compute a target data type TT(@p) for E(@p). For example, if the query is SELECT @p + 2 then
E(@p) = @p + 2, and there is no TT(@p).
Step 3
Now that E(@p) and TT(@p) are identified, the type deduction algorithm deduces a data type for @p in one
of the following two ways:
Simple deduction
If E(@p) = @p and TT(@p) exists, i.e., if @p is directly an argument to one of the expressions listed at the
beginning of step 2, the type deduction algorithm deduces the data type of @p to be TT(@p). For example:

SELECT * FROM t WHERE c1 = @p1 AND @p2 = dbo.tbl(@p3)

The data type for @p1, @p2, and @p3 will be the data type of c1, the return data type of dbo.tbl, and the
parameter data type for dbo.tbl respectively.
As a special case, if @p is an argument to a <, >, <=, or >= operator, simple deduction rules do not apply.
The type deduction algorithm will use the general deduction rules explained in the next section. For
example, if c1 is a column of data type char(30), consider the following two queries:

SELECT * FROM t WHERE c1 = @p


SELECT * FROM t WHERE c1 > @p

In the first case, the type deduction algorithm deduces char(30) as the data type for @p as per rules earlier
in this topic. In the second case, the type deduction algorithm deduces varchar(8000) according to the
general deduction rules in the next section.
General deduction
If simple deduction does not apply, the following data types are considered for undeclared parameters:
Integer data types (bit, tinyint, smallint, int, bigint)
Money data types (smallmoney, money)
Floating-point data types (float, real)
numeric(38, 19) - Other numeric or decimal data types are not considered.
varchar(8000), varchar(max), nvarchar(4000), and nvarchar(max) - Other string data types (such
as text, char(8000), nvarchar(30), etc.) are not considered.
varbinary(8000) and varbinary(max) - Other binary data types are not considered (such as image,
binary(8000), varbinary(30), etc.).
date, time(7), smalldatetime, datetime, datetime2(7), datetimeoffset(7) - Other date and time
types, such as time(4), are not considered.
sql_variant
xml
CLR system-defined types (hierarchyid, geometry, geography)
CLR user-defined types
Selection Criteria
Of the candidate data types, any data type that would invalidate the query is rejected. Of the remaining candidate
data types, the type deduction algorithm selects one according to the following rules.
1. The data type that produces the smallest number of implicit conversions in E(@p) is selected. If a particular
data type produces a data type for E(@p) that is different from TT(@p), the type deduction algorithm
considers this to be an extra implicit conversion from the data type of E(@p) to TT(@p).
For example:

SELECT * FROM t WHERE Col_Int = Col_Int + @p

In this case, E(@p) is Col_Int + @p and TT(@p) is int. int is chosen for @p because it produces no implicit
conversions. Any other choice of data type produces at least one implicit conversion.
2. If multiple data types tie for the smallest number of conversions, the data type with greater precedence is
used. For example

SELECT * FROM t WHERE Col_Int = Col_smallint + @p

In this case, int and smallint produce one conversion. Every other data type produces more than one
conversion. Because int takes precedence over smallint, int is used for @p. For more information about
data type precedence, see Data Type Precedence (Transact-SQL).
This rule only applies if there is an implicit conversion between every data type that ties according to rule 1
and the data type with the greatest precedence. If there is no implicit conversion, then data type deduction
fails with an error. For example in the query SELECT @p FROM t , data type deduction fails because any data
type for @p would be equally good. For example, there is no implicit conversion from int to xml.
3. If two similar data types tie under rule 1, for example varchar(8000) and varchar(max), the smaller data
type (varchar(8000)) is chosen. The same principle applies to nvarchar and varbinary data types.
4. For purposes of rule 1, the type deduction algorithm prefers certain conversions as better than others.
Conversions in order from best to worst are:
a. Conversion between same basic data type of different length.
b. Conversion between fixed-length and variable-length version of same data types (e.g., char to
varchar).
c. Conversion between NULL and int.
d. Any other conversion.
For example, for the query SELECT * FROM t WHERE [Col_varchar(30)] > @p , varchar(8000) is chosen because
conversion (a) is best. For the query SELECT * FROM t WHERE [Col_char(30)] > @p , varchar(8000) is still
chosen because it causes a type (b) conversion, and because another choice (such as varchar(4000)) would
cause a type (d) conversion.
As a final example, given a query SELECT NULL + @p , int is chosen for @p because it results in a type (c)
conversion.

Permissions
Requires permission to execute the @tsql argument.

Examples
The following example returns information such as the expected data type for the undeclared @id and @name
parameters.

sp_describe_undeclared_parameters @tsql =
N'SELECT object_id, name, type_desc
FROM sys.indexes
WHERE object_id = @id OR name = @name'

When the @id parameter is provided as a @params reference, the @id parameter is omitted from the result set
and only the @name parameter is described.

sp_describe_undeclared_parameters @tsql =
N'SELECT object_id, name, type_desc
FROM sys.indexes
WHERE object_id = @id OR NAME = @name',
@params = N'@id int'

See Also
sp_describe_first_result_set (Transact-SQL)
sys.dm_exec_describe_first_result_set (Transact-SQL)
sys.dm_exec_describe_first_result_set_for_object (Transact-SQL)
sp_detach_db (Transact-SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Detaches a database that is currently not in use from a server instance and, optionally, runs UPDATE STATISTICS
on all tables before detaching.

IMPORTANT
For a replicated database to be detached, it must be unpublished. For more information, see the "Remarks" section later in
this topic.

Transact-SQL Syntax Conventions

Syntax
sp_detach_db [ @dbname= ] 'database_name'
[ , [ @skipchecks= ] 'skipchecks' ]
[ , [ @keepfulltextindexfile = ] 'KeepFulltextIndexFile' ]

Arguments
[ @dbname = ] 'database_name'
Is the name of the database to be detached. database_name is a sysname value, with a default value of NULL.
[ @skipchecks = ] 'skipchecks'
Specifies whether to skip or run UPDATE STATISTIC. skipchecks is a nvarchar(10) value, with a default value of
NULL. To skip UPDATE STATISTICS, specify true. To explicitly run UPDATE STATISTICS, specify false.
By default, UPDATE STATISTICS is performed to update information about the data in the tables and indexes.
Performing UPDATE STATISTICS is useful for databases that are to be moved to read-only media.
[ @keepfulltextindexfile= ] 'KeepFulltextIndexFile'
Specifies that the full-text index file associated with the database that is being detached will not be dropped during
the database detach operation. KeepFulltextIndexFile is a nvarchar(10) value with a default of true. If
KeepFulltextIndexFile is false, all the full-text index files associated with the database and the metadata of the full-
text index are dropped, unless the database is read-only. If NULL or true, full-text related metadata are kept.

IMPORTANT
The@keepfulltextindexfile parameter will be removed in a future version of SQL Server. Do not use this parameter in new
development work, and modify applications that currently use this parameter as soon as possible.

Return Code Values


0 (success) or 1 (failure)
Result Sets
None

Remarks
When a database is detached, all its metadata is dropped. If the database was the default database of any login
accounts, master becomes their default database.

NOTE
For information about how to view the default database of all the login accounts, see sp_helplogins (Transact-SQL). If you
have the required permissions, you can use ALTER LOGIN to assign a new default database to a login.

Restrictions
A database cannot be detached if any of the following are true:
The database is currently in use. For more information, see "Obtaining Exclusive Access," later in this topic.
If replicated, the database is published.
Before you can detach the database, you must disable publishing by running sp_replicationdboption.

NOTE
If you cannot use sp_replicationdboption, you can remove replication by running sp_removedbreplication.

A database snapshot exists on the database.


Before you can detach the database, you must drop all of its snapshots. For more information, see Drop a
Database Snapshot (Transact-SQL).

NOTE
A database snapshot cannot be detached or attached.

The database is being mirrored.


The database cannot be detached until the database mirroring session is terminated. For more information,
see Removing Database Mirroring (SQL Server).
The database is suspect.
You must put a suspect database into emergency mode before you can detach the database. For more
information about how to put a database into emergency mode, see ALTER DATABASE (Transact-SQL).
The database is a system database.

Obtaining Exclusive Access


Detaching a database requires exclusive access to the database. If the database that you want to detach is in use,
before you can detach it, set the database to SINGLE_USER mode to obtain exclusive access.
For example, the following ALTER DATABASE statement obtains exclusive access to the AdventureWorks2012
database after all current users disconnect from the database.
USE master;
ALTER DATABASE AdventureWorks2012
SET SINGLE_USER;
GO

NOTE
To force current users out of the database immediately or within a specified number of seconds, also use the ROLLBACK
option: ALTER DATABASE database_name SET SINGLE_USER WITH ROLLBACK rollback_option. For more information, see
ALTER DATABASE (Transact-SQL).

Reattaching a Database
The detached files remain and can be reattached by using CREATE DATABASE (with the FOR ATTACH or FOR
ATTACH_REBUILD_LOG option). The files can be moved to another server and attached there.

Permissions
Requires membership in the sysadmin fixed server role or membership in the db_owner role of the database.

Examples
The following example detaches the AdventureWorks2012 database with skipchecks set to true.

EXEC sp_detach_db 'AdventureWorks2012', 'true';

The following example detaches the AdventureWorks2012 database and keeps the full-text index files and the
metadata of the full-text index. This command runs UPDATE STATISTICS, which is the default behavior.

exec sp_detach_db @dbname='AdventureWorks2012'


, @keepfulltextindexfile='true';

See Also
ALTER DATABASE (Transact-SQL)
Database Detach and Attach (SQL Server)
CREATE DATABASE (SQL Server Transact-SQL)
Detach a Database
sp_dropdevice (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops a database device or backup device from an instance of the SQL Server 2005 Database Engine, deleting the
entry from master.dbo.sysdevices.
Transact-SQL Syntax Conventions

Syntax
sp_dropdevice [ @logicalname = ] 'device'
[ , [ @delfile = ] 'delfile' ]

Arguments
[ @logicalname= ] 'device'
Is the logical name of the database device or backup device as listed in master.dbo.sysdevices.name. device is
sysname, with no default.
[ @delfile= ] 'delfile'
Specifies whether the physical backup device file should be deleted. delfile is varchar(7). If specified as DELFILE,
the physical backup device disk file is deleted.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_dropdevice cannot be used inside a transaction.

Permissions
Requires membership in the diskadmin fixed server role.

Examples
The following example drops the tapedump1 tape dump device from the Database Engine.

EXEC sp_dropdevice 'tapedump1';


See also
Backup Devices (SQL Server)
Delete a Backup Device (SQL Server)
sp_addumpdevice (Transact-SQL)
sp_helpdb (Transact-SQL)
sp_helpdevice (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_dropextendedproc (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops an extended stored procedure.

NOTE
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use CLR Integration instead.

Transact-SQL Syntax Conventions

Syntax
sp_dropextendedproc [ @functname = ] 'procedure'

Arguments
[ @functname =] 'procedure'
Is the name of the extended stored procedure to drop. procedure is nvarchar(517), with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Executing sp_dropextendedproc drops the user-defined extended stored procedure name from the sys.objects
catalog view and removes the entry from the sys.extended_procedures catalog view. This stored procedure can be
run only in the master database.
sp_dropextendedproc does not drop system extended stored procedures. Instead, the system administrator
should deny EXECUTE permission on the extended stored procedure to the public role.
sp_dropextendedproc cannot be executed inside a transaction.

Permissions
Only members of the sysadmin fixed server role can execute sp_dropextendedproc.

Examples
The following example drops the xp_hello extended stored procedure.
NOTE
This extended stored procedure must already exist, or the example will return an error message.

USE master;
GO
EXEC sp_dropextendedproc 'xp_hello';

See Also
sp_addextendedproc (Transact-SQL)
sp_helpextendedproc (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_dropextendedproperty (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops an existing extended property.
Transact-SQL Syntax Conventions

Syntax
sp_dropextendedproperty
[ @name = ] { 'property_name' }
[ , [ @level0type = ] { 'level0_object_type' }
, [ @level0name = ] { 'level0_object_name' }
[ , [ @level1type = ] { 'level1_object_type' }
, [ @level1name = ] { 'level1_object_name' }
[ , [ @level2type = ] { 'level2_object_type' }
, [ @level2name = ] { 'level2_object_name' }
]
]
]
]

Arguments
[ @name= ]{ 'property_name'}
Is the name of the property to be dropped. property_name is sysname and cannot be NULL.
[ @level0type= ]{ 'level0_object_type'}
Is the name of the level 0 object type specified. level0_object_type is varchar(128), with a default of NULL.
Valid inputs are ASSEMBLY, CONTRACT, EVENT NOTIFICATION, FILEGROUP, MESSAGE TYPE, PARTITION
FUNCTION, PARTITION SCHEME, REMOTE SERVICE BINDING, ROUTE, SCHEMA, SERVICE, USER, TRIGGER, TYPE,
and NULL.

IMPORTANT
USER and TYPE as level-0 types will be removed in a future version of SQL Server. Avoid using these features in new
development work, and plan to modify applications that currently use these features. Use SCHEMA as the level 0 type
instead of USER. For TYPE, use SCHEMA as the level 0 type and TYPE as the level 1 type.

[ @level0name= ]{ 'level0_object_name'}
Is the name of the level 0 object type specified. level0_object_name is sysname with a default of NULL.
[ @level1type= ]{ 'level1_object_type'}
Is the type of level 1 object. level1_object_type is varchar(128) with a default of NULL. Valid inputs are
AGGREGATE, DEFAULT, FUNCTION, LOGICAL FILE NAME, PROCEDURE, QUEUE, RULE, SYNONYM, TABLE,
TABLE_TYPE, TYPE, VIEW, XML SCHEMA COLLECTION, and NULL.
[ @level1name= ]{ 'level1_object_name'}
Is the name of the level 1 object type specified. level1_object_name is sysname with a default of NULL.
[ @level2type= ]{ 'level2_object_type'}
Is the type of level 2 object. level2_object_type is varchar(128) with a default of NULL. Valid inputs are COLUMN,
CONSTRAINT, EVENT NOTIFICATION, INDEX, PARAMETER, TRIGGER, and NULL.
[ @level2name= ]{ 'level2_object_name'}
Is the name of the level 2 object type specified. level2_object_name is sysname with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
For the purpose of specifying extended properties, the objects in a SQL Server database are classified into three
levels: 0, 1, and 2. Level 0 is the highest level and is defined as objects contained at the database scope. Level 1
objects are contained in a schema or user scope, and level 2 objects are contained by level 1 objects. Extended
properties can be defined for objects at any of these levels. References to an object in one level must be qualified
with the types and names of all higher level objects.
Given a valid property_name, if all object types and names are null and a property exists on the current database,
that property is deleted. See example B that follows later in this topic.

Permissions
Members of the db_owner and db_ddladmin fixed database roles may drop extended properties of any object with
the following exception: db_ddladmin may not add properties to the database itself, or to users or roles.
Users may drop extended properties to objects they own or on which they have ALTER or CONTROL permissions.

Examples
A. Dropping an extended property on a column
The following example removes the property caption from column id in table T1 contained in the schema
dbo .
CREATE TABLE T1 (id int , name char (20));
GO
EXEC sp_addextendedproperty
@name = 'caption'
,@value = 'Employee ID'
,@level0type = 'schema'
,@level0name = dbo
,@level1type = 'table'
,@level1name = 'T1'
,@level2type = 'column'
,@level2name = id;
GO
EXEC sp_dropextendedproperty
@name = 'caption'
,@level0type = 'schema'
,@level0name = dbo
,@level1type = 'table'
,@level1name = 'T1'
,@level2type = 'column'
,@level2name = id;
GO
DROP TABLE T1;
GO

B. Dropping an extended property on a database


The following example removes the property named MS_Description from the AdventureWorks2012 sample
database. Because the property is on the database itself, no object types and names are specified.

USE AdventureWorks2012;
GO
EXEC sp_dropextendedproperty
@name = N'MS_Description';
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
sys.fn_listextendedproperty (Transact-SQL)
sp_addextendedproperty (Transact-SQL)
sp_updateextendedproperty (Transact-SQL)
sys.extended_properties (Transact-SQL)
sp_dropmessage (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops a specified user-defined error message from an instance of the SQL Server Database Engine. User-defined
messages can be viewed using the sys.messages catalog view.
Transact-SQL Syntax Conventions

Syntax
sp_dropmessage [ @msgnum = ] message_number
[ , [ @lang = ] 'language' ]

Arguments
[ @msgnum = ] message_number
Is the message number to drop. message_number must be a user-defined message that has a message number
greater than 50000. message_number is int, with a default of NULL.
[ @lang = ] 'language'
Is the language of the message to drop. If all is specified, all language versions of message_number are dropped.
language is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Permissions
Requires membership in the sysadmin and serveradmin fixed server roles.

Remarks
Unless all is specified for language, all localized versions of a message must be dropped before the U.S. English
version of the message can be dropped.

Examples
A. Dropping a user-defined message
The following example drops a user-defined message, number 50001 , from sys.messages.
USE master;
GO
EXEC sp_dropmessage 50001;

B. Dropping a user-defined message that includes a localized version


The following example drops a user-defined message, number 60000 , that includes a localized version of the
message.

USE master;
GO

-- Create a user-defined message in U.S. English


EXEC sp_addmessage
@msgnum = 60000,
@severity = 16,
@msgtext = N'The item named %s already exists in %s.',
@lang = 'us_english';

-- Create a localized version of the same message.


EXEC sp_addmessage
@msgnum = 60000,
@severity = 16,
@msgtext = N'L''élément nommé %1! existe déjà dans %2!',
@lang = 'French';
GO

-- This statement will fail as long as the localized version


-- of the message exists.
EXEC sp_dropmessage 60000;
GO

-- This statement will drop the message.


EXEC sp_dropmessage
@msgnum = 60000,
@lang = 'all';
GO

C. Dropping a localized version of a user-defined message


The following example drops a localized version of a user-defined message, number 60000 , without dropping the
whole message.
USE master;
GO

-- Create a user-defined message in U.S. English


EXEC sp_addmessage
@msgnum = 60000,
@severity = 16,
@msgtext = N'The item named %s already exists in %s.',
@lang = 'us_english';

-- Create a localized version of the same message.


EXEC sp_addmessage
@msgnum = 60000,
@severity = 16,
@msgtext = N'L''élément nommé %1! existe déjà dans %2!',
@lang = 'French';
GO
-- This statement will remove only the localized version of the
-- message.
EXEC sp_dropmessage
@msgnum = 60000,
@lang = 'French';
GO

See Also
RAISERROR (Transact-SQL)
sp_addmessage (Transact-SQL)
sp_altermessage (Transact-SQL)
FORMATMESSAGE (Transact-SQL)
sys.messages (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_droptype (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes an alias data type from systypes.
Transact-SQL Syntax Conventions

Syntax
sp_droptype [ @typename = ] 'type'

Arguments
[ @typename=] 'type'
Is the name of an alias data type that you own. type is sysname, with no default.

Return Code Type


0 (success) or 1 (failure)

Result Sets
None

Remarks
The type alias data type cannot be dropped if tables or other database objects reference it.

NOTE
An alias data type cannot be dropped if the alias data type is used within a table definition or if a rule or default is bound to
it.

Permissions
Requires membership in the db_owner fixed database role or the db_ddladmin fixed database role.

Examples
The following example drops the alias data type birthday .

NOTE
This alias data type must already exist or this example returns an error message.
USE master;
GO
EXEC sp_droptype 'birthday';
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
sp_addtype (Transact-SQL)
sp_rename (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_estimate_data_compression_savings (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the current size of the requested object and estimates the object size for the requested compression state.
Compression can be evaluated for whole tables or parts of tables. This includes heaps, clustered indexes,
nonclustered indexes, indexed views, and table and index partitions. The objects can be compressed by using row
compression or page compression. If the table, index, or partition is already compressed, you can use this
procedure to estimate the size of the table, index, or partition if it is recompressed.

NOTE
Compression and sp_estimate_data_compression_savings are not available in every edition of Microsoft SQL Server. For a
list of features that are supported by the editions of SQL Server, see Features Supported by the Editions of SQL Server 2016.

To estimate the size of the object if it were to use the requested compression setting, this stored procedure samples
the source object and loads this data into an equivalent table and index created in tempdb. The table or index create
in tempdb is then compressed to the requested setting and the estimated compression savings is computed.
To change the compression state of a table, index, or partition, use the ALTER TABLE or ALTER INDEX statements.
For general information about compression, see Data Compression.

NOTE
If the existing data is fragmented, you might be able to reduce its size without using compression by rebuilding the index. For
indexes, the fill factor will be applied during an index rebuild. This could increase the size of the index.

Transact-SQL Syntax Conventions

Syntax
sp_estimate_data_compression_savings
[ @schema_name = ] 'schema_name'
, [ @object_name = ] 'object_name'
, [@index_id = ] index_id
, [@partition_number = ] partition_number
, [@data_compression = ] 'data_compression'
[;]

Arguments
[ @schema_name= ] 'schema_name'
Is the name of the database schema that contains the table or indexed view. schema_name is sysname. If
schema_name is NULL, the default schema of the current user is used.
[ @object_name= ] 'object_name'
Is the name of the table or indexed view that the index is on. object_name is sysname.
[ @index_id= ] 'index_id'
Is the ID of the index. index_id is int, and can be one of the following values: the ID number of an index, NULL, or 0
if object_id is a heap. To return information for all indexes for a base table or view, specify NULL. If you specify
NULL, you must also specify NULL for partition_number.
[ @partition_number= ] 'partition_number'
Is the partition number in the object. partition_number is int, and can be one of the following values: the partition
number of an index or heap, NULL or 1 for a nonpartitioned index or heap.
To specify the partition, you can also specify the $partition function. To return information for all partitions of the
owning object, specify NULL.
[ @data_compression= ] 'data_compression'
Is the type of compression to be evaluated. data_compression can be one of the following values: NONE, ROW, or
PAGE.

Return Code Values


0 (success) or 1 (failure)

Result Sets
The following result set is returned to provide current and estimated size for the table, index, or partition.

COLUMN NAME DATA TYPE DESCRIPTION

object_name sysname Name of the table or the indexed view.

schema_name sysname Schema of the table or indexed view.

index_id int Index ID of an index:

0 = Heap

1 = Clustered index

> 1 = Nonclustered index

partition_number int Partition number. Returns 1 for a


nonpartitioned table or index.

size_with_current_compression_setting bigint Size of the requested table, index, or


(KB) partition as it currently exists.

size_with_requested_compression_settin bigint Estimated size of the table, index, or


g (KB) partition that uses the requested
compression setting; and, if applicable,
the existing fill factor, and assuming
there is no fragmentation.

sample_size_with_current_compression_ bigint Size of the sample with the current


setting (KB) compression setting. This includes any
fragmentation.
COLUMN NAME DATA TYPE DESCRIPTION

sample_size_with_requested_compressio bigint Size of the sample that is created by


n_setting (KB) using the requested compression
setting; and, if applicable, the existing fill
factor and no fragmentation.

Remarks
Use sp_estimate_data_compression_savings to estimate the savings that can occur when you enable a table or
partition for row or page compression. For instance if the average size of the row can be reduced by 40 percent,
you can potentially reduce the size of the object by 40 percent. You might not receive a space savings because this
depends on the fill factor and the size of the row. For example, if you have a row that is 8000 bytes long and you
reduce its size by 40 percent, you can still fit only one row on a data page. There is no savings.
If the results of running sp_estimate_data_compression_savings indicate that the table will grow, this means that
many rows in the table use almost the whole precision of the data types, and the addition of the small overhead
needed for the compressed format is more than the savings from compression. In this rare case, do not enable
compression.
If a table is enabled for compression, use sp_estimate_data_compression_savings to estimate the average size of
the row if the table is uncompressed.
An (IS) lock is acquired on the table during this operation. If an (IS) lock cannot be obtained, the procedure will be
blocked. The table is scanned under the read committed isolation level.
If the requested compression setting is same as the current compression setting, the stored procedure will return
the estimated size with no data fragmentation and using the existing fill factor.
If the index or partition ID does not exist, no results are returned.

Permissions
Requires SELECT permission on the table.

Limitations and Restrictions


This procedure does not apply to columnstore tables, and therefore does not accept the data compression
parameters COLUMNSTORE and COLUMNSTORE_ARCHIVE.

Examples
The following example estimates the size of the Production.WorkOrderRouting table if it is compressed by using
ROW compression.

USE AdventureWorks2012;
GO
EXEC sp_estimate_data_compression_savings 'Production', 'WorkOrderRouting', NULL, NULL, 'ROW' ;
GO

See Also
CREATE TABLE (Transact-SQL)
CREATE INDEX (Transact-SQL)
sys.partitions (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
Unicode Compression Implementation
sp_estimated_rowsize_reduction_for_vardecimal
(Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Estimates the reduction in the average size of rows if you enable vardecimal storage format on a table. Use this
number to estimate the overall reduction in the size of the table. Since the statistical sampling is used to compute
the average reduction in the rowsize, regard it as an estimate only. In rare cases, rowsize may increase after
enabling the vardecimal storage format.

NOTE
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ROW and PAGE compression instead. For more
information, see Data Compression. For compression effects on the size of tables and indexes, see
sp_estimate_data_compression_savings (Transact-SQL).

Transact-SQL Syntax Conventions

Syntax
sp_estimated_rowsize_reduction_for_vardecimal [ [ @table_name = ] 'table'] [;]

Arguments
[ @table= ] 'table'
Is the three part name of the table for which the storage format is to be changed. table is nvarchar(776).

Return Code Values


0 (success) or 1 (failure)

Result Sets
The following result set is returned to provide current and estimated table size information.

COLUMN NAME DATA TYPE DESCRIPTION

avg_rowlen_fixed_format decimal (12, 2) Represents the length of the row in


fixed decimal storage format.

avg_rowlen_vardecimal_format decimal (12, 2) Represents average rowsize when


vardecimal storage format is used.

row_count int Number of rows in the table.


Remarks
Use sp_estimated_rowsize_reduction_for_vardecimal to estimate the savings that result if you enable a table
for vardecimal storage format. For instance if the average size of the row can be reduced by 40%, you can
potentially reduce the size of the table by 40%. You may not receive a space savings depending on the fill factor
and the size of the row. For example, if you have a row that is 8000 bytes long and you reduce its size by 40%, you
can still fit only one row on a data page, resulting in no savings.
If the results of sp_estimated_rowsize_reduction_for_vardecimal indicate that the table will grow, this means
that many rows in the table use nearly the entire precision of the decimal data types, and the addition of the small
overhead needed for vardecimal storage format is greater than the savings from vardecimal storage format. In this
rare case, do not enable vardecimal storage format.
If a table is enabled for vardecimal storage format, use sp_estimated_rowsize_reduction_for_vardecimal to
estimate the average size of the row if vardecimal storage format is disabled.

Permissions
Requires CONTROL permission on the table.

Examples
The following example estimates the rowsize reduction if the Production.WorkOrderRouting table in the
AdventureWorks2012 database is compressed.

USE AdventureWorks2012;
GO
EXEC sp_estimated_rowsize_reduction_for_vardecimal 'Production.WorkOrderRouting' ;
GO

See Also
sp_db_vardecimal_storage_format (Transact-SQL)
sp_tableoption (Transact-SQL)
sp_execute_remote (Azure SQL Database)
1/2/2018 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
Executes a Transact-SQL statement on a single remote Azure SQL Database or set of databases serving as shards in
a horizontal partitioning scheme.
The stored procedure is part of the elastic query feature. See Azure SQL Database elastic database query overview
and Elastic database queries for sharding (horizontal partitioning).
Transact-SQL Syntax Conventions

Syntax
sp_execute_remote [ @data_source_name = ] datasourcename
[ , @stmt = ] statement
[
{ , [ @params = ] N'@parameter_name data_type [,...n ]' }
{ , [ @param1 = ] 'value1' [ ,...n ] }
]

Arguments
[ @data_source_name = ] datasourcename
Identifies the external data source where the statement is executed. See CREATE EXTERNAL DATA SOURCE
(Transact-SQL). The external data source can be of type "RDBMS" or "SHARD_MAP_MANAGER".
[ @stmt= ] statement
Is a Unicode string that contains a Transact-SQL statement or batch. @stmt must be either a Unicode constant or a
Unicode variable. More complex Unicode expressions, such as concatenating two strings with the + operator, are
not allowed. Character constants are not allowed. If a Unicode constant is specified, it must be prefixed with an N.
For example, the Unicode constant N'sp_who' is valid, but the character constant 'sp_who' is not. The size of the
string is limited only by available database server memory. On 64-bit servers, the size of the string is limited to 2
GB, the maximum size of nvarchar(max).

NOTE
@stmt can contain parameters having the same form as a variable name, for example:
N'SELECT * FROM HumanResources.Employee WHERE EmployeeID = @IDParameter'

Each parameter included in @stmt must have a corresponding entry in both the @params parameter definition list
and the parameter values list.
[ @params= ] N'@parameter_namedata_type [ ,... n ] '
Is one string that contains the definitions of all parameters that have been embedded in @stmt. The string must be
either a Unicode constant or a Unicode variable. Each parameter definition consists of a parameter name and a data
type. n is a placeholder that indicates additional parameter definitions. Every parameter specified in @stmtmust be
defined in @params. If the Transact-SQL statement or batch in @stmt does not contain parameters, @params is
not required. The default value for this parameter is NULL.
[ @param1= ] 'value1'
Is a value for the first parameter that is defined in the parameter string. The value can be a Unicode constant or a
Unicode variable. There must be a parameter value supplied for every parameter included in @stmt. The values are
not required when the Transact-SQL statement or batch in @stmt has no parameters.
n
Is a placeholder for the values of additional parameters. Values can only be constants or variables. Values cannot be
more complex expressions such as functions, or expressions built by using operators.

Return Code Values


0 (success) or non-zero (failure)

Result Sets
Returns the result set from the first SQL statement.

Permissions
Requires ALTER ANY EXTERNAL DATA SOURCE permission.

Remarks
sp_execute_remote parameters must be entered in the specific order as described in the syntax section above. If the
parameters are entered out of order, an error message will occur.
sp_execute_remote has the same behavior as EXECUTE (Transact-SQL) with regard to batches and the scope of
names. The Transact-SQL statement or batch in the sp_execute_remote @stmt parameter is not compiled until the
sp_execute_remote statement is executed.
sp_execute_remote adds an additional column to the result set named '$ShardName' that contains the name of the
remote database that produced the row.
sp_execute_remote can be used similar to sp_executesql (Transact-SQL).

Examples
Simple example
The following example creates and executes a simple SELECT statement on a remote database.

EXEC sp_execute_remote
N'MyExtSrc',
N'SELECT COUNT(w_id) AS Count_id FROM warehouse'

Example with multiple parameters


Create a database scoped credential in a user database, specifying administrator credentials for the master
database. Create an external data source pointing to the master database and specifying the database scoped
credential. Then following, example in the user database, executes the sp_set_firewall_rule procedure in the
master database. The sp_set_firewall_rule procedure requires 3 parameters, and requires the @name parameter
to be Unicode.
EXEC sp_execute_remote @data_source_name = N'PointToMaster',
@stmt = N'sp_set_firewall_rule @name, @start_ip_address, @end_ip_address',
@params = N'@name nvarchar(128), @start_ip_address varchar(50), @end_ip_address varchar(50)',
@name = N'TempFWRule', @start_ip_address = '0.0.0.2', @end_ip_address = '0.0.0.2';

See Also:
CREATE DATABASE SCOPED CREDENTIAL
CREATE EXTERNAL DATA SOURCE (Transact-SQL)
sp_executesql (Transact-SQL)
11/21/2017 • 7 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Executes a Transact-SQL statement or batch that can be reused many times, or one that has been built dynamically.
The Transact-SQL statement or batch can contain embedded parameters.

IMPORTANT
Run time-compiled Transact-SQL statements can expose applications to malicious attacks.

Transact-SQL Syntax Conventions

Syntax
-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse

sp_executesql [ @stmt = ] statement


[
{ , [ @params = ] N'@parameter_name data_type [ OUT | OUTPUT ][ ,...n ]' }
{ , [ @param1 = ] 'value1' [ ,...n ] }
]

Arguments
[ @stmt= ] statement
Is a Unicode string that contains a Transact-SQL statement or batch. @stmt must be either a Unicode constant or a
Unicode variable. More complex Unicode expressions, such as concatenating two strings with the + operator, are
not allowed. Character constants are not allowed. If a Unicode constant is specified, it must be prefixed with an N.
For example, the Unicode constant N'sp_who' is valid, but the character constant 'sp_who' is not. The size of the
string is limited only by available database server memory. On 64-bit servers, the size of the string is limited to 2
GB, the maximum size of nvarchar(max).

NOTE
@stmt can contain parameters having the same form as a variable name, for example:
N'SELECT * FROM HumanResources.Employee WHERE EmployeeID = @IDParameter'

Each parameter included in @stmt must have a corresponding entry in both the @params parameter definition list
and the parameter values list.
[ @params= ] N'@parameter_namedata_type [ ,... n ] '
Is one string that contains the definitions of all parameters that have been embedded in @stmt. The string must be
either a Unicode constant or a Unicode variable. Each parameter definition consists of a parameter name and a
data type. n is a placeholder that indicates additional parameter definitions. Every parameter specified in
@stmtmust be defined in @params. If the Transact-SQL statement or batch in @stmt does not contain parameters,
@params is not required. The default value for this parameter is NULL.
[ @param1= ] 'value1'
Is a value for the first parameter that is defined in the parameter string. The value can be a Unicode constant or a
Unicode variable. There must be a parameter value supplied for every parameter included in @stmt. The values are
not required when the Transact-SQL statement or batch in @stmt has no parameters.
[ OUT | OUTPUT ]
Indicates that the parameter is an output parameter. text, ntext, and image parameters can be used as OUTPUT
parameters, unless the procedure is a common language runtime (CLR) procedure. An output parameter that uses
the OUTPUT keyword can be a cursor placeholder, unless the procedure is a CLR procedure.
n
Is a placeholder for the values of additional parameters. Values can only be constants or variables. Values cannot
be more complex expressions such as functions, or expressions built by using operators.

Return Code Values


0 (success) or non-zero (failure)

Result Sets
Returns the result sets from all the SQL statements built into the SQL string.

Remarks
sp_executesql parameters must be entered in the specific order as described in the "Syntax" section earlier in this
topic. If the parameters are entered out of order, an error message will occur.
sp_executesql has the same behavior as EXECUTE with regard to batches, the scope of names, and database
context. The Transact-SQL statement or batch in the sp_executesql @stmt parameter is not compiled until the
sp_executesql statement is executed. The contents of @stmt are then compiled and executed as an execution plan
separate from the execution plan of the batch that called sp_executesql. The sp_executesql batch cannot reference
variables declared in the batch that calls sp_executesql. Local cursors or variables in the sp_executesql batch are
not visible to the batch that calls sp_executesql. Changes in database context last only to the end of the
sp_executesql statement.
sp_executesql can be used instead of stored procedures to execute a Transact-SQL statement many times when the
change in parameter values to the statement is the only variation. Because the Transact-SQL statement itself
remains constant and only the parameter values change, the SQL Server query optimizer is likely to reuse the
execution plan it generates for the first execution.

NOTE
To improve performance use fully qualified object names in the statement string.

sp_executesql supports the setting of parameter values separately from the Transact-SQL string as shown in the
following example.
DECLARE @IntVariable int;
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);

/* Build the SQL string one time.*/


SET @SQLString =
N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
FROM AdventureWorks2012.HumanResources.Employee
WHERE BusinessEntityID = @BusinessEntityID';
SET @ParmDefinition = N'@BusinessEntityID tinyint';
/* Execute the string with the first parameter value. */
SET @IntVariable = 197;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@BusinessEntityID = @IntVariable;
/* Execute the same string with the second parameter value. */
SET @IntVariable = 109;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@BusinessEntityID = @IntVariable;

Output parameters can also be used with sp_executesql. The following example retrieves a job title from the
AdventureWorks2012.HumanResources.Employee table and returns it in the output parameter @max_title .

DECLARE @IntVariable int;


DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
DECLARE @max_title varchar(30);

SET @IntVariable = 197;


SET @SQLString = N'SELECT @max_titleOUT = max(JobTitle)
FROM AdventureWorks2012.HumanResources.Employee
WHERE BusinessEntityID = @level';
SET @ParmDefinition = N'@level tinyint, @max_titleOUT varchar(30) OUTPUT';

EXECUTE sp_executesql @SQLString, @ParmDefinition, @level = @IntVariable, @max_titleOUT=@max_title OUTPUT;


SELECT @max_title;

Being able to substitute parameters in sp_executesql offers the following advantages to using the EXECUTE
statement to execute a string:
Because the actual text of the Transact-SQL statement in the sp_executesql string does not change between
executions, the query optimizer will probably match the Transact-SQL statement in the second execution
with the execution plan generated for the first execution. Therefore, SQL Server does not have to compile
the second statement.
The Transact-SQL string is built only one time.
The integer parameter is specified in its native format. Casting to Unicode is not required.

Permissions
Requires membership in the public role.

Examples
A. Executing a simple SELECT statement
The following example creates and executes a simple SELECT statement that contains an embedded parameter
named @level .
EXECUTE sp_executesql
N'SELECT * FROM AdventureWorks2012.HumanResources.Employee
WHERE BusinessEntityID = @level',
N'@level tinyint',
@level = 109;

B. Executing a dynamically built string


The following example shows using sp_executesql to execute a dynamically built string. The example stored
procedure is used to insert data into a set of tables that are used to partition sales data for a year. There is one
table for each month of the year that has the following format:

CREATE TABLE May1998Sales


(OrderID int PRIMARY KEY,
CustomerID int NOT NULL,
OrderDate datetime NULL
CHECK (DATEPART(yy, OrderDate) = 1998),
OrderMonth int
CHECK (OrderMonth = 5),
DeliveryDate datetime NULL,
CHECK (DATEPART(mm, OrderDate) = OrderMonth)
)

This sample stored procedure dynamically builds and executes an INSERT statement to insert new orders into the
correct table. The example uses the order date to build the name of the table that should contain the data, and then
incorporates that name into an INSERT statement.

NOTE
This is a simple example for sp_executesql. The example does not contain error checking and does not include checks for
business rules, such as guaranteeing that order numbers are not duplicated between tables.
CREATE PROCEDURE InsertSales @PrmOrderID INT, @PrmCustomerID INT,
@PrmOrderDate DATETIME, @PrmDeliveryDate DATETIME
AS
DECLARE @InsertString NVARCHAR(500)
DECLARE @OrderMonth INT

-- Build the INSERT statement.


SET @InsertString = 'INSERT INTO ' +
/* Build the name of the table. */
SUBSTRING( DATENAME(mm, @PrmOrderDate), 1, 3) +
CAST(DATEPART(yy, @PrmOrderDate) AS CHAR(4) ) +
'Sales' +
/* Build a VALUES clause. */
' VALUES (@InsOrderID, @InsCustID, @InsOrdDate,' +
' @InsOrdMonth, @InsDelDate)'

/* Set the value to use for the order month because


functions are not allowed in the sp_executesql parameter
list. */
SET @OrderMonth = DATEPART(mm, @PrmOrderDate)

EXEC sp_executesql @InsertString,


N'@InsOrderID INT, @InsCustID INT, @InsOrdDate DATETIME,
@InsOrdMonth INT, @InsDelDate DATETIME',
@PrmOrderID, @PrmCustomerID, @PrmOrderDate,
@OrderMonth, @PrmDeliveryDate

GO

Using sp_executesql in this procedure is more efficient than using EXECUTE to execute a string. When
sp_executesql is used, there are only 12 versions of the INSERT string that are generated, one for each monthly
table. With EXECUTE, each INSERT string is unique because the parameter values are different. Although both
methods generate the same number of batches, the similarity of the INSERT strings generated by sp_executesql
makes it more likely that the query optimizer will reuse execution plans.
C. Using the OUTPUT Parameter
The following example uses an OUTPUT parameter to store the result set generated by the SELECT statement in the
@SQLString parameter.Two SELECT statements are then executed that use the value of the OUTPUT parameter.
USE AdventureWorks2012;
GO
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
DECLARE @SalesOrderNumber nvarchar(25);
DECLARE @IntVariable int;
SET @SQLString = N'SELECT @SalesOrderOUT = MAX(SalesOrderNumber)
FROM Sales.SalesOrderHeader
WHERE CustomerID = @CustomerID';
SET @ParmDefinition = N'@CustomerID int,
@SalesOrderOUT nvarchar(25) OUTPUT';
SET @IntVariable = 22276;
EXECUTE sp_executesql
@SQLString
,@ParmDefinition
,@CustomerID = @IntVariable
,@SalesOrderOUT = @SalesOrderNumber OUTPUT;
-- This SELECT statement returns the value of the OUTPUT parameter.
SELECT @SalesOrderNumber;
-- This SELECT statement uses the value of the OUTPUT parameter in
-- the WHERE clause.
SELECT OrderDate, TotalDue
FROM Sales.SalesOrderHeader
WHERE SalesOrderNumber = @SalesOrderNumber;

Examples: Azure SQL Data Warehouse and Parallel Data Warehouse


D. Executing a simple SELECT statement
The following example creates and executes a simple SELECT statement that contains an embedded parameter
named @level .

-- Uses AdventureWorks

EXECUTE sp_executesql
N'SELECT * FROM AdventureWorksPDW2012.dbo.DimEmployee
WHERE EmployeeKey = @level',
N'@level tinyint',
@level = 109;

For additional examples, see sp_executesql (Transact-SQL).

See Also
EXECUTE (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_execute_external_script (Transact-SQL)
11/21/2017 • 7 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Executes the script provided as argument at an external location. The script must be written in a supported and
registered language. The query tree is controlled by SQL Server and users cannot perform arbitrary operations on
the query. To execute sp_execute_external_script, you must first enable external scripts by using the
sp_configure 'external scripts enabled', 1; statement.

Transact-SQL Syntax Conventions

Syntax
sp_execute_external_script
@language = N'language,
@script = N'script'
[ , @input_data_1 = N'input_data_1' ]
[ , @input_data_1_name = N'input_data_1_name' ]
[ , @output_data_1_name = N'output_data_1_name' ]
[ , @parallel = 0 | 1 ]
[ , @params = N'@parameter_name data_type [ OUT | OUTPUT ] [ ,...n ]' ]
[ , @parameter1 = 'value1' [ OUT | OUTPUT ] [ ,...n ] ]

Arguments
@language = N'language'
Indicates the script language. language is sysname.
Valid values are Python or R .
@script = N'script'
External language script specified as a literal or variable input. script is nvarchar(max).
[ @input_data_1_name = N'input_data_1_name' ]
Specifies the name of the variable used to represent the query defined by @input_data_1. The data type of the
variable in the external script depends on the language. In case of R, the input variable is a data frame. In the case of
Python, input must be tabular. input_data_1_name is sysname.
Default value is "InputDataSet".
[ @input_data_1 = N'input_data_1' ]
Specifies the input data used by the external script in the form of a Transact-SQL query. input_data_1 is
nvarchar(max).
[ @output_data_1_name = N'output_data_1_name' ]
Specifies the name of the variable in the external script that contains the data to be returned to SQL Server upon
completion of the stored procedure call. The data type of the variable in the external script depends on the
language. In the case of R, the output must be a data frame. In the case of Python, the output must be a pandas data
frame. output_data_1_name is sysname.
Default value is "OutputDataSet".
[ @parallel = 0 | 1 ]
Enable parallel execution of R scripts by setting the @parallel parameter to 1. The default for this parameter is 0
(no parallelism).
For R scripts that do not use RevoScaleR functions, using the @parallel parameter can be beneficial for processing
large datasets, assuming the script can be trivially parallelized. For example, when using the R predict function
with a model to generate new predictions, set @parallel = 1 as a hint to the query engine. If the query can be
parallelized, rows are distributed according to the MAXDOP setting.
If @parallel = 1 and the output is being streamed directly to the client machine, then the WITH RESULTS SETS
clause is required and an output schema must be specified.
For R scripts that use RevoScaleR functions, parallel processing is handled automatically and you should not specify
@parallel = 1 to the sp_execute_external_script call.

[ @params = N'@parameter_name data_type [ OUT | OUTPUT ] [ ,...n ]' ]


A list of input parameter declarations that are used in the external script.
[ @parameter1 = 'value1' [ OUT | OUTPUT ] [ ,...n ] ]
A list of values for the input parameters used by the external script.

Remarks
Use sp_execute_external_script to execute scripts written in a supported language such as R. In SQL Server, R
Services (In-Database) is comprised of a server component installed with SQL Server, and a set of workstation tools
and connectivity libraries that connect the data scientist to the high-performance environment of SQL Server. Install
R Services (In-Database) during SQL Server setup to enable the execution of R scripts. For more information, see
Set up SQL Server R Services (In-Database).
You can control the resources used by an external script by configuring an external resource pool. For more
information, see CREATE EXTERNAL RESOURCE POOL (Transact-SQL). Information about the workload can be
obtained from the resource governor catalog views, DMV's, and counters. For more information, see Resource
Governor Catalog Views (Transact-SQL), Resource Governor Related Dynamic Management Views (Transact-SQL),
and SQL Server, External Scripts Object.
Monitor script execution using sys.dm_external_script_requests and sys.dm_external_script_execution_stats.
By default, result sets returned by this stored procedure are output with unnamed columns. Column names used
within a script are local to the scripting environment and are not reflected in the outputted result set. To name
result set columns, use the WITH RESULTS SET clause of EXECUTE .
In addition to returning a result set, you can return scalar values from R script to SQL Server using OUTPUT
parameters. The following example shows the use of OUTPUT parameter:
DECLARE @model varbinary(max);
EXEC sp_execute_external_script
@language = N'R'
, @script = N'
# build classification model to predict tipped or not
logitObj <- glm(tipped ~ passenger_count + trip_distance + trip_time_in_secs + direct_distance, data =
featureDataSource, family = binomial(link=logit));

# First, serialize a model and put it into a database table


modelbin <- serialize(logitObj, NULL);
'
, @input_data_1 = N'
SELECT tipped, passenger_count, trip_time_in_secs, trip_distance, d.direct_distance
FROM dbo.nyctaxi_sample TABLESAMPLE (1 PERCENT) REPEATABLE (98074)
CROSS APPLY [CalculateDistance](pickup_latitude, pickup_longitude, dropoff_latitude, dropoff_longitude) as d
'
, @input_data_1_name = N'featureDataSource'
, @params = N'@modelbin varbinary(max) OUTPUT'
, @modelbin = @model OUTPUT;

Streaming execution for R script


Streaming execution of R script is supported by specifying @r_rowsPerRead int parameter in @params collection.
Streaming allows R scripts to work with data that doesn’t fit in memory. For example, if there are billion rows to
score using predict function the new @r_rowsPerRead parameter can be used to split the execution into one stream
at a time. Because this parameter controls the number of rows that are sent to the R processes, it can also be used
to throttle the number of rows being read at one time. This might be useful to mitigate server performance issues
if, for example, a large model is being trained. Note that this parameter can only be used in cases where the output
of the R script doesn’t depend on reading or looking at the entire set of rows.
Both the @r_rowsPerRead parameter for streaming and the @parallel argument should be considered hints. For
the hint to be applied, it must be possible to generate a SQL query plan that includes parallel processing. If this is
not possible, parallel processing cannot be enabled.

NOTE
Streaming and parallel processing are supported only in Enterprise Edition. You can include the parameters in your queries in
Standard Edition without raising an error, but the parameters have no effect and R scripts run in a single process.

Restrictions
Data types: The following data types are not supported when used in the input query or parameters of
sp_execute_external_script procedure, and return an unsupported type error.

As a workaround, CAST the column or value to a supported type in Transact-SQL and send it to R.
cursor
timestamp
datetime2, datetimeoffset, time
sql_variant
text, image
xml
hierarchyid, geometry, geography
CLR user-defined types
datetime values in the input are converted to NA on the R side for values that do not fit the permissible
range of values in R. this is required because SQL Server permits a larger range of values than is supported
in the R language.
Float values (for example, +Inf, -Inf, NaN) are not supported in SQL Server even though both languages use
IEEE 754. Current behavior just sends the values to SQL Server directly and as a result sqlclient in
Management Studio throws error. These values convert to NULL.
Any R result set that cannot be mapped to a Transact-SQL data type, is output as NULL.

Permissions
Requires EXECUTE ANY EXTERNAL SCRIPT database permission.

Examples
This section contains examples of how this stored procedure can be used to execute R scripts using Transact-SQL.
A. Return a data set from R to SQL Server
The following example creates a stored procedure that uses sp_execute_external_script to return an iris dataset
from R to SQL Server.

DROP PROC IF EXISTS get_iris_dataset;


go
CREATE PROC get_iris_dataset
AS
BEGIN
EXEC sp_execute_external_script
@language = N'R'
, @script = N'iris_data <- iris;'
, @input_data_1 = N''
, @output_data_1_name = N'iris_data'
WITH RESULT SETS (("Sepal.Length" float not null,
"Sepal.Width" float not null,
"Petal.Length" float not null,
"Petal.Width" float not null, "Species" varchar(100)));
END;
go

B. Generate a model based on data from SQL Server


The following example creates a stored procedure that uses sp_execute_external_script to generate an iris model
and return the model to SQL Server.

NOTE
This example requires installing the e1071 package. For more information, see Install Additional R Packages on SQL Server.
DROP PROC IF EXISTS generate_iris_model;
go

CREATE PROC generate_iris_model


AS
BEGIN
EXEC sp_execute_external_script
@language = N'R'
, @script = N'
library(e1071);
irismodel <-naiveBayes(iris_data[,1:4], iris_data[,5]);
trained_model <- data.frame(payload = as.raw(serialize(irismodel, connection=NULL)));
'
, @input_data_1 = N'select "Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species" from
iris_data'
, @input_data_1_name = N'iris_data'
, @output_data_1_name = N'trained_model'
WITH RESULT SETS ((model varbinary(max)));
END;
go

See Also
System Stored Procedures (Transact-SQL)
Python Libraries and Data Types
R Libraries and R Data Types
SQL Server R Services
Known Issues for SQL Server R Services
CREATE EXTERNAL LIBRARY (Transact-SQL)
sp_prepare (Transact SQL)
sp_configure (Transact-SQL)
external scripts enabled Server Configuration Option
SERVERPROPERTY (Transact-SQL)
SQL Server, External Scripts Object
sys.dm_external_script_requests
sys.dm_external_script_execution_stats
sp_getbindtoken (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns a unique identifier for the transaction. This unique identifier is a string used to bind sessions using
sp_bindsession.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use Multiple Active Results Sets (MARS) or distributed
transactions instead. For more information, see Using Multiple Active Result Sets (MARS).

Transact-SQL Syntax Conventions

Syntax
sp_getbindtoken [@out_token =] 'return_value' OUTPUT

Arguments
[@out_token= ]'return_value'
Is the token to use to bind sessions. return_value is varchar(255) with no default.

Return Code Values


None

Result Sets
None

Remarks
sp_getbindtoken will return a valid token only when the stored procedure is executed inside an active transaction.
Otherwise, the Database Engine will return an error message. For example:

-- Declare a variable to hold the bind token.


-- No active transaction.
DECLARE @bind_token varchar(255);
-- Trying to get the bind token returns an error 3921.
EXECUTE sp_getbindtoken @bind_token OUTPUT;
Server: Msg 3921, Level 16, State 1, Procedure sp_getbindtoken, Line 4
Cannot get a transaction token if there is no transaction active.
Reissue the statement after a transaction has been started.

When sp_getbindtoken is used to enlist a distributed transaction connection inside an open transaction, SQL
Server returns the same token. For example:

USE AdventureWorks2012;
GO
DECLARE @bind_token varchar(255);

BEGIN TRAN;

EXECUTE sp_getbindtoken @bind_token OUTPUT;


SELECT @bind_token AS Token;

BEGIN DISTRIBUTED TRAN;

EXECUTE sp_getbindtoken @bind_token OUTPUT;


SELECT @bind_token AS Token;

Both SELECT statements return the same token:

Token
-----
PKb'gN5<9aGEedk_16>8U=5---/5G=--
(1 row(s_) affected)

Token
-----
PKb'gN5<9aGEedk_16>8U=5---/5G=--
(1 row(s_) affected)

The bind token can be used with sp_bindsession to bind new sessions to the same transaction. The bind token is
only valid locally inside each instance of the Database Engine and cannot be shared across multiple instances.
To obtain and pass a bind token, you must run sp_getbindtoken before executing sp_bindsession for sharing the
same lock space. If you obtain a bind token, sp_bindsession runs correctly.

NOTE
We recommend that you use the srv_getbindtoken Open Data Services application programming interface (API) to obtain a
bind token to be used from an extended stored procedure.

Permissions
Requires membership in the public role.

Examples
The following example obtains a bind token and displays the bind token name.

DECLARE @bind_token varchar(255);


BEGIN TRAN;
EXECUTE sp_getbindtoken @bind_token OUTPUT;
SELECT @bind_token AS Token;

Here is the result set.


Token

----------------------------------------------------------
\0]---5^PJK51bP<1F<-7U-]ANZ

See Also
sp_bindsession (Transact-SQL)
System Stored Procedures (Transact-SQL)
srv_getbindtoken (Extended Stored Procedure API)
sp_getapplock (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Places a lock on an application resource.
Transact-SQL Syntax Conventions

Syntax
sp_getapplock [ @Resource = ] 'resource_name' ,
[ @LockMode = ] 'lock_mode'
[ , [ @LockOwner = ] 'lock_owner' ]
[ , [ @LockTimeout = ] 'value' ]
[ , [ @DbPrincipal = ] 'database_principal' ]
[ ; ]

Arguments
[ @Resource= ] 'resource_name'
Is a string specifying a name that identifies the lock resource. The application must ensure that the resource name
is unique. The specified name is hashed internally into a value that can be stored in the SQL Server lock manager.
resource_name is nvarchar(255) with no default. If a resource string is longer than nvarchar(255), it will be
truncated to nvarchar(255).
resource_name is binary compared, and thus is case-sensitive regardless of the collation settings of the current
database.

NOTE
After an application lock has been acquired, only the first 32 characters can be retrieved in plain text; the remainder will be
hashed.

[ @LockMode= ] 'lock_mode'
Is the lock mode to be obtained for a particular resource. lock_mode is nvarchar(32) and has no default value. The
value can be any of the following: Shared, Update, IntentShared, IntentExclusive, or Exclusive.
[ @LockOwner= ] 'lock_owner'
Is the owner of the lock, which is the lock_owner value when the lock was requested. lock_owner is nvarchar(32).
The value can be Transaction (the default) or Session. When the lock_owner value is Transaction, by default or
specified explicitly, sp_getapplock must be executed from within a transaction.
[ @LockTimeout= ] 'value'
Is a lock time-out value in milliseconds. The default value is the same as the value returned by @@LOCK_TIMEOUT.
To indicate that a lock request should return an error instead of wait for the lock when the request cannot be
granted immediately, specify 0.
[ @DbPrincipal= ] 'database_principal'
Is the user, role, or application role that has permissions to an object in a database. The caller of the function must
be a member of database_principal, dbo, or the db_owner fixed database role to call the function successfully. The
default is public.

Return Code Values


>= 0 (success), or < 0 (failure)

VALUE RESULT

0 The lock was successfully granted synchronously.

1 The lock was granted successfully after waiting for other


incompatible locks to be released.

-1 The lock request timed out.

-2 The lock request was canceled.

-3 The lock request was chosen as a deadlock victim.

-999 Indicates a parameter validation or other call error.

Remarks
Locks placed on a resource are associated with either the current transaction or the current session. Locks
associated with the current transaction are released when the transaction commits or rolls back. Locks associated
with the session are released when the session is logged out. When the server shuts down for any reason, all locks
are released.
The lock resource created by sp_getapplock is created in the current database for the session. Each lock resource is
identified by the combined values of:
The database ID of the database containing the lock resource.
The database principle specified in the @DbPrincipal parameter.
The lock name specified in the @Resource parameter.
Only a member of the database principal specified in the @DbPrincipal parameter can acquire application
locks that specify that principal. Members of the dbo and db_owner roles are implicitly considered members
of all roles.
Locks can be explicitly released with sp_releaseapplock. When an application calls sp_getapplock multiple
times for the same lock resource, sp_releaseapplock must be called the same number of times to release the
lock.
If sp_getapplock is called multiple times for the same lock resource, but the lock mode that is specified in
any of the requests is not the same as the existing mode, the effect on the resource is a union of the two lock
modes. In most cases, this means the lock mode is promoted to the stronger of the lock modes, the existing
mode, or the newly requested mode. This stronger lock mode is held until the lock is ultimately released
even if lock release calls have occurred before that time. For example, in the following sequence of calls, the
resource is held in Exclusive mode instead of in Shared mode.
USE AdventureWorks2012;
GO
BEGIN TRANSACTION;
DECLARE @result int;
EXEC @result = sp_getapplock @Resource = 'Form1',
@LockMode = 'Shared';
EXEC @result = sp_getapplock @Resource = 'Form1',
@LockMode = 'Exclusive';
EXEC @result = sp_releaseapplock @Resource = 'Form1';
COMMIT TRANSACTION;
GO

A deadlock with an application lock does not roll back the transaction that requested the application lock. Any
rollback that might be required as a result of the return value must be done manually. Consequently, we
recommend that error checking be included in the code so that if certain values are returned (for example, -3), a
ROLLBACK TRANSACTION or alternative action is initiated.
Here is an example:

USE AdventureWorks2012;
GO
BEGIN TRANSACTION;
DECLARE @result int;
EXEC @result = sp_getapplock @Resource = 'Form1',
@LockMode = 'Exclusive';
IF @result = -3
BEGIN
ROLLBACK TRANSACTION;
END
ELSE
BEGIN
EXEC @result = sp_releaseapplock @Resource = 'Form1';
COMMIT TRANSACTION;
END;
GO

SQL Server uses the current database ID to qualify the resource. Therefore, if sp_getapplock is executed, even with
identical parameter values on different databases, the result is separate locks on separate resources.
Use the sys.dm_tran_locks dynamic management view or the sp_lock system stored procedure to examine lock
information, or use SQL Server Profiler to monitor locks.

Permissions
Requires membership in the public role.

Examples
The following example places a shared lock, which is associated with the current transaction, on the resource
Form1 in the AdventureWorks2012 database.

USE AdventureWorks2012;
GO
BEGIN TRAN;
DECLARE @result int;
EXEC @result = sp_getapplock @Resource = 'Form1',
@LockMode = 'Shared';
COMMIT TRAN;
GO
The following example specifies dbo as the database principal.

BEGIN TRAN;
EXEC sp_getapplock @DbPrincipal = 'dbo', @Resource = 'AdventureWorks2012',
@LockMode = 'Shared';
COMMIT TRAN;
GO

See Also
APPLOCK_MODE (Transact-SQL)
APPLOCK_TEST (Transact-SQL)
sp_releaseapplock (Transact-SQL)
sp_get_query_template (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the parameterized form of a query. The results returned mimic the parameterized form of a query that
results from using forced parameterization. sp_get_query_template is used primarily when you create TEMPLATE
plan guides.
Transact-SQL Syntax Conventions

Syntax
sp_get_query_template
[ @querytext = ] N'query_text'
, @templatetext OUTPUT
, @parameters OUTPUT

Arguments
'query_text'
Is the query for which the parameterized version is to be generated. 'query_text' must be enclosed in single
quotation marks and be preceded by the N Unicode specifier. N'query_text' is the value assigned to the @querytext
parameter. This is of type nvarchar(max).
@templatetext
Is an output parameter of type nvarchar(max), provided as indicated, to receive the parameterized form of
query_text as a string literal.
@parameters
Is an output parameter of type nvarchar(max), provided as indicated, to receive a string literal of the parameter
names and data types that have been parameterized in @templatetext.

Remarks
sp_get_query_template returns an error when the following occur:
It does not parameterize any constant literal values in query_text.
query_text is NULL, not a Unicode string, syntactically not valid, or cannot be compiled.
If sp_get_query_template returns an error, it does not modify the values of the @templatetext and
@parameters output parameters.

Permissions
Requires membership in the public database role.

Examples
The following example returns the parameterized form of a query that contains two constant literal values.

USE AdventureWorks2012;
GO
DECLARE @my_templatetext nvarchar(max)
DECLARE @my_parameters nvarchar(max)
EXEC sp_get_query_template
N'SELECT pi.ProductID, SUM(pi.Quantity) AS Total
FROM Production.ProductModel pm
INNER JOIN Production.ProductInventory pi
ON pm.ProductModelID = pi.ProductID
WHERE pi.ProductID = 2
GROUP BY pi.ProductID, pi.Quantity
HAVING SUM(pi.Quantity) > 400',
@my_templatetext OUTPUT,
@my_parameters OUTPUT;
SELECT @my_templatetext;
SELECT @my_parameters;

Here are the parameterized results of the @my_templatetext``OUTPUT parameter:


select pi . ProductID , SUM ( pi . Quantity ) as Total

from Production . ProductModel pm

inner join Production . ProductInventory pi

on pm . ProductModelID = pi . ProductID

where pi . ProductID = @0

group by pi . ProductID , pi . Quantity

having SUM ( pi . Quantity ) > 400

Note that the first constant literal, 2 , is converted to a parameter. The second literal, 400 , is not converted
because it is inside a HAVING clause. The results returned by sp_get_query_template mimic the parameterized form
of a query when the PARAMETERIZATION option of ALTER DATABASE is set to FORCED.
Here are the parameterized results of the @my_parameters OUTPUT parameter:

@0 int

NOTE
The order and naming of parameters in the output of sp_get_query_template can change between quick-fix engineering,
service pack, and version upgrades of SQL Server. Upgrades can also cause a different set of constant literals to be
parameterized for the same query, and different spacing to be applied in the results of both output parameters.

See Also
System Stored Procedures (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
Specify Query Parameterization Behavior by Using Plan Guides
sp_help (Transact-SQL)
11/21/2017 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports information about a database object (any object listed in the sys.sysobjects compatibility view), a user-
defined data type, or a data type.
Transact-SQL Syntax Conventions

Syntax
sp_help [ [ @objname = ] 'name' ]

Arguments
[ @objname=] 'name'
Is the name of any object, in sysobjects or any user-defined data type in the systypes table. name is
nvarchar(776), with a default of NULL. Database names are not acceptable. Two or three part names must be
delimited, such as 'Person.AddressType' or [Person.AddressType].

Return Code Values


0 (success) or 1 (failure)

Result Sets
The result sets that are returned depend on whether name is specified, when it is specified, and what database
object it is.
1. If sp_help is executed with no arguments, summary information of objects of all types that exist in the
current database is returned.

COLUMN NAME DATA TYPE DESCRIPTION

Name nvarchar(128) Object name

Owner nvarchar(128) Object owner (This is the database


principal that owns object. Defaults
to the owner of the schema that
contains the object.)

Object_type nvarchar(31) Object type

2. If name is a SQL Server data type or user-defined data type, sp_help returns this result set.
COLUMN NAME DATA TYPE DESCRIPTION

Type_name nvarchar(128) Data type name.

Storage_type nvarchar(128) SQL Server type name.

Length smallint Physical length of the data type (in


bytes).

Prec int Precision (total number of digits).

Scale int Number of digits to the right of the


decimal.

Nullable varchar(35) Indicates whether NULL values are


allowed: Yes or No.

Default_name nvarchar(128) Name of a default bound to this


type.

NULL = No default is bound.

Rule_name nvarchar(128) Name of a rule bound to this type.

NULL = No default is bound.

Collation sysname Collation of the data type. NULL for


non-character data types.

3. If name is any database object other than a data type, sp_help returns this result set and also additional
result sets, based on the type of object specified.

COLUMN NAME DATA TYPE DESCRIPTION

Name nvarchar(128) Table name

Owner nvarchar(128) Table owner

Type nvarchar(31) Table type

Created_datetime datetime Date table created

Depending on the database object specified, sp_help returns additional result sets.
If name is a system table, user table, or view, sp_help returns the following result sets. However, the result
set that describes where the data file is located on a file group is not returned for a view.
Additional result set returned on column objects:

COLUMN NAME DATA TYPE DESCRIPTION

Column_name nvarchar(128) Column name.

Type nvarchar(128) Column data type.


COLUMN NAME DATA TYPE DESCRIPTION

Computed varchar(35) Indicates whether the values in the


column are computed: Yes or No.

Length int Column length in bytes.

Note: If the column data type is a


large value type (varchar(max),
nvarchar(max), varbinary(max),
or xml), the value will display as -
1.

Prec char(5) Column precision.

Scale char(5) Column scale.

Nullable varchar(35) Indicates whether NULL values are


allowed in the column: Yes or No.

TrimTrailingBlanks varchar(35) Trim the trailing blanks. Returns


Yes or No.

FixedLenNullInSource varchar(35) For backward compatibility only.

Collation sysname Collation of the column. NULL for


noncharacter data types.

Additional result set returned on identity columns:

COLUMN NAME DATA TYPE DESCRIPTION

Identity nvarchar(128) Column name whose data type is


declared as identity.

Seed numeric Starting value for the identity


column.

Increment numeric Increment to use for values in this


column.

Not For Replication int IDENTITY property is not enforced


when a replication login, such as
sqlrepl, inserts data into the table:

1 = True

0 = False

Additional result set returned on columns:

COLUMN NAME DATA TYPE DESCRIPTION

RowGuidCol sysname Name of the global unique


identifier column.

Additional result set returned on filegroups:


COLUMN NAME DATA TYPE DESCRIPTION

Data_located_on_filegroup nvarchar(128) Filegroup in which the data is


located: Primary, Secondary, or
Transaction Log.

Additional result set returned on indexes:

COLUMN NAME DATA TYPE DESCRIPTION

index_name sysname Index name.

Index_description varchar(210) Description of the index.

index_keys nvarchar(2078) Column names on which the index


is built. Returns NULL for xVelocity
memory optimized columnstore
indexes.

Additional result set returned on constraints:

COLUMN NAME DATA TYPE DESCRIPTION

constraint_type nvarchar(146) Type of constraint.

constraint_name nvarchar(128) Name of the constraint.

delete_action nvarchar(9) Indicates whether the DELETE


action is: NO_ACTION, CASCADE,
SET_NULL, SET_DEFAULT, or N/A.

Only applicable to FOREIGN KEY


constraints.

update_action nvarchar(9) Indicates whether the UPDATE


action is: NO_ACTION, CASCADE,
SET_NULL, SET_DEFAULT, or N/A.

Only applicable to FOREIGN KEY


constraints.

status_enabled varchar(8) Indicates whether the constraint is


enabled: Enabled, Disabled, or N/A.

Only applicable to CHECK and


FOREIGN KEY constraints.

status_for_replication varchar(19) Indicates whether the constraint is


for replication.

Only applicable to CHECK and


FOREIGN KEY constraints.

constraint_keys nvarchar(2078) Names of the columns that make


up the constraint or, in the case
for defaults and rules, the text that
defines the default or rule.
Additional result set returned on referencing objects:

COLUMN NAME DATA TYPE DESCRIPTION

Table is referenced by nvarchar(516) Identifies other database objects


that reference the table.

Additional result set returned on stored procedures, functions, or extended stored procedures.

COLUMN NAME DATA TYPE DESCRIPTION

Parameter_name nvarchar(128) Stored procedure parameter


name.

Type nvarchar(128) Data type of the stored procedure


parameter.

Length smallint Maximum physical storage length,


in bytes.

Prec int Precision or total number of digits.

Scale int Number of digits to the right of


the decimal point.

Param_order smallint Order of the parameter.

Remarks
The sp_help procedure looks for an object in the current database only.
When name is not specified, sp_help lists object names, owners, and object types for all objects in the current
database. sp_helptrigger provides information about triggers.
sp_help exposes only orderable index columns; therefore, it does not expose information about XML indexes or
spatial indexes.

Permissions
Requires membership in the public role. The user must have at least one permission on objname. To view column
constraint keys, defaults, or rules, you must have VIEW DEFINITION permission on the table.

Examples
A. Returning information about all objects
The following example lists information about each object in the master database.

USE master;
GO
EXEC sp_help;
GO

B. Returning information about a single object


The following example displays information about the Person table.
USE AdventureWorks2012;
GO
EXEC sp_help 'Person.Person';
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
sp_helpindex (Transact-SQL)
sp_helprotect (Transact-SQL)
sp_helpserver (Transact-SQL)
sp_helptrigger (Transact-SQL)
sp_helpuser (Transact-SQL)
System Stored Procedures (Transact-SQL)
sys.sysobjects (Transact-SQL)
sp_helpconstraint (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a list of all constraint types, their user-defined or system-supplied name, the columns on which they have
been defined, and the expression that defines the constraint (for DEFAULT and CHECK constraints only).
Transact-SQL Syntax Conventions

Syntax
sp_helpconstraint [ @objname = ] 'table'
[ , [ @nomsg = ] 'no_message' ]

Arguments
[ @objname= ] 'table'
Is the table about which constraint information is returned. The table specified must be local to the current
database. table is nvarchar(776), with no default.
[ @nomsg=] 'no_message'
Is an optional parameter that prints the table name. no_message is varchar(5), with a default of msg. nomsg
suppresses the printing.

Return Code Values


0 (success) or 1 (failure)

Result Sets
sp_helpconstraint displays a descending indexed column if it participated in primary keys. The descending
indexed column will be listed in the result set with a minus sign (-) following its name. The default, an ascending
indexed column, will be listed by its name alone.

Remarks
Executing sp_helptable reports all information about the specified table. To see only the constraint information,
use sp_helpconstraint.

Permissions
Requires membership in the public role.

Examples
The following example shows all constraints for the Product table.
USE AdventureWorks2012;
GO
EXEC sp_helpconstraint 'Production.Product';

See Also
Database Engine Stored Procedures (Transact-SQL)
ALTER TABLE (Transact-SQL)
CREATE TABLE (Transact-SQL)
sp_help (Transact-SQL)
System Stored Procedures (Transact-SQL)
sys.key_constraints (Transact-SQL)
sys.check_constraints (Transact-SQL)
sys.default_constraints (Transact-SQL)
sp_helpdb (Transact-SQL)
1/2/2018 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports information about a specified database or all databases.
Transact-SQL Syntax Conventions

Syntax
sp_helpdb [ [ @dbname= ] 'name' ]

Arguments
[ @dbname= ] 'name'
Is the name of the database for which information is reported. name is sysname, with no default. If name is not
specified, sp_helpdb reports on all databases in the sys.databases catalog view.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

name sysname Database name.

db_size nvarchar(13) Total size of the database.

owner sysname Database owner, such as sa.

dbid smallint Database ID.

created nvarchar(11) Date the database was created.

status nvarchar(600) Comma-separated list of values of


database options that are currently set
on the database.

Boolean-valued options are listed only


if they are enabled. Non-Boolean
options are listed with their
corresponding values in the form of
option_name=value.

For more information, see ALTER


DATABASE (Transact-SQL).
COLUMN NAME DATA TYPE DESCRIPTION

compatibility_level tinyint Database compatibility level: 60, 65, 70,


80, or 90.

If name is specified, there is an additional result set that shows the file allocation for the specified database.

COLUMN NAME DATA TYPE DESCRIPTION

name nchar(128) Logical file name.

fileid smallint File ID.

filename nchar(260) Operating-system file name (physical


file name).

filegroup nvarchar(128) Filegroup in which the file belongs.

NULL = file is a log file. This is never a


part of a filegroup.

size nvarchar(18) File size in megabytes.

maxsize nvarchar(18) Maximum size to which the file can


grow. A value of UNLIMITED in this
field indicates that the file grows until
the disk is full.

growth nvarchar(18) Growth increment of the file. This


indicates the amount of space added to
the file each time new space is needed.

usage varchar(9) Usage of the file. For a data file, the


value is 'data only' and for the log file
the value is 'log only'.

Remarks
The status column in the result set reports which options have been set to ON in the database. All database
options are not reported by the status column. To see a complete list of the current database option settings, use
the sys.databases catalog view.

Permissions
When a single database is specified, membership in the public role in the database is required. When no database
is specified, membership in the public role in the master database is required.
If a database cannot be accessed, sp_helpdb displays error message 15622 and as much information about the
database as it can.

Examples
A. Returning information about a single database
The following example displays information about the AdventureWorks2012 database.
EXEC sp_helpdb N'AdventureWorks2012';

B. Returning information about all databases


This following example displays information about all databases on the server running SQL Server.

EXEC sp_helpdb;
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
ALTER DATABASE (Transact-SQL)
CREATE DATABASE (SQL Server Transact-SQL)
sys.databases (Transact-SQL)
sys.database_files (Transact-SQL)
sys.filegroups (Transact-SQL)
sys.master_files (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpdevice (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports information about Microsoft® SQL Server™ backup devices.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. We recommend that you use the sys.backup_devices catalog
view instead

Transact-SQL Syntax Conventions

Syntax
sp_helpdevice [ [ @devname = ] 'name' ]

Arguments
[ @devname = ] 'name'
Is the name of the backup device for which information is reported. The value of name is always sysname.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

device_name sysname Logical device name.

physical_name nvarchar(260) Physical file name.

description nvarchar(255) Description of the device.

status int A number that corresponds to the


status description in the description
column.

cntrltype smallint Controller type of the device:

2 = Disk device

5 = Tape device
COLUMN NAME DATA TYPE DESCRIPTION

size int Device size in 2-KB pages.

Remarks
If name is specified, sp_helpdevice displays information about the specified dump device. If name is not specified,
sp_helpdevice displays information about all dump devices in the sys.backup_devices catalog view.
Dump devices are added to the system by using sp_addumpdevice.

Permissions
Requires membership in the public role.

Examples
The following example reports information about all dump devices on an instance of SQL Server.

EXEC sp_helpdevice;

See Also
sp_addumpdevice (Transact-SQL)
sp_dropdevice (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpextendedproc (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports the currently defined extended stored procedures and the name of the dynamic-link library (DLL) to which
the procedure (function) belongs.

NOTE
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use CLR Integration instead.

Transact-SQL Syntax Conventions

Syntax
sp_helpextendedproc [ [@funcname = ] 'procedure' ]

Arguments
[ @funcname =] 'procedure'
Is the name of the extended stored procedure for which information is reported. procedure is sysname, with a
default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

name sysname Name of the extended stored


procedure.

dll nvarchar(255) Name of the DLL.

Remarks
When procedure is specified, sp_helpextendedproc reports on the specified extended stored procedure. When
this parameter is not supplied, sp_helpextendedproc returns all extended stored procedure names and the DLL
names to which each extended stored procedure belongs.

Permissions
Permission to execute sp_helpextendedproc is granted to public.
Examples
A. Reporting help on all extended stored procedures
The following example reports on all extended stored procedures.

USE master;
GO
EXEC sp_helpextendedproc;
GO

B. Reporting help on a single extended stored procedure


The following example reports on the xp_cmdshell extended stored procedure.

USE master;
GO
EXEC sp_helpextendedproc xp_cmdshell;
GO

See Also
sp_addextendedproc (Transact-SQL)
sp_dropextendedproc (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpfile (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the physical names and attributes of files associated with the current database. Use this stored procedure
to determine the names of files to attach to or detach from the server.
Transact-SQL Syntax Conventions

Syntax
sp_helpfile [ [ @filename= ] 'name' ]

Arguments
[ @filename = ] 'name'
Is the logical name of any file in the current database. name is sysname, with a default of NULL. If name is not
specified, the attributes of all files in the current database are returned.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

name sysname Logical file name.

fileid smallint Numeric identifier of the file. Is not


returned if name is specified.

filename nchar(260) Physical file name.

filegroup sysname Filegroup in which the file belongs.

NULL = File is a log file. This is never a


part of a filegroup.

size nvarchar(15) File size in kilobytes.

maxsize nvarchar(15) Maximum size to which the file can


grow. A value of UNLIMITED in this
field indicates that the file grows until
the disk is full.
COLUMN NAME DATA TYPE DESCRIPTION

growth nvarchar(15) Growth increment of the file. This


indicates the amount of space added to
the file every time that new space is
required.

0 = File is a fixed size and will not grow.

usage varchar(9) For data file, the value is 'data only'


and for the log file the value is 'log
only'.

Permissions
Requires membership in the public role.

Examples
The following example returns information about the files in AdventureWorks2012.

USE AdventureWorks2012;
GO
EXEC sp_helpfile;
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
sp_helpfilegroup (Transact-SQL)
sys.database_files (Transact-SQL)
sys.master_files (Transact-SQL)
sys.filegroups (Transact-SQL)
System Stored Procedures (Transact-SQL)
Database Files and Filegroups
sp_helpfilegroup (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the names and attributes of filegroups associated with the current database.
Transact-SQL Syntax Conventions

Syntax
sp_helpfilegroup [ [ @filegroupname = ] 'name' ]

Arguments
[ @filegroupname = ] 'name'
Is the logical name of any filegroup in the current database. name is sysname, with a default of NULL. If name is
not specified, all filegroups in the current database are listed and only the first result set shown in the Result Sets
section is displayed.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

groupname sysname Name of the filegroup.

groupid smallint Numeric filegroup identifier.

filecount int Number of files in the filegroup.

If name is specified, one row for each file in the filegroup is returned.

COLUMN NAME DATA TYPE DESCRIPTION

file_in_group sysname Logical name of the file in the filegroup.

fileid smallint Numeric file identifier.

filename nchar(260) Physical name of the file including the


directory path.

size nvarchar(15) File size in kilobytes.


COLUMN NAME DATA TYPE DESCRIPTION

maxsize nvarchar(15) Maximum size of the file.

This is the maximum size to which the


file can grow. A value of UNLIMITED in
this field indicates that the file grows
until the disk is full.

growth nvarchar(15) Growth increment of the file. This


indicates the amount of space added to
the file every time new space is
required.

0 = File is a fixed size and will not grow.

Permissions
Requires membership in the public role.

Examples
A. Returning all filegroups in a database
The following example returns information about the filegroups in the AdventureWorks2012 sample database.

USE AdventureWorks2012;
GO
EXEC sp_helpfilegroup;
GO

B. Returning all files in a filegroup


The following example returns information for all files in the PRIMARY filegroup in the AdventureWorks2012
sample database.

USE AdventureWorks2012;
GO
EXEC sp_helpfilegroup 'PRIMARY';
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
sp_helpfile (Transact-SQL)
sys.database_files (Transact-SQL)
sys.master_files (Transact-SQL)
sys.filegroups (Transact-SQL)
System Stored Procedures (Transact-SQL)
Database Files and Filegroups
sp_helpindex (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports information about the indexes on a table or view.
Transact-SQL Syntax Conventions

Syntax
sp_helpindex [ @objname = ] 'name'

Arguments
[ @objname= ] 'name'
Is the qualified or nonqualified name of a user-defined table or view. Quotation marks are required only if a
qualified table or view name is specified. If a fully qualified name, including a database name, is provided, the
database name must be the name of the current database. name is nvarchar(776), with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

index_name sysname Index name.

index_description varchar(210) Index description including the


filegroup it is located on.

index_keys nvarchar(2078) Table or view columns upon which the


index is built.

A descending indexed column will be listed in the result set with a minus sign (-) following its name; an ascending
indexed column, the default, will be listed by its name alone.

Remarks
If indexes have been set by using the NORECOMPUTE option of UPDATE STATISTICS, that information is included
in the index_description column.
sp_helpindex exposes only orderable index columns; therefore, it does not expose information about XML
indexes or spatial indexes.

Permissions
Requires membership in the public role.

Examples
The following example reports on the types of indexes on the Customer table.

USE AdventureWorks2012;
GO
EXEC sp_helpindex N'Sales.Customer';
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
sys.indexes (Transact-SQL)
sys.index_columns (Transact-SQL)
System Stored Procedures (Transact-SQL)
UPDATE STATISTICS (Transact-SQL)
sp_helplanguage (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Reports information about a particular alternative language or about all languages in SQL Server 2017.
Transact-SQL Syntax Conventions

Syntax
sp_helplanguage [ [ @language = ] 'language' ]

Arguments
[ @language= ] 'language'
Is the name of the alternative language for which to display information. language is sysname, with a default of
NULL. If language is specified, information about the specified language is returned. If language is not specified,
information about all languages in the sys.syslanguages compatibility view is returned.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

langid smallint Language identification number.

dateformat nchar(3) Format of the date.

datefirst tinyint First day of the week: 1 for Monday, 2


for Tuesday, and so on through 7 for
Sunday.

upgrade int SQL Server version of the last upgrade


for this language.

name sysname Language name.

alias sysname Alternative name of the language.

months nvarchar(372) Month names.

shortmonths nvarchar(132) Short month names.


COLUMN NAME DATA TYPE DESCRIPTION

days nvarchar(217) Day names.

lcid int Windows locale ID for the language.

msglangid smallint SQL Server message group ID.

Permissions
Requires membership in the public role.

Examples
A. Returning information about a single language
The following example displays information about the alternative language French .

sp_helplanguage French;

B. Returning information about all languages


The following example displays information about all installed alternative languages.

sp_helplanguage;

See Also
Database Engine Stored Procedures (Transact-SQL)
@@LANGUAGE (Transact-SQL)
SET LANGUAGE (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpserver (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports information about a particular remote or replication server, or about all servers of both types. Provides
the server name, the network name of the server, the replication status of the server, the identification number of
the server, and the collation name. Also provides time-out values for connecting to, or queries against, linked
servers.
Transact-SQL Syntax Conventions

Syntax
sp_helpserver [ [ @server = ] 'server' ]
[ , [ @optname = ] 'option' ]
[ , [ @show_topology = ] 'show_topology' ]

Arguments
[ @server = ] 'server'
Is the server about which information is reported. When server is not specified, reports about all servers in
master.sys.servers. server is sysname, with a default of NULL.
[ @optname = ] 'option'
Is the option describing the server. option is varchar(35), with a default of NULL, and must be one of these
values.

VALUE DESCRIPTION

collation compatible Affects the Distributed Query execution against linked


servers. If this option is set to true,

data access Enables and disables a linked server for distributed query
access.

dist Distributor.

dpub Remote Publisher to this Distributor.

lazy schema validation Skips schema checking of remote tables at the beginning of
the query.

pub Publisher.

rpc Enables RPC from the specified server.

rpc out Enables RPC to the specified server.


VALUE DESCRIPTION

sub Subscriber.

system Identified for informational purposes only. Not supported.


Future compatibility is not guaranteed.

use remote collation Uses the collation of a remote column instead of that of the
local server.

[ @show_topology = ] 'show_topology'
Is the relationship of the specified server to other servers. show_topology is varchar(1), with a default of NULL. If
show_topology is not equal to t or is NULL, sp_helpserver returns columns listed in the Result Sets section. If
show_topology is equal to t, in addition to the columns listed in the Result Sets, sp_helpserver also returns topx
and topy information.

Return Code Values


0 (success) or 1 (failure).

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

name sysname Server name.

network_name sysname Network name of the server.

status varchar(70) Server status.

id char(4) Identification number of the server.

collation_name sysname Collation of the server.

connect_timeout int Time-out value for connecting to linked


server.

query_timeout int Time-out value for queries against


linked server.

Remarks
A server can have more than one status.

Permissions
No permissions are checked.

Examples
A. Displaying information about all servers
The following example displays information about all servers by using sp_helpserver with no parameters.
USE master;
GO
EXEC sp_helpserver;

B. Displaying information about a specific server


The following example displays all information about the SEATTLE2 server.

USE master;
GO
EXEC sp_helpserver 'SEATTLE2';

See Also
Database Engine Stored Procedures (Transact-SQL)
sp_adddistpublisher (Transact-SQL)
sp_addserver (Transact-SQL)
sp_addsubscriber (Transact-SQL)
sp_changesubscriber (Transact-SQL)
sp_dropserver (Transact-SQL)
sp_dropsubscriber (Transact-SQL)
sp_helpdistributor (Transact-SQL)
sp_helpremotelogin (Transact-SQL)
sp_helpsubscriberinfo (Transact-SQL)
sp_serveroption (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpsort (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Displays the sort order and character set for the instance of SQL Server.
Transact-SQL Syntax Conventions

Syntax
sp_helpsort

Return Code Values


0 (success) or 1 (failure)

Result Sets
Returns server default collation.

Remarks
If an instance of SQL Server is installed with a collation specified to be compatible with an earlier installation of
SQL Server, sp_helpsort returns blank results. When this behavior occurs, you can determine the collation by
querying the SERVERPROPERTY object, such as: SELECT SERVERPROPERTY ('Collation'); .

Permissions
Requires membership in the public role.

Examples
The following example displays the name of the default sort order of the server, its character set, and a table of its
primary sort values.

sp_helpsort;

Here is the result set.


Server default collation

------------------------

Latin1-General, case-sensitive, accent-sensitive, kanatype-insensitive, width-insensitive for Unicode Data, SQL


Server Sort Order 51 on Code Page 1252 for non-Unicode Data.

See Also
System Stored Procedures (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
COLLATE (Transact-SQL)
sys.fn_helpcollations (Transact-SQL)
SERVERPROPERTY (Transact-SQL)
sp_helpstats (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns statistics information about columns and indexes on the specified table.

IMPORTANT
This feature will be removed in the next version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. To obtain information about statistics, query the sys.stats and
sys.stats_columns catalog views.

Transact-SQL Syntax Conventions

Syntax
sp_helpstats[ @objname = ] 'object_name'
[ , [ @results = ] 'value' ]

Arguments
[ @objname=] 'object_name'
Specifies the table on which to provide statistics information. object_name is nvarchar(520) and cannot be null. A
one- or two-part name can be specified.
[ @results=] 'value'
Specifies the extent of information to provide. Valid entries are ALL and STATS. ALL lists statistics for all indexes
and also columns that have statistics created on them; STATS only lists statistics not associated with an index. value
is nvarchar(5) with a default of STATS.

Return Code Values


0 (success) or 1 (failure)

Result Sets
The following table describes the columns in the result set.

COLUMN NAME DESCRIPTION

statistics_name The name of the statistics. Returns sysname and cannot be


null.

statistics_keys The keys on which statistics are based. Returns


nvarchar(2078) and cannot be null.
Remarks
Use DBCC SHOW_STATISTICS to display detailed statistics information about any particular index or statistics. For
more information, see DBCC SHOW_STATISTICS (Transact-SQL) and sp_helpindex (Transact-SQL).

Permissions
Requires membership in the public role.

Examples
The following example creates single-column statistics for all eligible columns for all user tables in the
AdventureWorks2012 database by executing sp_createstats . Then, sp_helpstats is run to find the resultant
statistics created on the Customer table.

USE AdventureWorks2012;
GO
EXEC sp_createstats;
GO
EXEC sp_helpstats
@objname = 'Sales.Customer',
@results = 'ALL';

Here is the result set.


statistics_name statistics_keys

---------------------------- ----------------

_WA_Sys_00000003_22AA2996 AccountNumber

AK_Customer_AccountNumber AccountNumber

AK_Customer_rowguid rowguid

CustomerType CustomerType

IX_Customer_TerritoryID TerritoryID

ModifiedDate ModifiedDate

PK_Customer_CustomerID CustomerID

See Also
System Stored Procedures (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
sp_helptext (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Displays the definition of a user-defined rule, default, unencrypted Transact-SQL stored procedure, user-defined
Transact-SQL function, trigger, computed column, CHECK constraint, view, or system object such as a system
stored procedure.
Transact-SQL Syntax Conventions

Syntax
sp_helptext [ @objname = ] 'name' [ , [ @columnname = ] computed_column_name ]

Arguments
[ @objname = ] 'name'
Is the qualified or nonqualified name of a user-defined, schema-scoped object. Quotation marks are required only
if a qualified object is specified. If a fully qualified name, including a database name, is provided, the database
name must be the name of the current database. The object must be in the current database. name is
nvarchar(776), with no default.
[ @columnname = ] 'computed_column_name'
Is the name of the computed column for which to display definition information. The table that contains the
column must be specified as name. column_name is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

Text nvarchar(255) Object definition

Remarks
sp_helptext displays the definition that is used to create an object in multiple rows. Each row contains 255
characters of the Transact-SQL definition. The definition resides in the definition column in the sys.sql_modules
catalog view.

Permissions
Requires membership in the public role. System object definitions are publicly visible. The definition of user
objects is visible to the object owner or grantees that have any one of the following permissions: ALTER,
CONTROL, TAKE OWNERSHIP, or VIEW DEFINITION.

Examples
A. Displaying the definition of a trigger
The following example displays the definition of the trigger dEmployee in the AdventureWorks2012database.

USE AdventureWorks2012;
GO
EXEC sp_helptext 'HumanResources.dEmployee';
GO

B. Displaying the definition of a computed column


The following example displays the definition of the computed column TotalDue on the SalesOrderHeader table in
the AdventureWorks2012 database.

USE AdventureWorks2012;
GO
sp_helptext @objname = N'AdventureWorks2012.Sales.SalesOrderHeader', @columnname = TotalDue ;
GO

Here is the result set.


Text

---------------------------------------------------------------------

(isnull(([SubTotal]+[TaxAmt])+[Freight],(0)))

See Also
Database Engine Stored Procedures (Transact-SQL)
OBJECT_DEFINITION (Transact-SQL)
sp_help (Transact-SQL)
sys.sql_modules (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helptrigger (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the type or types of DML triggers defined on the specified table for the current database. sp_helptrigger
cannot be used with DDL triggers. Query the system stored procedures catalog view instead.
Transact-SQL Syntax Conventions

Syntax
sp_helptrigger [ @tabname = ] 'table'
[ , [ @triggertype = ] 'type' ]

Arguments
[ @tabname= ] 'table'
Is the name of the table in the current database for which to return trigger information. table is nvarchar(776),
with no default.
[ @triggertype= ] 'type'
Is the type of DML trigger to return information about. type is char(6), with a default of NULL, and can be one of
these values.

VALUE DESCRIPTION

DELETE Returns DELETE trigger information.

INSERT Returns INSERT trigger information.

UPDATE Returns UPDATE trigger information.

Return Code Values


0 (success) or 1 (failure)

Result Sets
The following table shows the information that is contained in the result set.

COLUMN NAME DATA TYPE DESCRIPTION

trigger_name sysname Name of the trigger.

trigger_owner sysname Name of the owner of the table on


which the trigger is defined.
COLUMN NAME DATA TYPE DESCRIPTION

isupdate int 1=UPDATE trigger

0=Not an UPDATE trigger

isdelete int 1=DELETE trigger

0=Not a DELETE trigger

isinsert int 1=INSERT trigger

0=Not an INSERT trigger

isafter int 1=AFTER trigger

0=Not an AFTER trigger

isinsteadof int 1=INSTEAD OF trigger

0=Not an INSTEAD OF trigger

trigger_schema sysname Name of the schema to which the


trigger belongs.

Permissions
Requires Metadata Visibility Configuration permission on the table.

Examples
The following example executes sp_helptrigger to produce information about the trigger(s) on the Person.Person
table.

USE AdventureWorks2012;
GO
EXEC sp_helptrigger 'Person.Person';

See Also
Database Engine Stored Procedures (Transact-SQL)
ALTER TRIGGER (Transact-SQL)
CREATE TRIGGER (Transact-SQL)
DROP TRIGGER (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_indexoption (Transact-SQL)
1/2/2018 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Sets locking option values for user-defined clustered and nonclustered indexes or tables with no clustered index.
The SQL Server Database Engine automatically makes choices of page-, row-, or table-level locking. You do not
have to set these options manually. sp_indexoption is provided for expert users who know with certainty that a
particular type of lock is always appropriate.

IMPORTANT
This feature will be removed in the next version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Instead, use ALTER INDEX (Transact-SQL).

Transact-SQL Syntax Conventions

Syntax
sp_indexoption [ @IndexNamePattern = ] 'table_or_index_name'
, [ @OptionName = ] 'option_name'
, [ @OptionValue = ] 'value'

Arguments
[ @IndexNamePattern=] 'table_or_index_name'
Is the qualified or nonqualified name of a user-defined table or index. table_or_index_name is nvarchar(1035),
with no default. Quotation marks are required only if a qualified index or table name is specified. If a fully qualified
table name, including a database name, is provided, the database name must be the name of the current database.
If a table name is specified with no index, the specified option value is set for all indexes on that table and the table
itself if no clustered index exists.
[ @OptionName =] 'option_name'
Is an index option name. option_name is varchar(35), with no default. option_name can have one of the following
values.

VALUE DESCRIPTION

AllowRowLocks When TRUE, row locks are allowed when accessing the index.
The Database Engine determines when row locks are used.
When FALSE, row locks are not used. The default is TRUE.

AllowPageLocks When TRUE, page locks are allowed when accessing the index.
The Database Engine determines when page locks are used.
When FALSE, page locks are not used. The default is TRUE.
VALUE DESCRIPTION

DisAllowRowLocks When TRUE, row locks are not used. When FALSE, row locks
are allowed when accessing the index. The Database Engine
determines when row locks are used.

DisAllowPageLocks When TRUE, page locks are not used. When FALSE, page locks
are allowed when accessing the index. The Database Engine
determines when page locks are used.

[ @OptionValue =] 'value'
Specifies whether the option_name setting is enabled (TRUE, ON, yes, or 1) or disabled (FALSE, OFF, no, or 0). value
is varchar(12), with no default.

Return Code Values


0 (success) or greater than 0 (failure)

Remarks
XML indexes are not supported. If an XML index is specified, or a table name is specified with no index name and
the table contains an XML index, the statement fails. To set these options, use ALTER INDEX instead.
To display the current row and page locking properties, use INDEXPROPERTY or the sys.indexes catalog view.
Row-, page-, and table-level locks are allowed when accessing the index when AllowRowLocks = TRUE or
DisAllowRowLocks = FALSE, and AllowPageLocks = TRUE or DisAllowPageLocks = FALSE. The
Database Engine chooses the appropriate lock and can escalate the lock from a row or page lock to a table
lock.
Only a table-level lock is allowed when accessing the index when AllowRowLocks = FALSE or
DisAllowRowLocks = TRUE and AllowPageLocks = FALSE or DisAllowPageLocks = TRUE.
If a table name is specified with no index, the settings are applied to all indexes on that table. When the
underlying table has no clustered index (that is, it is a heap) the settings are applied as follows:
When AllowRowLocks or DisAllowRowLocks are set to TRUE or FALSE, the setting is applied to the heap
and any associated nonclustered indexes.
When AllowPageLocks option is set to TRUE or DisAllowPageLocks is set to FALSE, the setting is applied
to the heap and any associated nonclustered indexes.
When AllowPageLocks option is set FALSE or DisAllowPageLocks is set to TRUE, the setting is fully
applied to the nonclustered indexes. That is, all page locks are disallowed on the nonclustered indexes. On
the heap, only the shared (S), update (U), and exclusive (X) locks for the page are disallowed. The Database
Engine can still acquire an intent page lock (IS, IU or IX) for internal purposes.

Permissions
Requires ALTER permission on the table.

Examples
A. Setting an option on a specific index
The following example disallows page locks on the IX_Customer_TerritoryID index on the Customer table.
USE AdventureWorks2012;
GO
EXEC sp_indexoption N'Sales.Customer.IX_Customer_TerritoryID',
N'disallowpagelocks', TRUE;

B. Setting an option on all indexes on a table


The following example disallows row locks on all indexes associated with the Product table. The sys.indexes
catalog view is queried before and after executing the sp_indexoption procedure to show the results of the
statement.

USE AdventureWorks2012;
GO
--Display the current row and page lock options for all indexes on the table.
SELECT name, type_desc, allow_row_locks, allow_page_locks
FROM sys.indexes
WHERE object_id = OBJECT_ID(N'Production.Product');
GO
-- Set the disallowrowlocks option on the Product table.
EXEC sp_indexoption N'Production.Product',
N'disallowrowlocks', TRUE;
GO
--Verify the row and page lock options for all indexes on the table.
SELECT name, type_desc, allow_row_locks, allow_page_locks
FROM sys.indexes
WHERE object_id = OBJECT_ID(N'Production.Product');
GO

C. Setting an option on a table with no clustered index


The following example disallows page locks on a table with no clustered index (a heap). The sys.indexes catalog
view is queried before and after the sp_indexoption procedure is executed to show the results of the statement.

USE AdventureWorks2012;
GO
--Display the current row and page lock options of the table.
SELECT OBJECT_NAME (object_id) AS [Table], type_desc, allow_row_locks, allow_page_locks
FROM sys.indexes
WHERE OBJECT_NAME (object_id) = N'DatabaseLog';
GO
-- Set the disallowpagelocks option on the table.
EXEC sp_indexoption DatabaseLog,
N'disallowpagelocks', TRUE;
GO
--Verify the row and page lock settings of the table.
SELECT OBJECT_NAME (object_id) AS [Table], allow_row_locks, allow_page_locks
FROM sys.indexes
WHERE OBJECT_NAME (object_id) = N'DatabaseLog';
GO

See Also
INDEXPROPERTY (Transact-SQL)
System Stored Procedures (Transact-SQL)
sys.indexes (Transact-SQL)
sp_invalidate_textptr (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Invalidates the specified in-row text pointer, or all in-row text pointers, in the transaction. sp_invalidate_textptr
can be used only on in-row text pointers. These pointers are from tables that have the text in row option enabled.
Transact-SQL Syntax Conventions

Syntax
sp_invalidate_textptr [ [ @TextPtrValue = ] textptr_value ]

Arguments
[ @TextPtrValue= ] textptr_value
Is the in-row text pointer that to be invalidated. textptr_value is varbinary(16), with a default of NULL. If NULL,
sp_invalidate_textptr invalidates all in-row text pointers in the transaction.

Return Code Values


0 (success) or 1 (failure)

Remarks
SQL Server allows for a maximum of 1,024 active valid in-row text pointers per transaction per database; however,
a transaction spanning more than one database can have 1,024 in-row text pointers in each database.
sp_invalidate_textptr can be used to invalidate in-row text pointers and, therefore, free space for additional in-
row text pointers.
For more information about the text in row option, see sp_tableoption (Transact-SQL).

Permissions
Requires membership in the public role.

See Also
Database Engine Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_tableoption (Transact-SQL)
TEXTPTR (Transact-SQL)
TEXTVALID (Transact-SQL)
sp_lock (Transact-SQL)
11/27/2017 • 6 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Reports information about locks.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. To obtain information about locks in the SQL Server Database
Engine, use the sys.dm_tran_locks dynamic management view.

Transact-SQL Syntax Conventions

Syntax
sp_lock [ [ @spid1 = ] 'session ID1' ] [ , [@spid2 = ] 'session ID2' ]
[ ; ]

Arguments
[ @spid1 = ] 'session ID1'
Is a Database Engine session ID number from sys.dm_exec_sessions for which the user wants locking
information. session ID1 is int with a default value of NULL. Execute sp_who to obtain process information about
the session. If session ID1 is not specified, information about all locks is displayed.
[ @spid2 = ] 'session ID2'
Is another Database Engine session ID number from sys.dm_exec_sessions that might have a lock at the same
time as session ID1 and about which the user also wants information. session ID2 is int with a default value of
NULL.

Return Code Values


0 (success)

Result Sets
The sp_lock result set contains one row for each lock held by the sessions specified in the @spid1 and @spid2
parameters. If neither @spid1 nor @spid2 is specified, the result set reports the locks for all sessions currently
active in the instance of the Database Engine.

COLUMN NAME DATA TYPE DESCRIPTION

spid smallint The Database Engine session ID


number for the process requesting the
lock.
COLUMN NAME DATA TYPE DESCRIPTION

dbid smallint The identification number of the


database in which the lock is held. You
can use the DB_NAME() function to
identify the database.

ObjId int The identification number of the object


on which the lock is held. You can use
the OBJECT_NAME() function in the
related database to identify the object.
A value of 99 is a special case that
indicates a lock on one of the system
pages used to record the allocation of
pages in a database.

IndId smallint The identification number of the index


on which the lock is held.

Type nchar(4) The lock type:

RID = Lock on a single row in a table


identified by a row identifier (RID).

KEY = Lock within an index that


protects a range of keys in serializable
transactions.

PAG = Lock on a data or index page.

EXT = Lock on an extent.

TAB = Lock on an entire table, including


all data and indexes.

DB = Lock on a database.

FIL = Lock on a database file.

APP = Lock on an application-specified


resource.

MD = Locks on metadata, or catalog


information.

HBT = Lock on a heap or B-Tree index.


This information is incomplete in SQL
Server.

AU = Lock on an allocation unit. This


information is incomplete in SQL Server.
COLUMN NAME DATA TYPE DESCRIPTION

Resource nchar(32) The value identifying the resource that


is locked. The format of the value
depends on the type of resource
identified in the Type column:

Type Value: Resource Value

RID: An identifier in the format


fileid:pagenumber:rid, where fileid
identifies the file containing the page,
pagenumber identifies the page
containing the row, and rid identifies
the specific row on the page. fileid
matches the file_id column in the
sys.database_files catalog view.

KEY: A hexadecimal number used


internally by the Database Engine.

PAG: A number in the format


fileid:pagenumber, where fileid identifies
the file containing the page, and
pagenumber identifies the page.

EXT: A number identifying the first page


in the extent. The number is in the
format fileid:pagenumber.

TAB: No information provided because


the table is already identified in the
ObjId column.

DB: No information provided because


the database is already identified in the
dbid column.

FIL: The identifier of the file, which


matches the file_id column in the
sys.database_files catalog view.

APP: An identifier unique to the


application resource being locked. In
the format DbPrincipleId:<first two to
16 characters of the resource string>
<hashed value>.

MD: varies by resource type. For more


information, see the description of the
resource_description column in
sys.dm_tran_locks (Transact-SQL).

HBT: No information provided. Use the


sys.dm_tran_locks dynamic
management view instead.

AU: No information provided. Use the


sys.dm_tran_locks dynamic
management view instead.

Mode nvarchar(8) The lock mode requested. Can be:

NULL = No access is granted to the


resource. Serves as a placeholder.
COLUMN NAME DATA TYPE DESCRIPTION
Sch-S = Schema stability. Ensures that a
schema element, such as a table or
index, is not dropped while any session
holds a schema stability lock on the
schema element.

Sch-M = Schema modification. Must be


held by any session that wants to
change the schema of the specified
resource. Ensures that no other
sessions are referencing the indicated
object.

S = Shared. The holding session is


granted shared access to the resource.

U = Update. Indicates an update lock


acquired on resources that may
eventually be updated. It is used to
prevent a common form of deadlock
that occurs when multiple sessions lock
resources for potential update at a later
time.

X = Exclusive. The holding session is


granted exclusive access to the
resource.

IS = Intent Shared. Indicates the


intention to place S locks on some
subordinate resource in the lock
hierarchy.

IU = Intent Update. Indicates the


intention to place U locks on some
subordinate resource in the lock
hierarchy.

IX = Intent Exclusive. Indicates the


intention to place X locks on some
subordinate resource in the lock
hierarchy.

SIU = Shared Intent Update. Indicates


shared access to a resource with the
intent of acquiring update locks on
subordinate resources in the lock
hierarchy.

SIX = Shared Intent Exclusive. Indicates


shared access to a resource with the
intent of acquiring exclusive locks on
subordinate resources in the lock
hierarchy.

UIX = Update Intent Exclusive. Indicates


an update lock hold on a resource with
the intent of acquiring exclusive locks
on subordinate resources in the lock
hierarchy.

BU = Bulk Update. Used by bulk


operations.
COLUMN NAME DATA TYPE DESCRIPTION
RangeS_S = Shared Key-Range and
Shared Resource lock. Indicates
serializable range scan.

RangeS_U = Shared Key-Range and


Update Resource lock. Indicates
serializable update scan.

RangeI_N = Insert Key-Range and Null


Resource lock. Used to test ranges
before inserting a new key into an
index.

RangeI_S = Key-Range Conversion lock.


Created by an overlap of RangeI_N and
S locks.

RangeI_U = Key-Range Conversion lock


created by an overlap of RangeI_N and
U locks.

RangeI_X = Key-Range Conversion lock


created by an overlap of RangeI_N and
X locks.

RangeX_S = Key-Range Conversion lock


created by an overlap of RangeI_N and
RangeS_S. locks.

RangeX_U = Key-Range Conversion


lock created by an overlap of RangeI_N
and RangeS_U locks.

RangeX_X = Exclusive Key-Range and


Exclusive Resource lock. This is a
conversion lock used when updating a
key in a range.

Status nvarchar(5) The lock request status:

CNVRT: The lock is being converted


from another mode, but the conversion
is blocked by another process holding a
lock with a conflicting mode.

GRANT: The lock was obtained.

WAIT: The lock is blocked by another


process holding a lock with a conflicting
mode.

Remarks
Users can control the locking of read operations by:
Using SET TRANSACTION ISOLATION LEVEL to specify the level of locking for a session. For syntax and
restrictions, see SET TRANSACTION ISOLATION LEVEL (Transact-SQL).
Using locking table hints to specify the level of locking for an individual reference of a table in a FROM
clause. For syntax and restrictions, see Table Hints (Transact-SQL).
All distributed transactions not associated with a session are orphaned transactions. The Database Engine
assigns all orphaned distributed transactions the SPID value of -2, which makes it easier for a user to
identify blocking distributed transactions. For more information, see Use Marked Transactions to Recover
Related Databases Consistently (Full Recovery Model).

Permissions
Requires VIEW SERVER STATE permission.

Examples
A. Listing all locks
The following example displays information about all locks currently held in an instance of the Database Engine.

USE master;
GO
EXEC sp_lock;
GO

B. Listing a lock from a single -server process


The following example displays information, including locks, about process ID 53 .

USE master;
GO
EXEC sp_lock 53;
GO

See Also
sys.dm_tran_locks (Transact-SQL)
DB_NAME (Transact-SQL)
KILL (Transact-SQL)
OBJECT_NAME (Transact-SQL)
sp_who (Transact-SQL)
sys.database_files (Transact-SQL)
sys.dm_os_tasks (Transact-SQL)
sys.dm_os_threads (Transact-SQL)
sp_monitor (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Displays statistics about Microsoft SQL Server.
Transact-SQL Syntax Conventions

Syntax
sp_monitor

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DESCRIPTION

last_run Time sp_monitor was last run.

current_run Time sp_monitor is being run.

seconds Number of elapsed seconds since sp_monitor was run.

cpu_busy Number of seconds that the server computer's CPU has been
doing SQL Server work.

io_busy Number of seconds that SQL Server has spent doing input
and output operations.

idle Number of seconds that SQL Server has been idle.

packets_received Number of input packets read by SQL Server.

packets_sent Number of output packets written by SQL Server.

packet_errors Number of errors encountered by SQL Server while reading


and writing packets.

total_read Number of reads by SQL Server.

total_write Number of writes by SQL Server.

total_errors Number of errors encountered by SQL Server while reading


and writing.
COLUMN NAME DESCRIPTION

connections Number of logins or attempted logins to SQL Server.

Remarks
SQL Server keeps track, through a series of functions, of how much work it has done. Executing sp_monitor
displays the current values returned by these functions and shows how much they have changed since the last time
the procedure was run.
For each column, the statistic is printed in the form number(number)-number% or number(number). The first
number refers to the number of seconds (for cpu_busy, io_busy, and idle) or the total number (for the other
variables) since SQL Server was restarted. The number in parentheses refers to the number of seconds or total
number since the last time sp_monitor was run. The percentage is the percentage of time since sp_monitor was
last run. For example, if the report shows cpu_busy as 4250(215)-68%, the CPU has been busy 4250 seconds since
SQL Server was last started up, 215 seconds since sp_monitor was last run, and 68 percent of the total time since
sp_monitor was last run.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example reports information about how busy SQL Server has been.

USE master
EXEC sp_monitor

Here is the result set.

last_run current_run seconds

Mar 29 1998 11:55AM Apr 4 1998 2:22 PM 561

cpu_busy io_busy idle

190(0)-0% 187(0)-0% 148(556)-99%

packets_received packets_sent packet_errors

16(1) 20(2) 0(0)

total_read total_write total_errors connections

141(0) 54920(127) 0(0) 4(0)


See Also
sp_who (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_procoption (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Sets or clears a stored procedure for automatic execution. A stored procedure that is set to automatic execution
runs every time an instance of SQL Server is started.
Transact-SQL Syntax Conventions

Syntax
sp_procoption [ @ProcName = ] 'procedure'
, [ @OptionName = ] 'option'
, [ @OptionValue = ] 'value'

Arguments
[ @ProcName = ] 'procedure'
Is the name of the procedure for which to set an option. procedure is nvarchar(776), with no default.
[ @OptionName = ] 'option'
Is the name of the option to set. The only value for option is startup.
[ @OptionValue = ] 'value'
Is whether to set the option on (true or on) or off (false or off). value is varchar(12), with no default.

Return Code Values


0 (success) or error number (failure)

Remarks
Startup procedures must be in the master database and cannot contain INPUT or OUTPUT parameters. Execution
of the stored procedures starts when all databases are recovered and the "Recovery is completed" message is
logged at startup.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example sets a procedure for automatic execution.

EXEC sp_procoption @ProcName = '<procedure name>'


, @OptionName = ] 'startup'
, @OptionValue = 'on';
The following example stops a procedure from executing automatically.

EXEC sp_procoption @ProcName = '<procedure name>'


, @OptionValue = 'off';

See Also
Execute a Stored Procedure
sp_recompile (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Causes stored procedures, triggers, and user-defined functions to be recompiled the next time that they are run. It
does this by dropping the existing plan from the procedure cache forcing a new plan to be created the next time
that the procedure or trigger is run. In a SQL Server Profiler collection, the event SP:CacheInsert is logged instead
of the event SP:Recompile.
Transact-SQL Syntax Conventions

Syntax
sp_recompile [ @objname = ] 'object'

Arguments
[ @objname= ] 'object'
The qualified or unqualified name of a stored procedure, trigger, table, view, or user-defined function in the current
database. object is nvarchar(776), with no default. If object is the name of a stored procedure, trigger, or user-
defined function, the stored procedure, trigger, or function will be recompiled the next time that it is run. If object is
the name of a table or view, all the stored procedures, triggers, or user-defined functions that reference the table or
view will be recompiled the next time that they are run.

Return Code Values


0 (success) or a nonzero number (failure)

Remarks
sp_recompile looks for an object in the current database only.
The queries used by stored procedures, or triggers, and user-defined functions are optimized only when they are
compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures,
triggers, and user-defined functions may lose efficiency. By recompiling stored procedures and triggers that act on
a table, you can reoptimize the queries.

NOTE
SQL Server automatically recompiles stored procedures, triggers, and user-defined functions when it is advantageous to do
this.

Permissions
Requires ALTER permission on the specified object.
Examples
The following example causes stored procedures, triggers, and user-defined functions that act on the Customer
table to be recompiled the next time that they are run.

USE AdventureWorks2012;
GO
EXEC sp_recompile N'Sales.Customer';
GO

See Also
CREATE PROCEDURE (Transact-SQL)
CREATE TRIGGER (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_refreshsqlmodule (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Updates the metadata for the specified non-schema-bound stored procedure, user-defined function, view, DML
trigger, database-level DDL trigger, or server-level DDL trigger in the current database. Persistent metadata for
these objects, such as data types of parameters, can become outdated because of changes to their underlying
objects.
Transact-SQL Syntax Conventions

Syntax
sys.sp_refreshsqlmodule [ @name = ] 'module_name'
[ , [ @namespace = ] ' <class> ' ]

<class> ::=
{
| DATABASE_DDL_TRIGGER
| SERVER_DDL_TRIGGER
}

Arguments
[ @name= ] 'module_name'
Is the name of the stored procedure, user-defined function, view, DML trigger, database-level DDL trigger, or
server-level DDL trigger. module_name cannot be a common language runtime (CLR) stored procedure or a CLR
function. module_name cannot be schema-bound. module_name is nvarchar, with no default. module_name can
be a multi-part identifier, but can only refer to objects in the current database.
[ , @namespace = ] ' <class> '
Is the class of the specified module. When module_name is a DDL trigger, <class> is required. <class> is
nvarchar(20). Valid inputs are:

DATABASE_DDL_TRIGGER

SERVER_DDL_TRIGGER Applies to: SQL Server 2008 through SQL Server 2017.

Return Code Values


0 (success) or a nonzero number (failure)

Remarks
sp_refreshsqlmodule should be run when changes are made to the objects underlying the module that affect its
definition. Otherwise, the module might produce unexpected results when it is queried or invoked. To refresh a
view, you can use either sp_refreshsqlmodule or sp_refreshview with the same results.
sp_refreshsqlmodule does not affect any permissions, extended properties, or SET options that are associated
with the object.
To refresh a server-level DDL trigger, execute this stored procedure from the context of any database.

NOTE
Any signatures that are associated with the object are dropped when you run sp_refreshsqlmodule.

Permissions
Requires ALTER permission on the module and REFERENCES permission on any CLR user-defined types and XML
schema collections that are referenced by the object. Requires ALTER ANY DATABASE DDL TRIGGER permission in
the current database when the specified module is a database-level DDL trigger. Requires CONTROL SERVER
permission when the specified module is a server-level DDL trigger.
Additionally, for modules that are defined with the EXECUTE AS clause, IMPERSONATE permission is required on
the specified principal. Generally, refreshing an object does not change its EXECUTE AS principal, unless the module
was defined with EXECUTE AS USER and the user name of the principal now resolves to a different user than that at
the time the module was created.

Examples
A. Refreshing a user-defined function
The following example refreshes a user-defined function. The example creates an alias data type, mytype , and a
user-defined function, to_upper , that uses mytype . Then, mytype is renamed to myoldtype , and a new mytype is
created that has a different definition. The dbo.to_upper function is refreshed so that it references the new
implementation of mytype , instead of the old one.
-- Create an alias type.
USE AdventureWorks2012;
GO
IF EXISTS (SELECT 'mytype' FROM sys.types WHERE name = 'mytype')
DROP TYPE mytype;
GO

CREATE TYPE mytype FROM nvarchar(5);


GO

IF OBJECT_ID ('dbo.to_upper', 'FN') IS NOT NULL


DROP FUNCTION dbo.to_upper;
GO

CREATE FUNCTION dbo.to_upper (@a mytype)


RETURNS mytype
WITH ENCRYPTION
AS
BEGIN
RETURN upper(@a)
END;
GO

SELECT dbo.to_upper('abcde');
GO

-- Increase the length of the alias type.


sp_rename 'mytype', 'myoldtype', 'userdatatype';
GO

CREATE TYPE mytype FROM nvarchar(10);


GO

-- The function parameter still uses the old type.


SELECT name, type_name(user_type_id)
FROM sys.parameters
WHERE object_id = OBJECT_ID('dbo.to_upper');
GO

SELECT dbo.to_upper('abcdefgh'); -- Fails because of truncation


GO

-- Refresh the function to bind to the renamed type.


EXEC sys.sp_refreshsqlmodule 'dbo.to_upper';

-- The function parameters are now bound to the correct type and the statement works correctly.
SELECT name, type_name(user_type_id) FROM sys.parameters
WHERE object_id = OBJECT_ID('dbo.to_upper');
GO

SELECT dbo.to_upper('abcdefgh');
GO

B. Refreshing a database -level DDL trigger


The following example refreshes a database-level DDL trigger.

USE AdventureWorks2012;
GO
EXEC sys.sp_refreshsqlmodule @name = 'ddlDatabaseTriggerLog' , @namespace = 'DATABASE_DDL_TRIGGER';
GO

C. Refreshing a server-level DDL trigger


The following example refreshes a server-level DDL trigger.
||
|-|
|Applies to: SQL Server 2008 through SQL Server 2017.|

USE master;
GO
EXEC sys.sp_refreshsqlmodule @name = 'ddl_trig_database' , @namespace = 'SERVER_DDL_TRIGGER';
GO

See Also
sp_refreshview (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
sp_refreshview (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates the metadata for the specified non-schema-bound view. Persistent metadata for a view can become
outdated because of changes to the underlying objects upon which the view depends.
Transact-SQL Syntax Conventions

Syntax
sp_refreshview [ @viewname = ] 'viewname'

Arguments
[ @viewname= ] 'viewname'
Is the name of the view. viewname is nvarchar, with no default. viewname can be a multipart identifier, but can
only refer to views in the current database.

Return Code Values


0 (success) or a nonzero number (failure)

Remarks
If a view is not created with schemabinding, sp_refreshview should be run when changes are made to the objects
underlying the view that affect the definition of the view. Otherwise, the view might produce unexpected results
when it is queried.

Permissions
Requires ALTER permission on the view and REFERENCES permission on common language runtime (CLR) user-
defined types and XML schema collections that are referenced by the view columns.

Examples
A. Updating the metadata of a view
The following example refreshes the metadata for the view Sales.vIndividualCustomer .

USE AdventureWorks2012;
GO
EXECUTE sp_refreshview N'Sales.vIndividualCustomer';

B. Creating a script that updates all views that have dependencies on a changed object
Assume that the table Person.Person was changed in a way that would affect the definition of any views that are
created on it. The following example creates a script that refreshes the metadata for all views that have a
dependency on table Person.Person .

USE AdventureWorks2012;
GO
SELECT DISTINCT 'EXEC sp_refreshview ''' + name + ''''
FROM sys.objects AS so
INNER JOIN sys.sql_expression_dependencies AS sed
ON so.object_id = sed.referencing_id
WHERE so.type = 'V' AND sed.referenced_id = OBJECT_ID('Person.Person');

See Also
Database Engine Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sys.sql_expression_dependencies (Transact-SQL)
sp_refreshsqlmodule (Transact-SQL)
sp_releaseapplock (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Releases a lock on an application resource.
Transact-SQL Syntax Conventions

Syntax
sp_releaseapplock [ @Resource = ] 'resource_name'
[ , [ @LockOwner = ] 'lock_owner' ]
[ , [ @DbPrincipal = ] 'database_principal' ]
[ ; ]

Arguments
[ @Resource= ] 'resource_name'
Is a lock resource name specified by the client application. The application must ensure that the resource is unique.
The specified name is hashed internally into a value that can be stored in the SQL Server lock manager.
resource_name is nvarchar(255) with no default. resource_name is binary compared, thus is case-sensitive
regardless of the collation settings of the current database.
[ @LockOwner= ] 'lock_owner'
Is the owner of the lock, which is the lock_owner value when the lock was requested. lock_owner is nvarchar(32).
The value can be Transaction (the default) or Session. When the lock_owner value is Transaction, by default or
specified explicitly, sp_getapplock must be executed from within a transaction.
[ @DbPrincipal= ] 'database_principal'
Is the user, role, or application role that has permissions to an object in a database. The caller of the function must
be a member of database_principal, dbo, or the db_owner fixed database role in order to call the function
successfully. The default is public.

Return Code Values


>= 0 (success), or < 0 (failure)

VALUE RESULT

0 Lock was successfully released.

-999 Indicates parameter validation or other call error.

Remarks
When an application calls sp_getapplock multiple times for the same lock resource, sp_releaseapplock must be
called the same number of times to release the lock.
When the server shuts down for any reason, the locks are released.

Permissions
Requires membership in the public role.

Examples
The following example releases the lock associated with the current transaction on the resource Form1 in the
AdventureWorks2012 database.

USE AdventureWorks2012;
GO
EXEC sp_getapplock @DbPrincipal = 'dbo', @Resource = 'Form1',
@LockMode = 'Shared';
EXEC sp_releaseapplock @DbPrincipal = 'dbo', @Resource = 'Form1';
GO

See Also
APPLOCK_MODE (Transact-SQL)
APPLOCK_TEST (Transact-SQL)
sp_getapplock (Transact-SQL)
sp_rename (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the name of a user-created object in the current database. This object can be a table, index, column, alias
data type, or Microsoft .NET Framework common language runtime (CLR) user-defined type.
Cau t i on

Changing any part of an object name can break scripts and stored procedures. We recommend you do not use this
statement to rename stored procedures, triggers, user-defined functions, or views; instead, drop the object and re-
create it with the new name.
Transact-SQL Syntax Conventions

Syntax
sp_rename [ @objname = ] 'object_name' , [ @newname = ] 'new_name'
[ , [ @objtype = ] 'object_type' ]

Arguments
[ @objname = ] 'object_name'
Is the current qualified or nonqualified name of the user object or data type. If the object to be renamed is a
column in a table, object_name must be in the form table.column or schema.table.column. If the object to be
renamed is an index, object_name must be in the form table.index or schema.table.index. If the object to be
renamed is a constraint, object_name must be in the form schema.constraint.
Quotation marks are only necessary if a qualified object is specified. If a fully qualified name, including a database
name, is provided, the database name must be the name of the current database. object_name is nvarchar(776),
with no default.
[ @newname = ] 'new_name'
Is the new name for the specified object. new_name must be a one-part name and must follow the rules for
identifiers. newname is sysname, with no default.

NOTE
Trigger names cannot start with # or ##.

[ @objtype = ] 'object_type'
Is the type of object being renamed. object_type is varchar(13), with a default of NULL, and can be one of these
values.

VALUE DESCRIPTION

COLUMN A column to be renamed.


VALUE DESCRIPTION

DATABASE A user-defined database. This object type is required when


renaming a database.

INDEX A user-defined index. Renaming an index with statistics, also


automatically renames the statistics.

OBJECT An item of a type tracked in sys.objects. For example, OBJECT


could be used to rename objects including constraints
(CHECK, FOREIGN KEY, PRIMARY/UNIQUE KEY), user tables,
and rules.

STATISTICS Applies to: SQL Server 2012 through SQL Server 2017 and
Azure SQL Database.

Statistics created explicitly by a user or created implicitly with


an index. Renaming the statistics of an index automatically
renames the index as well.

USERDATATYPE A CLR User-defined Types added by executing CREATE TYPE


or sp_addtype.

Return Code Values


0 (success) or a nonzero number (failure)

Remarks
You can change the name of an object or data type in the current database only. The names of most system data
types and system objects cannot be changed.
sp_rename automatically renames the associated index whenever a PRIMARY KEY or UNIQUE constraint is
renamed. If a renamed index is tied to a PRIMARY KEY constraint, the PRIMARY KEY constraint is also automatically
renamed by sp_rename.
sp_rename can be used to rename primary and secondary XML indexes.
Renaming a stored procedure, function, view, or trigger will not change the name of the corresponding object
name in the definition column of the sys.sql_modules catalog view. Therefore, we recommend that sp_rename not
be used to rename these object types. Instead, drop and re-create the object with its new name.
Renaming an object such as a table or column will not automatically rename references to that object. You must
modify any objects that reference the renamed object manually. For example, if you rename a table column and
that column is referenced in a trigger, you must modify the trigger to reflect the new column name.
Usesys.sql_expression_dependencies to list dependencies on the object before renaming it.

Permissions
To rename objects, columns, and indexes, requires ALTER permission on the object. To rename user types, requires
CONTROL permission on the type. To rename a database, requires membership in the sysadmin or dbcreator fixed
server roles

Examples
A. Renaming a table
The following example renames the SalesTerritory table to SalesTerr in the Sales schema.

USE AdventureWorks2012;
GO
EXEC sp_rename 'Sales.SalesTerritory', 'SalesTerr';
GO

B. Renaming a column
The following example renames the TerritoryID column in the SalesTerritory table to TerrID .

USE AdventureWorks2012;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO

C. Renaming an index
The following example renames the IX_ProductVendor_VendorID index to IX_VendorID .

USE AdventureWorks2012;
GO
EXEC sp_rename N'Purchasing.ProductVendor.IX_ProductVendor_VendorID', N'IX_VendorID', N'INDEX';
GO

D. Renaming an alias data type


The following example renames the Phone alias data type to Telephone .

USE AdventureWorks2012;
GO
EXEC sp_rename N'Phone', N'Telephone', N'USERDATATYPE';
GO

E. Renaming constraints
The following examples rename a PRIMARY KEY constraint, a CHECK constraint and a FOREIGN KEY constraint.
When renaming a constraint, the schema to which the constraint belongs must be specified.
USE AdventureWorks2012;
GO
-- Return the current Primary Key, Foreign Key and Check constraints for the Employee table.
SELECT name, SCHEMA_NAME(schema_id) AS schema_name, type_desc
FROM sys.objects
WHERE parent_object_id = (OBJECT_ID('HumanResources.Employee'))
AND type IN ('C','F', 'PK');
GO

-- Rename the primary key constraint.


sp_rename 'HumanResources.PK_Employee_BusinessEntityID', 'PK_EmployeeID';
GO

-- Rename a check constraint.


sp_rename 'HumanResources.CK_Employee_BirthDate', 'CK_BirthDate';
GO

-- Rename a foreign key constraint.


sp_rename 'HumanResources.FK_Employee_Person_BusinessEntityID', 'FK_EmployeeID';

-- Return the current Primary Key, Foreign Key and Check constraints for the Employee table.
SELECT name, SCHEMA_NAME(schema_id) AS schema_name, type_desc
FROM sys.objects
WHERE parent_object_id = (OBJECT_ID('HumanResources.Employee'))
AND type IN ('C','F', 'PK');

name schema_name type_desc


------------------------------------- ------------------ ----------------------
FK_Employee_Person_BusinessEntityID HumanResources FOREIGN_KEY_CONSTRAINT
PK_Employee_BusinessEntityID HumanResources PRIMARY_KEY_CONSTRAINT
CK_Employee_BirthDate HumanResources CHECK_CONSTRAINT
CK_Employee_MaritalStatus HumanResources CHECK_CONSTRAINT
CK_Employee_HireDate HumanResources CHECK_CONSTRAINT
CK_Employee_Gender HumanResources CHECK_CONSTRAINT
CK_Employee_VacationHours HumanResources CHECK_CONSTRAINT
CK_Employee_SickLeaveHours HumanResources CHECK_CONSTRAINT

(7 row(s) affected)

name schema_name type_desc


------------------------------------- ------------------ ----------------------
FK_Employee_ID HumanResources FOREIGN_KEY_CONSTRAINT
PK_Employee_ID HumanResources PRIMARY_KEY_CONSTRAINT
CK_BirthDate HumanResources CHECK_CONSTRAINT
CK_Employee_MaritalStatus HumanResources CHECK_CONSTRAINT
CK_Employee_HireDate HumanResources CHECK_CONSTRAINT
CK_Employee_Gender HumanResources CHECK_CONSTRAINT
CK_Employee_VacationHours HumanResources CHECK_CONSTRAINT
CK_Employee_SickLeaveHours HumanResources CHECK_CONSTRAINT

(7 row(s) affected)

F. Renaming statistics
The following example creates a statistics object named contactMail1 and then renames the statistic to
NewContact by using sp_rename. When renaming statistics, the object must be specified in the format
schema.table.statistics_name.
CREATE STATISTICS ContactMail1
ON Person.Person (BusinessEntityID, EmailPromotion)
WITH SAMPLE 5 PERCENT;

sp_rename 'Person.Person.ContactMail1', 'NewContact','Statistics';

See Also
sys.sql_expression_dependencies (Transact-SQL)
sys.sql_modules (Transact-SQL)
System Stored Procedures (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
sp_renamedb (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the name of a database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER DATABASE MODIFY NAME instead. For more
information, see ALTER DATABASE (Transact-SQL).

Transact-SQL Syntax Conventions

Syntax
sp_renamedb [ @dbname = ] 'old_name' , [ @newname = ] 'new_name'

Arguments
[ @dbname=] 'old_name'
Is the current name of the database. old_name is sysname, with no default.
[ @newname=] 'new_name'
Is the new name of the database. new_name must follow the rules for identifiers. new_name is sysname, with no
default.

Return Code Values


0 (success) or a nonzero number (failure)

Permissions
Requires membership in the sysadmin or dbcreator fixed server roles.

Examples
The following example creates the Accounting database and then changes the name of the database to Financial .
The sys.databases catalog view is then queried to verify the new name of the database.
USE master;
GO
CREATE DATABASE Accounting;
GO
EXEC sp_renamedb N'Accounting', N'Financial';
GO
SELECT name, database_id, modified_date
FROM sys.databases
WHERE name = N'Financial';
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
ALTER DATABASE (Transact-SQL)
sp_changedbowner (Transact-SQL)
sp_helpdb (Transact-SQL)
sys.databases (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_resetstatus (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Resets the status of a suspect database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER DATABASE instead.

Transact-SQL Syntax Conventions

Syntax
sp_resetstatus [ @dbname = ] 'database'

Arguments
[ @dbname= ] 'database'
Is the name of the database to reset. database is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_resetstatus turns off the suspect flag on a database. This procedure updates the mode and status columns of the
named database in sys.databases. The SQL Server error log should be consulted and all problems resolved before
running this procedure. Stop and restart the instance of SQL Server after you execute sp_resetstatus.
A database can become suspect for several reasons. Possible causes include denial of access to a database resource
by the operating system, and the unavailability or corruption of one or more database files.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example resets the status of the AdventureWorks2012 database.

EXEC sp_resetstatus 'AdventureWorks2012';


See Also
System Stored Procedures (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
sp_rxPredict
1/8/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Generates a predicted value based on a stored model.
Provides scoring on machine learning models in near real-time. sp_rxPredict is a stored procedure provided as a
wrapper for the rxPredict function in RevoScaleR and MicrosoftML. It is written in C+ and is optimized specifically
for scoring operations. It supports both R or Python machine learning models.
This topic applies to:
SQL Server 2017
SQL Server 2016 R Services with upgrade to Microsoft R Server

Syntax
sp_rxPredict ( @model, @input )

Arguments
model
A pretrained model in a supported format.
input
A valid SQL query
Return values
A score column is returned, as well as any pass-through columns from the input data source. Additional score
columns, such as confidence interval, can be returned if the algorithm supports generation of such values.

Remarks
To enable use of the stored procedure, SQLCLR must be enabled on the instance.

NOTE
Consider the security implications before you enable this option.

The user needs EXECUTE permission on the database.


Supported platforms
Requires one of the following editions:
SQL Server 2017 Machine Learning Services (includes Microsoft R Server 9.1.0)
Microsoft Machine Learning Server
SQL Server R Services 2016, with an upgrade of the R Services instance to Microsoft R Server 9.1.0 or later
Supported algorithms
For a list of supported algorithms, see Real-time scoring.
The following model types are not supported:
Models containing other, unsupported types of R transformations
Models using the rxGlm or rxNaiveBayes algorithms in RevoScaleR
PMML models
Models created using other R libraries from CRAN or other repositories
Models containing any other kind of R transformation other than those listed here

Examples
DECLARE @model = SELECT @model
FROM model_table
WHERE model_name = 'rxLogit trained';

EXEC sp_rxPredict @model = @model,


@inputData = N'SELECT * FROM data';

In addition to being a valid SQL query, the input data in @inputData must include columns compatible with the
columns in the stored model.
sp_rxPredictsupports only the following .NET column types: double, float, short, ushort, long, ulong and string.
You may need to filter out unsupported types in your input data before using it for real-time scoring.
For information about corresponding SQL types, see SQL-CLR Type Mapping or Mapping CLR Parameter Data.
sp_sequence_get_range (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a range of sequence values from a sequence object. The sequence object generates and issues the number
of values requested and provides the application with metadata related to the range.
For a more information about sequence numbers, see Sequence Numbers.
Transact-SQL Syntax Conventions

Syntax
sp_sequence_get_range [ @sequence_name = ] N'<sequence>'
, [ @range_size = ] range_size
, [ @range_first_value = ] range_first_value OUTPUT
[, [ @range_last_value = ] range_last_value OUTPUT ]
[, [ @range_cycle_count = ] range_cycle_count OUTPUT ]
[, [ @sequence_increment = ] sequence_increment OUTPUT ]
[, [ @sequence_min_value = ] sequence_min_value OUTPUT ]
[, [ @sequence_max_value = ] sequence_max_value OUTPUT ]
[ ; ]

Arguments
[ @sequence_name = ] N'sequence'
The name of the sequence object. The schema is optional. sequence_name is nvarchar(776).
[ @range_size = ] range_size
The number of values to fetch from the sequence. @range_size is bigint.
[ @range_first_value = ] range_first_value
Output parameter returns the first (minimum or maximum) value of the sequence object used to calculate the
requested range. @range_first_value is sql_variant with the same base type as that of the sequence object used
in the request.
[ @range_last_value = ] range_last_value
Optional output parameter returns the last value of the requested range. @range_last_value is sql_variant with
the same base type as that of the sequence object used in the request.
[ @range_cycle_count = ] range_cycle_count
Optional output parameter returns the number of times that the sequence object cycled in order to return the
requested range. @range_cycle_count is int.
[ @sequence_increment = ] sequence_increment
Optional output parameter returns the increment of the sequence object used to calculate the requested range.
@sequence_increment is sql_variant with the same base type as that of the sequence object used in the request.
[ @sequence_min_value = ] sequence_min_value
Optional output parameter returns the minimum value of the sequence object. @sequence_min_value is
sql_variant with the same base type as that of the sequence object used in the request.
[ @sequence_max_value = ] sequence_max_value
Optional output parameter returns the maximum value of the sequence object. @sequence_max_value is
sql_variant with the same base type as that of the sequence object used in the request.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_sequence_get_rangeis in the sys. schema and can be referenced as sys.sp_sequence_get_range.
Cycling sequences
If required, the sequence object will cycle the appropriate number of times to service the requested range. The
number of times cycled is returned to the caller through the @range_cycle_count parameter.

NOTE
When cycling, a sequence object restarts from the minimum value for an ascending sequence and the maximum value for a
descending sequence, not from the start value of the sequence object.

Non-cycling sequences
If the number of values in the requested range is greater than the remaining available values in the sequence
object the requested range is not deducted from the sequence object and the following error 11732 is returned:
The requested range for sequence object '%.*ls' exceeds the maximum or minimum limit. Retry with a smaller
range.

Permissions
Requires UPDATE permission on the sequence object or the schema of the sequence object.

Examples
The following examples use a sequence object named Test.RangeSeq. Use the following statement to create the
Test.RangeSeq sequence.

CREATE SCHEMA Test ;


GO

CREATE SEQUENCE Test.RangeSeq


AS int
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 25
CYCLE
CACHE 10
;

A. Retrieving a range of sequence values


The following statement gets four sequence numbers from the Test.RangeSeq sequence object and returns the first
of the numbers to the user.
DECLARE @range_first_value sql_variant ,
@range_first_value_output sql_variant ;

EXEC sp_sequence_get_range
@sequence_name = N'Test.RangeSeq'
, @range_size = 4
, @range_first_value = @range_first_value_output OUTPUT ;

SELECT @range_first_value_output AS FirstNumber ;

B. Returning all output parameters


The following example returns all the output values from the sp_sequence_get_range procedure.

DECLARE
@FirstSeqNum sql_variant
, @LastSeqNum sql_variant
, @CycleCount int
, @SeqIncr sql_variant
, @SeqMinVal sql_variant
, @SeqMaxVal sql_variant ;

EXEC sys.sp_sequence_get_range
@sequence_name = N'Test.RangeSeq'
, @range_size = 5
, @range_first_value = @FirstSeqNum OUTPUT
, @range_last_value = @LastSeqNum OUTPUT
, @range_cycle_count = @CycleCount OUTPUT
, @sequence_increment = @SeqIncr OUTPUT
, @sequence_min_value = @SeqMinVal OUTPUT
, @sequence_max_value = @SeqMaxVal OUTPUT ;

-- The following statement returns the output values


SELECT
@FirstSeqNum AS FirstVal
, @LastSeqNum AS LastVal
, @CycleCount AS CycleCount
, @SeqIncr AS SeqIncrement
, @SeqMinVal AS MinSeq
, @SeqMaxVal AS MaxSeq ;

Changing the @range_size argument to a large number such as 75 will cause the sequence object to cycle. Check
the @range_cycle_count argument to determine if and how many times the sequence object has cycled.
C. Example using ADO.NET
The following example gets a range from the Test.RangeSeq by using ADO.NET.
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sys.sp_sequence_get_range";
cmd.Parameters.AddWithValue("@sequence_name", "Test.RangeSeq");
cmd.Parameters.AddWithValue("@range_size", 10);

// Specify an output parameter to retreive the first value of the generated range.
SqlParameter firstValueInRange = new SqlParameter("@range_first_value", SqlDbType.Variant);
firstValueInRange.Direction = ParameterDirection.Output;
cmd.Parameters.Add(firstValueInRange);

conn.Open();
cmd.ExecuteNonQuery();

// Output the first value of the generated range.


Console.WriteLine(firstValueInRange.Value);

See Also
CREATE SEQUENCE (Transact-SQL)
ALTER SEQUENCE (Transact-SQL)
DROP SEQUENCE (Transact-SQL)
NEXT VALUE FOR (Transact-SQL)
Sequence Numbers
sp_server_diagnostics (Transact-SQL)
1/2/2018 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Captures diagnostic data and health information about SQL Server to detect potential failures. The procedure runs
in repeat mode and sends results periodically. It can be invoked from either a regular or a DAC connection.
Applies to: SQL Server ( SQL Server 2012 through SQL Server 2017).
Transact-SQL Syntax Conventions

Syntax
sp_server_diagnostics [@repeat_interval =] 'repeat_interval_in_seconds'

Arguments
[ @repeat_interval =] 'repeat_interval_in_seconds'
Indicates the time interval at which the stored procedure will run repeatedly to send health information.
repeat_interval_in_seconds is int with the default of 0. The valid parameter values are 0, or any value equal to or
more than 5. The stored procedure has to run at least 5 seconds to return complete data. The minimum value for
the stored procedure to run in the repeat mode is 5 seconds.
If this parameter is not specified, or if the specified value is 0, the stored procedure will return data one time and
then exit.
If the specified value is less than the minimum value, it will raise an error and return nothing.
If the specified value is equal to or more than 5, the stored procedure runs repeatedly to return the health state
until it is manually canceled.

Return Code Values


0 (success) or 1 (failure)

Result Sets
sp_server_diagnostics returns the following information

COLUMN DATA TYPE DESCRIPTION

creation_time datetime Indicates the time stamp of row


creation. Each row in a single rowset has
the same time stamp.
COLUMN DATA TYPE DESCRIPTION

component_type sysname Indicates whether the row contains


information for the SQL Server instance
level component or for an Always On
availability group:

instance

Always On:AvailabilityGroup

component_name sysname Indicates the name of component or


the name of the availability group:

system

resource

query_processing

io_subsystem

events

<name of the availability group>

state int Indicates the health status of the


component:

state_desc sysname Describes the state column.


Descriptions that correspond to the
values in the state column are:

0: Unknown

1: clean

2: warning

3: error

data varchar (max) Specifies data that is specific to the


component.

Here are the descriptions of the five components:


system: Collects data from a system perspective on spinlocks, severe processing conditions, non-yielding
tasks, page faults, and CPU usage. This information is produces an overall health state recommendation.
resource: Collects data from a resource perspective on physical and virtual memory, buffer pools, pages,
cache and other memory objects. This information produces an overall health state recommendation.
query_processing: Collects data from a query-processing perspective on the worker threads, tasks, wait
types, CPU intensive sessions, and blocking tasks. This information produces an overall health state
recommendation.
io_subsystem: Collects data on IO. In addition to diagnostic data, this component produces a clean healthy
or warning health state only for an IO subsystem.
events: Collects data and surfaces through the stored procedure on the errors and events of interest
recorded by the server, including details about ring buffer exceptions, ring buffer events about memory
broker, out of memory, scheduler monitor, buffer pool, spinlocks, security, and connectivity . Events will
always show 0 as the state.
<name of the availability group>: Collects data for the specified availability group (if component_type =
"Always On:AvailabilityGroup").

Remarks
From a failure perspective, the system, resource, and query_processing components will be leveraged for failure
detection while the io_subsystem and events components will be leveraged for diagnostic purposes only.
The following table maps the components to their associated health states.

COMPONENTS CLEAN (1) WARNING (2) ERROR (3) UNKNOWNS (0)

system x x x

resource x x x

query_processing x x x

io_subsystem x x

events x

The (x) in each row represents valid health states for the component. For example, io_subsystem will either show as
clean or warning. It will not show the error states.

NOTE
Execution of sp_server_diagnostics internal procedure is implemented on a preemptive thread at high priority.

Permissions
Requires VIEW SERVER STATE permission on the server.

Examples
It is best practice to use the extended sessions to capture the health information and save it to a file that is located
outside of SQL Server. Therefore, you can still access it if there is a failure. The following example saves the output
from an event session to a file:
CREATE EVENT SESSION [diag]
ON SERVER
ADD EVENT [sp_server_diagnostics_component_result] (set collect_data=1)
ADD TARGET [asynchronous_file_target] (set filename='c:\temp\diag.xel');
GO
ALTER EVENT SESSION [diag]
ON SERVER STATE = start;
GO

The example query below reads the extended session log file:

SELECT
xml_data.value('(/event/@name)[1]','varchar(max)') AS Name
, xml_data.value('(/event/@package)[1]', 'varchar(max)') AS Package
, xml_data.value('(/event/@timestamp)[1]', 'datetime') AS 'Time'
, xml_data.value('(/event/data[@name=''component_type'']/value)[1]','sysname') AS Sysname
, xml_data.value('(/event/data[@name=''component_name'']/value)[1]','sysname') AS Component
, xml_data.value('(/event/data[@name=''state'']/value)[1]','int') AS State
, xml_data.value('(/event/data[@name=''state_desc'']/value)[1]','sysname') AS State_desc
, xml_data.query('(/event/data[@name="data"]/value/*)') AS Data
FROM
(
SELECT
object_name as event
,CONVERT(xml, event_data) as xml_data
FROM
sys.fn_xe_file_target_read_file('C:\Program Files\Microsoft SQL
Server\MSSQL13.MSSQLSERVER\MSSQL\Log\*.xel', NULL, NULL, NULL)
)
AS XEventData
ORDER BY time;

The following example captures the output of sp_server_diagnostics to a table in a non-repeat mode:

CREATE TABLE SpServerDiagnosticsResult


(
create_time DateTime,
component_type sysname,
component_name sysname,
state int,
state_desc sysname,
data xml
);
INSERT INTO SpServerDiagnosticsResult
EXEC sp_server_diagnostics;

The example query below reads the summary output from the table:

SELECT create_time,
component_name,
state_desc
FROM SpServerDiagnosticsResult;

The example query below reads some of the detailed output from the each component in the table:

-- system
select data.value('(/system/@systemCpuUtilization)[1]','bigint') as 'System_CPU',
data.value('(/system/@sqlCpuUtilization)[1]','bigint') as 'SQL_CPU',
data.value('(/system/@nonYieldingTasksReported)[1]','bigint') as 'NonYielding_Tasks',
data.value('(/system/@pageFaults)[1]','bigint') as 'Page_Faults',
data.value('(/system/@latchWarnings)[1]','bigint') as 'Latch_Warnings',
data.value('(/system/@latchWarnings)[1]','bigint') as 'Latch_Warnings',
data.value('(/system/@BadPagesDetected)[1]','bigint') as 'BadPages_Detected',
data.value('(/system/@BadPagesFixed)[1]','bigint') as 'BadPages_Fixed'
from SpServerDiagnosticsResult
where component_name like 'system'
go

-- Resource Monitor
select data.value('(./Record/ResourceMonitor/Notification)[1]', 'VARCHAR(max)') AS [Notification],
data.value('(/resource/memoryReport/entry[@description=''Working Set'']/@value)[1]', 'bigint')/1024 AS
[SQL_Mem_in_use_MB],
data.value('(/resource/memoryReport/entry[@description=''Available Paging File'']/@value)[1]',
'bigint')/1024 AS [Avail_Pagefile_MB],
data.value('(/resource/memoryReport/entry[@description=''Available Physical Memory'']/@value)[1]',
'bigint')/1024 AS [Avail_Physical_Mem_MB],
data.value('(/resource/memoryReport/entry[@description=''Available Virtual Memory'']/@value)[1]',
'bigint')/1024 AS [Avail_VAS_MB],
data.value('(/resource/@lastNotification)[1]','varchar(100)') as 'LastNotification',
data.value('(/resource/@outOfMemoryExceptions)[1]','bigint') as 'OOM_Exceptions'
from SpServerDiagnosticsResult
where component_name like 'resource'
go

-- Nonpreemptive waits
select waits.evt.value('(@waitType)','varchar(100)') as 'Wait_Type',
waits.evt.value('(@waits)','bigint') as 'Waits',
waits.evt.value('(@averageWaitTime)','bigint') as 'Avg_Wait_Time',
waits.evt.value('(@maxWaitTime)','bigint') as 'Max_Wait_Time'
from SpServerDiagnosticsResult
CROSS APPLY data.nodes('/queryProcessing/topWaits/nonPreemptive/byDuration/wait') AS waits(evt)
where component_name like 'query_processing'
go

-- Preemptive waits
select waits.evt.value('(@waitType)','varchar(100)') as 'Wait_Type',
waits.evt.value('(@waits)','bigint') as 'Waits',
waits.evt.value('(@averageWaitTime)','bigint') as 'Avg_Wait_Time',
waits.evt.value('(@maxWaitTime)','bigint') as 'Max_Wait_Time'
from SpServerDiagnosticsResult
CROSS APPLY data.nodes('/queryProcessing/topWaits/preemptive/byDuration/wait') AS waits(evt)
where component_name like 'query_processing'
go

-- CPU intensive requests


select cpureq.evt.value('(@sessionId)','bigint') as 'SessionID',
cpureq.evt.value('(@command)','varchar(100)') as 'Command',
cpureq.evt.value('(@cpuUtilization)','bigint') as 'CPU_Utilization',
cpureq.evt.value('(@cpuTimeMs)','bigint') as 'CPU_Time_ms'
from SpServerDiagnosticsResult
CROSS APPLY data.nodes('/queryProcessing/cpuIntensiveRequests/request') AS cpureq(evt)
where component_name like 'query_processing'
go

-- Blocked Process Report


select blk.evt.query('.') as 'Blocked_Process_Report_XML'
from SpServerDiagnosticsResult
CROSS APPLY data.nodes('/queryProcessing/blockingTasks/blocked-process-report') AS blk(evt)
where component_name like 'query_processing'
go

-- IO
select data.value('(/ioSubsystem/@ioLatchTimeouts)[1]','bigint') as 'Latch_Timeouts',
data.value('(/ioSubsystem/@totalLongIos)[1]','bigint') as 'Total_Long_IOs'
from SpServerDiagnosticsResult
where component_name like 'io_subsystem'
go

-- Event information
select xevts.evt.value('(@name)','varchar(100)') as 'xEvent_Name',
xevts.evt.value('(@package)','varchar(100)') as 'Package',
xevts.evt.value('(@package)','varchar(100)') as 'Package',
xevts.evt.value('(@timestamp)','datetime') as 'xEvent_Time',
xevts.evt.query('.') as 'Event Data'
from SpServerDiagnosticsResult
CROSS APPLY data.nodes('/events/session/RingBufferTarget/event') AS xevts(evt)
where component_name like 'events'
go

See Also
Failover Policy for Failover Cluster Instances
sp_set_session_context (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sets a key-value pair in the session context.
Transact-SQL Syntax Conventions

Syntax
sp_set_session_context [ @key= ] 'key', [ @value= ] 'value'
[ , [ @read_only = ] { 0 | 1 } ]
[ ; ]

Arguments
[ @key= ] 'key'
The key being set, of type sysname. The maximum key size is 128 bytes.
[ @value= ] 'value'
The value for the specified key, of type sql_variant. Setting a value of NULL frees the memory. The maximum size
is 8,000 bytes.
[ @read_only= ] { 0 | 1 }
A flag of type bit. If 1, then the value for the specified key cannot be changed again on this logical connection. If 0
(default), then the value can be changed.

Permissions
Any user can set a session context for their session.

Remarks
Like other stored procedures, only literals and variables (not expressions or function calls) can be passed as
parameters.
The total size of the session context is limited to 256 kb. If set a value that causes this limit to be exceeded, the
statement fails. You can monitor overall memory usage in sys.dm_os_memory_objects (Transact-SQL).
You can monitor overall memory usage by querying sys.dm_os_memory_cache_counters (Transact-SQL) as
follows: SELECT * FROM sys.dm_os_memory_cache_counters WHERE type = 'CACHESTORE_SESSION_CONTEXT';

Examples
The following example shows how to set and then return a sessions context key named language with a value of
English.

EXEC sp_set_session_context 'language', 'English';


SELECT SESSION_CONTEXT(N'language');
The following example demonstrates the use of the optional read-only flag.

EXEC sp_set_session_context 'user_id', 4, @read_only = 1;

See Also
CURRENT_TRANSACTION_ID (Transact-SQL)
SESSION_CONTEXT (Transact-SQL)
Row-Level Security
CONTEXT_INFO (Transact-SQL)
SET CONTEXT_INFO (Transact-SQL)
sp_setnetname (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Sets the network names in sys.servers to their actual network computer names for remote instances of SQL
Server. This procedure can be used to enable execution of remote stored procedure calls to computers that have
network names containing SQL Server identifiers that are not valid.
Transact-SQL Syntax Conventions

Syntax
sp_setnetname
@server = 'server',
@netname = 'network_name'

Arguments
@server = ' server '
Is the name of the remote server as referenced in user-coded remote stored procedure call syntax. Exactly one row
in sys.servers must already exist to use this server. server is sysname, with no default.
@netname =' network_name '
Is the network name of the computer to which remote stored procedure calls are made. network_name is
sysname, with no default.
This name must match the Microsoft Windows computer name, and the name can include characters that are not
allowed in SQL Server identifiers.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Some remote stored procedure calls to Windows computers can encounter problems if the computer name
contains identifiers that are not valid.
Because linked servers and remote servers reside in the same namespace, they cannot have the same name.
However, you can define both a linked server and a remote server against a specified server by assigning different
names and by using sp_setnetname to set the network name of one of them to the network name of the
underlying server.
--Assume sqlserv2 is actual name of SQL Server
--database server
EXEC sp_addlinkedserver 'sqlserv2';
GO
EXEC sp_addserver 'rpcserv2';
GO
EXEC sp_setnetname 'rpcserv2', 'sqlserv2';

NOTE
Using sp_setnetname to point a linked server back to the local server is not supported. Servers that are referenced in this
manner cannot participate in a distributed transaction.

Permissions
Requires membership in the sysadmin and setupadmin fixed server roles.

Examples
The following example shows a typical administrative sequence used on SQL Server to issue the remote stored
procedure call.

USE master;
GO
EXEC sp_addserver 'Win_1';
EXEC sp_setnetname 'Win_1','Win-1';
EXEC Win_1.master.dbo.sp_who;

See Also
Database Engine Stored Procedures (Transact-SQL)
sp_addlinkedserver (Transact-SQL)
sp_addserver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_settriggerorder (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Specifies the AFTER triggers that are fired first or last. The AFTER triggers that are fired between the first and last
triggers are executed in undefined order.
Transact-SQL Syntax Conventions

Syntax
sp_settriggerorder [ @triggername = ] '[ triggerschema. ] triggername'
, [ @order = ] 'value'
, [ @stmttype = ] 'statement_type'
[ , [ @namespace = ] { 'DATABASE' | 'SERVER' | NULL } ]

Arguments
[ @triggername= ] '[ triggerschema.] triggername'
Is the name of the trigger and the schema to which it belongs, if applicable, whose order is to be set or changed.
[triggerschema.]triggername is sysname. If the name does not correspond to a trigger or if the name corresponds
to an INSTEAD OF trigger, the procedure returns an error. triggerschema cannot be specified for DDL or logon
triggers.
[ @order= ] 'value'
Is the setting for the new order of the trigger. value is varchar(10) and it can be any one of the following values.

IMPORTANT
The First and Last triggers must be two different triggers.

VALUE DESCRIPTION

First Trigger is fired first.

Last Trigger is fired last.

None Trigger is fired in undefined order.

[ @stmttype= ] 'statement_type'
Specifies the SQL statement that fires the trigger. statement_type is varchar(50) and can be INSERT, UPDATE,
DELETE, LOGON, or any Transact-SQL statement event listed in DDL Events. Event groups cannot be specified.
A trigger can be designated as the First or Last trigger for a statement type only after that trigger has been defined
as a trigger for that statement type. For example, trigger TR1 can be designated First for INSERT on table T1 if TR1
is defined as an INSERT trigger. The Database Engine returns an error if TR1, which has been defined only as an
INSERT trigger, is set as a First, or Last, trigger for an UPDATE statement. For more information, see the Remarks
section.
@namespace= { 'DATABASE' | 'SERVER' | NULL }
When triggername is a DDL trigger, @namespace specifies whether triggername was created with database
scope or server scope. If triggername is a logon trigger, SERVER must be specified. For more information about
DDL trigger scope, see DDL Triggers. If not specified, or if NULL is specified, triggername is a DML trigger.
||
|-|
|SERVER applies to: SQL Server 2008 through SQL Server 2017.|

Return Code Values


0 (success) and 1 (failure)

Remarks
DML Triggers
There can be only one First and one Last trigger for each statement on a single table.
If a First trigger is already defined on the table, database, or server, you cannot designate a new trigger as First for
the same table, database, or server for the same statement_type. This restriction also applies Last triggers.
Replication automatically generates a first trigger for any table that is included in an immediate updating or
queued updating subscription. Replication requires that its trigger be the first trigger. Replication raises an error
when you try to include a table with a first trigger in an immediate updating or queued updating subscription. If
you try to make a trigger a first trigger after a table has been included in a subscription, sp_settriggerorder
returns an error. If you use ALTER TRIGGER on the replication trigger, or use sp_settriggerorder to change the
replication trigger to a Last or None trigger, the subscription does not function correctly.

DDL Triggers
If a DDL trigger with database scope and a DDL trigger with server scope exist on the same event, you can specify
that both triggers be a First trigger or a Last trigger. However, server-scoped triggers always fire first. In general,
the order of execution of DDL triggers that exist on the same event is as follows:
1. The server-level trigger marked First.
2. Other server-level triggers.
3. The server-level trigger marked Last.
4. The database-level trigger marked First.
5. Other database-level triggers.
6. The database-level trigger marked Last.

General Trigger Considerations


If an ALTER TRIGGER statement changes a first or last trigger, the First or Last attribute originally set on the trigger
is dropped, and the value is replaced by None. The order value must be reset by using sp_settriggerorder.
If the same trigger must be designated as the first or last order for more than one statement type,
sp_settriggerorder must be executed for each statement type. Also, the trigger must be first defined for a
statement type before it can be designated as the First or Last trigger to fire for that statement type.
Permissions
To set the order of a DDL trigger with server scope (created ON ALL SERVER) or a logon trigger requires CONTROL
SERVER permission.
To set the order of a DDL trigger with database scope (created ON DATABASE) requires ALTER ANY DATABASE
DDL TRIGGER permission.
To set the order of a DML trigger requires ALTER permission on the table or view on which the trigger is defined.

Examples
A. Setting the firing order for a DML trigger
The following example specifies that trigger uSalesOrderHeader be the first trigger to fire after an UPDATE
operation occurs on the Sales.SalesOrderHeader table.

USE AdventureWorks2012;
GO
sp_settriggerorder @triggername= 'Sales.uSalesOrderHeader', @order='First', @stmttype = 'UPDATE';

B. Setting the firing order for a DDL trigger


The following example specifies that trigger ddlDatabaseTriggerLog be the first trigger to fire after an ALTER_TABLE
event occurs in the AdventureWorks2012 database.

USE AdventureWorks2012;
GO
sp_settriggerorder @triggername= 'ddlDatabaseTriggerLog', @order='First', @stmttype = 'ALTER_TABLE',
@namespace = 'DATABASE';

See Also
System Stored Procedures (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
ALTER TRIGGER (Transact-SQL)
sp_spaceused (Transact-SQL)
11/21/2017 • 10 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Displays the number of rows, disk space reserved, and disk space used by a table, indexed view, or Service Broker
queue in the current database, or displays the disk space reserved and used by the whole database.
Transact-SQL Syntax Conventions

Syntax
sp_spaceused [[ @objname = ] 'objname' ]
[, [ @updateusage = ] 'updateusage' ]
[, [ @mode = ] 'mode' ]
[, [ @oneresultset = ] oneresultset ]
[, [ @include_total_xtp_storage = ] include_total_xtp_storage ]

Arguments
For SQL Data Warehouse, sp_spacedused must specify named parameters (for example
sp_spacedused (@objname= N'Table1'); rather than relying upon the ordinal position of parameters.
[ @objname=] 'objname'
Is the qualified or nonqualified name of the table, indexed view, or queue for which space usage information is
requested. Quotation marks are required only if a qualified object name is specified. If a fully qualified object name
(including a database name) is provided, the database name must be the name of the current database.
If objname is not specified, results are returned for the whole database.
objname is nvarchar(776), with a default of NULL.

NOTE
SQL Data Warehouse and Parallel Data Warehouse only support database and table objects.

[ @updateusage=] 'updateusage'
Indicates DBCC UPDATEUSAGE should be run to update space usage information. When objname is not specified,
the statement is run on the whole database; otherwise, the statement is run on objname. Values can be true or
false. updateusage is varchar(5), with a default of false.
[ @mode=] 'mode'
Indicates the scope of the results. For a stretched table or database, the mode parameter lets you include or exclude
the remote portion of the object. For more info, see Stretch Database.
The mode argument can have the following values:

VALUE DESCRIPTION

ALL Returns the storage statistics of the object or database


including both the local portion and the remote portion.
VALUE DESCRIPTION

LOCAL_ONLY Returns the storage statistics of only the local portion of the
object or database. If the object or database is not Stretch-
enabled, returns the same statistics as when @mode = ALL.

REMOTE_ONLY Returns the storage statistics of only the remote portion of


the object or database. This option raises an error when one
of the following conditions is true:

The table is not enabled for Stretch.

The table is enabled for Stretch, but you have never enabled
data migration. In this case, the remote table does not yet
have a schema.

The user has manually dropped the remote table.

The provisioning of the remote data archive returned a status


of Success, but in fact it failed.

mode is varchar(11), with a default of N'ALL'.


[ @oneresultset=] oneresultset
Indicates whether to return a single result set. The oneresultset argument can have the following values:

VALUE DESCRIPTION

0 When @objname is null or is not specified, two result sets are


returned. Two result sets is the default behavior.

1 When @objname = null or is not specified, a single result set


is returned.

oneresultset is bit, with a default of 0.


[ @include_total_xtp_storage] 'include_total_xtp_storage'
Applies to: SQL Server 2016, SQL Database.
When @oneresultset=1, the parameter @include_total_xtp_storage determines whether the single resultset
includes columns for MEMORY_OPTIMIZED_DATA storage. The default value is 0, that is, by default (if the
parameter is omitted) the XTP columns are not included in the resultset.

Return Code Values


0 (success) or 1 (failure)

Result Sets
If objname is omitted and the value of oneresultset is 0, the following result sets are returned to provide current
database size information.

COLUMN NAME DATA TYPE DESCRIPTION

database_name nvarchar(128) Name of the current database.


COLUMN NAME DATA TYPE DESCRIPTION

database_size varchar(18) Size of the current database in


megabytes. database_size includes
both data and log files.

unallocated space varchar(18) Space in the database that has not been
reserved for database objects.

COLUMN NAME DATA TYPE DESCRIPTION

reserved varchar(18) Total amount of space allocated by


objects in the database.

data varchar(18) Total amount of space used by data.

index_size varchar(18) Total amount of space used by indexes.

unused varchar(18) Total amount of space reserved for


objects in the database, but not yet
used.

If objname is omitted and the value of oneresultset is 1, the following single result set is returned to provide
current database size information.

COLUMN NAME DATA TYPE DESCRIPTION

database_name nvarchar(128) Name of the current database.

database_size varchar(18) Size of the current database in


megabytes. database_size includes
both data and log files.

unallocated space varchar(18) Space in the database that has not been
reserved for database objects.

reserved varchar(18) Total amount of space allocated by


objects in the database.

data varchar(18) Total amount of space used by data.

index_size varchar(18) Total amount of space used by indexes.

unused varchar(18) Total amount of space reserved for


objects in the database, but not yet
used.

If objname is specified, the following result set is returned for the specified object.

COLUMN NAME DATA TYPE DESCRIPTION


COLUMN NAME DATA TYPE DESCRIPTION

name nvarchar(128) Name of the object for which space


usage information was requested.

The schema name of the object is not


returned. If the schema name is
required, use the
sys.dm_db_partition_stats or
sys.dm_db_index_physical_stats dynamic
management views to obtain equivalent
size information.

rows char(20) Number of rows existing in the table. If


the object specified is a Service Broker
queue, this column indicates the
number of messages in the queue.

reserved varchar(18) Total amount of reserved space for


objname.

data varchar(18) Total amount of space used by data in


objname.

index_size varchar(18) Total amount of space used by indexes


in objname.

unused varchar(18) Total amount of space reserved for


objname but not yet used.

This is the default mode, when no parameters are specified. The following result sets are returned detailing on-disk
database size information.

COLUMN NAME DATA TYPE DESCRIPTION

database_name nvarchar(128) Name of the current database.

database_size varchar(18) Size of the current database in


megabytes. database_size includes
both data and log files. If the database
has a MEMORY_OPTIMIZED_DATA
filegroup, this includes the total on-disk
size of all checkpoint files in the
filegroup.

unallocated space varchar(18) Space in the database that has not been
reserved for database objects. If the
database has a
MEMORY_OPTIMIZED_DATA filegroup,
this includes the total on-disk size of
the checkpoint files with state
PRECREATED in the filegroup.

Space used by tables in the database: (this resultset does not reflect memory-optimized tables, as there is no per-
table accounting of disk usage)
COLUMN NAME DATA TYPE DESCRIPTION

reserved varchar(18) Total amount of space allocated by


objects in the database.

data varchar(18) Total amount of space used by data.

index_size varchar(18) Total amount of space used by indexes.

unused varchar(18) Total amount of space reserved for


objects in the database, but not yet
used.

The following result set is returned ONLY IF the database has a MEMORY_OPTIMIZED_DATA filegroup with at least
one container:

COLUMN NAME DATA TYPE DESCRIPTION

xtp_precreated varchar(18) Total size of checkpoint files with state


PRECREATED, in KB. Counts towards the
unallocated space in the database as a
whole. [For example, if there is 600,000
KB of precreated checkpoint files, this
column contains '600000 KB']

xtp_used varchar(18) Total size of checkpoint files with states


UNDER CONSTRUCTION, ACTIVE, and
MERGE TARGET, in KB. This is the disk
space actively used for data in memory-
optimized tables.

xtp_pending_truncation varchar(18) Total size of checkpoint files with state


WAITING_FOR_LOG_TRUNCATION, in
KB. This is the disk space used for
checkpoint files that are awaiting
cleanup, once log truncation happens.

If objname is omitted, the value of oneresultset is 1, and include_total_xtp_storage is 1, the following single result
set is returned to provide current database size information. If include_total_xtp_storage is 0 (the default), the last
three columns are omitted.

COLUMN NAME DATA TYPE DESCRIPTION

database_name nvarchar(128) Name of the current database.

database_size varchar(18) Size of the current database in


megabytes. database_size includes
both data and log files. If the database
has a MEMORY_OPTIMIZED_DATA
filegroup, this includes the total on-disk
size of all checkpoint files in the
filegroup.
COLUMN NAME DATA TYPE DESCRIPTION

unallocated space varchar(18) Space in the database that has not been
reserved for database objects. If the
database has a
MEMORY_OPTIMIZED_DATA filegroup,
this includes the total on-disk size of
the checkpoint files with state
PRECREATED in the filegroup.

reserved varchar(18) Total amount of space allocated by


objects in the database.

data varchar(18) Total amount of space used by data.

index_size varchar(18) Total amount of space used by indexes.

unused varchar(18) Total amount of space reserved for


objects in the database, but not yet
used.

xtp_precreated varchar(18) Total size of checkpoint files with state


PRECREATED, in KB. This counts
towards the unallocated space in the
database as a whole. Returns NULL if
the database does not have a
memory_optimized_data filegroup with
at least one container. This column is
only included if
@include_total_xtp_storage=1.

xtp_used varchar(18) Total size of checkpoint files with states


UNDER CONSTRUCTION, ACTIVE, and
MERGE TARGET, in KB. This is the disk
space actively used for data in memory-
optimized tables. Returns NULL if the
database does not have a
memory_optimized_data filegroup with
at least one container. This column is
only included if
@include_total_xtp_storage=1.

xtp_pending_truncation varchar(18) Total size of checkpoint files with state


WAITING_FOR_LOG_TRUNCATION, in
KB. This is the disk space used for
checkpoint files that are awaiting
cleanup, once log truncation happens.
Returns NULL if the database does not
have a memory_optimized_data
filegroup with at least one container.
This column is only included if
@include_total_xtp_storage=1 .

Remarks
database_size is always larger than the sum of reserved + unallocated space because it includes the size of log
files, but reserved and unallocated_space consider only data pages.
Pages that are used by XML indexes and full-text indexes are included in index_size for both result sets. When
objname is specified, the pages for the XML indexes and full-text indexes for the object are also counted in the total
reserved and index_size results.
If space usage is calculated for a database or an object that has a spatial index, the space-size columns, such as
database_size, reserved, and index_size, include the size of the spatial index.
When updateusage is specified, the SQL Server Database Engine scans the data pages in the database and makes
any required corrections to the sys.allocation_units and sys.partitions catalog views regarding the storage space
used by each table. There are some situations, for example, after an index is dropped, when the space information
for the table may not be current. updateusage can take some time to run on large tables or databases. Use
updateusage only when you suspect incorrect values are being returned and when the process will not have an
adverse effect on other users or processes in the database. If preferred, DBCC UPDATEUSAGE can be run
separately.

NOTE
When you drop or rebuild large indexes, or drop or truncate large tables, the Database Engine defers the actual page
deallocations, and their associated locks, until after the transaction commits. Deferred drop operations do not release
allocated space immediately. Therefore, the values returned by sp_spaceused immediately after dropping or truncating a
large object may not reflect the actual disk space available.

Permissions
Permission to execute sp_spaceused is granted to the public role. Only members of the db_owner fixed database
role can specify the @updateusage parameter.

Examples
A. Displaying disk space information about a table
The following example reports disk space information for the Vendor table and its indexes.

USE AdventureWorks2012;
GO
EXEC sp_spaceused N'Purchasing.Vendor';
GO

B. Displaying updated space information about a database


The following example summarizes space used in the current database and uses the optional parameter
@updateusage to ensure current values are returned.

USE AdventureWorks008R2;
GO
EXEC sp_spaceused @updateusage = N'TRUE';
GO

C. Displaying space usage information about the remote table associated with a Stretch-enabled table
The following example summarizes the space used by the remote table associated with a Stretch-enabled table by
using the @mode argument to specify the remote target. For more info, see Stretch Database.

USE StretchedAdventureWorks2016
GO
EXEC sp_spaceused N'Purchasing.Vendor', @mode = 'REMOTE_ONLY'
D. Displaying space usage information for a database in a single result set
The following example summarizes space usage for the current database in a single result set.

USE AdventureWorks2016
GO
EXEC sp_spaceused @oneresultset = 1

E. Displaying space usage information for a database with at least one MEMORY_OPTIMIZED file group in a
single result set
The following example summarizes space usage for the current database with at least one MEMORY_OPTIMIZED
file group in a single result set.

USE WideWorldImporters
GO
EXEC sp_spaceused @updateusage = 'FALSE', @mode = 'ALL', @oneresultset = '1', @include_total_xtp_storage =
'1';
GO

F. Displaying space usage information for a MEMORY_OPTIMIZED table object in a database.


The following example summarizes space usage for a MEMORY_OPTIMIZED table object in the current database
with at least one MEMORY_OPTIMIZED file group.

USE WideWorldImporters
GO
EXEC sp_spaceused
@objname = N'VehicleTemparatures',
@updateusage = 'FALSE',
@mode = 'ALL',
@oneresultset = '0',
@include_total_xtp_storage = '1';
GO

See Also
CREATE INDEX (Transact-SQL)
CREATE TABLE (Transact-SQL)
DBCC UPDATEUSAGE (Transact-SQL)
SQL Server Service Broker
sys.allocation_units (Transact-SQL)
sys.indexes (Transact-SQL)
sys.index_columns (Transact-SQL)
sys.objects (Transact-SQL)
sys.partitions (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_tableoption (Transact-SQL)
11/21/2017 • 6 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sets option values for user-defined tables. sp_tableoption can be used to control the in-row behavior of tables
with varchar(max), nvarchar(max), varbinary(max), xml, text, ntext, image, or large user-defined type
columns.

IMPORTANT
The text in row feature will be removed in a future version of SQL Server. To store large value data, we recommend that you
use of the varchar(max), nvarchar(max) and varbinary(max) data types.

Transact-SQL Syntax Conventions

Syntax
sp_tableoption [ @TableNamePattern = ] 'table'
, [ @OptionName = ] 'option_name'
,[ @OptionValue =] 'value'

Arguments
[ @TableNamePattern =] 'table'
Is the qualified or nonqualified name of a user-defined database table. If a fully qualified table name, including a
database name, is provided, the database name must be the name of the current database. Table options for
multiple tables can not be set at the same time. table is nvarchar(776), with no default.
[ @OptionName = ] 'option_name'
Is a table option name. option_name is varchar(35), with no default of NULL. option_name can be one of the
following values.

VALUE DESCRIPTION

table lock on bulk load When disabled (the default), it causes the bulk load process
on user-defined tables to obtain row locks. When enabled, it
causes the bulk load processes on user-defined tables to
obtain a bulk update lock.

insert row lock No longer supported.

This option has no effect on the locking behavior of SQL


Server and is included only for compatibility of existing scripts
and procedures.
VALUE DESCRIPTION

text in row When OFF or 0 (disabled, the default), it does not change
current behavior, and there is no BLOB in row.

When specified and @OptionValue is ON (enabled) or an


integer value from 24 through 7000, new text, ntext, or
image strings are stored directly in the data row. All existing
BLOB (binary large object: text, ntext, or image data) will be
changed to text in row format when the BLOB value is
updated. For more information, see Remarks.

large value types out of row 1 = varchar(max), nvarchar(max), varbinary(max), xml


and large user-defined type (UDT) columns in the table are
stored out of row, with a 16-byte pointer to the root.

0 = varchar(max), nvarchar(max), varbinary(max), xml


and large UDT values are stored directly in the data row, up
to a limit of 8000 bytes and as long as the value can fit in the
record. If the value does not fit in the record, a pointer is
stored in-row and the rest is stored out of row in the LOB
storage space. 0 is the default value.

Large user-defined type (UDT) applies to: SQL Server 2008


through SQL Server 2017.

Use the TEXTIMAGE_ON option of CREATE TABLE to specify a


location for storage of large data types.

vardecimal storage format Applies to: SQL Server 2008 through SQL Server 2017.

When TRUE, ON, or 1, the designated table is enabled for


vardecimal storage format. When FALSE, OFF, or 0, the table
is not enabled for vardecimal storage format. Vardecimal
storage format can be enabled only when the database has
been enabled for vardecimal storage format by using
sp_db_vardecimal_storage_format. In SQL Server 2008 and
later, vardecimal storage format is deprecated. Use ROW
compression instead. For more information, see Data
Compression. 0 is the default value.

[ @OptionValue =] 'value'
Is whether the option_name is enabled (TRUE, ON, or 1) or disabled (FALSE, OFF, or 0). value is varchar(12), with
no default. value is case insensitive.
For the text in row option, valid option values are 0, ON, OFF, or an integer from 24 through 7000. When value is
ON, the limit defaults to 256 bytes.

Return Code Values


0 (success) or error number (failure)

Remarks
sp_tableoption can be used only to set option values for user-defined tables. To display table properties, use
OBJECTPROPERTY.
The text in row option in sp_tableoption can be enabled or disabled only on tables that contain text columns. If the
table does not have a text column, SQL Server raises an error.
When the text in row option is enabled, the @OptionValue parameter allows users to specify the maximum size to
be stored in a row for a BLOB. The default is 256 bytes, but values can range from 24 through 7000 bytes.
text, ntext, or image strings are stored in the data row if the following conditions apply:
text in row is enabled.
The length of the string is shorter than the limit specified in @OptionValue
There is enough space available in the data row.
When BLOB strings are stored in the data row, reading and writing the text, ntext, or image strings can be
as fast as reading or writing character and binary strings. SQL Server does not have to access separate
pages to read or write the BLOB string.
If a text, ntext, or image string is larger than the specified limit or the available space in the row, pointers
are stored in the row instead. The conditions for storing the BLOB strings in the row nonetheless apply:
There must be enough space in the data row to hold the pointers.
BLOB strings and pointers stored in the row of a table are treated similarly to variable-length strings. SQL
Server uses only the number of bytes required to store the string or the pointer.
Existing BLOB strings are not converted immediately when text in row is first enabled. The strings are
converted only when they are updated. Likewise, when the text in row option limit is increased, the text,
ntext, or image strings already in the data row will not be converted to adhere to the new limit until the
time they are updated.

NOTE
Disabling the text in row option or reducing the limit of the option will require the conversion of all BLOBs; therefore, the
process can be long, depending on the number of BLOB strings that must be converted. The table is locked during the
conversion process.

A table variable, including a function that returns a table variable, automatically has the text in row option enabled
with a default inline limit of 256. This option cannot be changed.
The text in row option supports the TEXTPTR, WRITETEXT, UPDATETEXT, and READTEXT functions. Users can read
parts of a BLOB with the SUBSTRING() function, but must remember that in-row text pointers have different
duration and number limits from other text pointers.
To change a table from vardecimal storage format back to the normal decimal storage format, the database must
be in SIMPLE recovery mode. Changing the recovery mode will break the log chain for backup purposes, therefore
you should create a full database backup after removing the vardecimal storage format from a table.
If you are converting an existing LOB data type column (text, ntext, or image) to small-to-medium large value
types (varchar(max), nvarchar(max), or varbinary(max)) , and most statements do not reference the large value
type columns in your environment, consider changing large_value_types_out_of_row to 1 to gain optimal
performance. When the large_value_types_out_of_row option value is changed, existing varchar(max),
nvarchar(max), varbinary(max), and xml values are not immediately converted. The storage of the strings is
changed as they are subsequently updated. Any new values inserted into a table are stored according to the table
option in effect. For immediate results, either make a copy of the data and then repopulate the table after
changing the large_value_types_out_of_row setting or update each small-to-medium large value types column
to itself so that the storage of the strings is changed with the table option in effect. Consider rebuilding the
indexes on the table after the update or repopulation to condense the table.

Permissions
To execute sp_tableoption requires ALTER permission on the table.

Examples
A. Storing xml data out of the row
The following example specifies that the xml data in the HumanResources.JobCandidate table be stored out of row.

USE AdventureWorks2012;
GO
EXEC sp_tableoption 'HumanResources.JobCandidate', 'large value types out of row', 1;

B. Enabling vardecimal storage format on a table


The following example modifies the Production.WorkOrderRouting table to store the decimal data type in the
vardecimal storage format.

USE master;
GO
-- The database must be enabled for vardecimal storage format
-- before a table can be enabled for vardecimal storage format
EXEC sp_db_vardecimal_storage_format 'AdventureWorks2012', 'ON';
GO
USE AdventureWorks2012;
GO
EXEC sp_tableoption 'Production.WorkOrderRouting',
'vardecimal storage format', 'ON';

See Also
sys.tables (Transact-SQL)
OBJECTPROPERTY (Transact-SQL)
System Stored Procedures (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
sp_unbindefault (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Unbinds, or removes, a default from a column or from an alias data type in the current database.

IMPORTANT
This feature will be removed in the next version of Microsoft SQL Server. Do not use this feature in new development work,
and modify applications that currently use this feature as soon as possible. We recommend that you create default
definitions by using the DEFAULT keyword in the ALTER TABLE or CREATE TABLE statements instead.

Transact-SQL Syntax Conventions

Syntax
sp_unbindefault [ @objname = ] 'object_name'
[ , [ @futureonly = ] 'futureonly_flag' ]

Arguments
[ @objname= ] 'object_name'
Is the name of the table and column or the alias data type from which the default is to be unbound. object_name is
nvarchar(776), with no default. SQL Server attempts to resolve two-part identifiers to column names first, then to
alias data types.
When unbinding a default from an alias data type, any columns of that data type that have the same default are
also unbound. Columns of that data type with defaults bound directly to them are unaffected.

NOTE
object_name can contain brackets [] as delimited identifier characters. For more information, see Database Identifiers.

[ @futureonly= ] 'futureonly_flag'
Is used only when unbinding a default from an alias data type. futureonly_flag is varchar(15), with a default of
NULL. When futureonly_flag is futureonly, existing columns of the data type do not lose the specified default.

Return Code Values


0 (success) or 1 (failure)

Remarks
To display the text of a default, execute sp_helptext with the name of the default as the parameter.

Permissions
To unbind a default from a table column requires ALTER permission on the table. To unbind a default from an alias
data type requires CONTROL permission on the type or ALTER permission on the schema to which the type
belongs.

Examples
A. Unbinding a default from a column
The following example unbinds the default from the hiredate column of an employees table.

EXEC sp_unbindefault 'employees.hiredate';

B. Unbinding a default from an alias data type


The following example unbinds the default from the alias data type ssn . It unbinds existing and future columns of
that type.

EXEC sp_unbindefault 'ssn';

C. Using the futureonly_flag


The following example unbinds future uses of the alias data type ssn without affecting existing ssn columns.

EXEC sp_unbindefault 'ssn', 'futureonly';

D. Using delimited identifiers


The following example shows using delimited identifiers in object_name parameter.

CREATE TABLE [t.3] (c1 int); -- Notice the period as part of the table
-- name.
CREATE DEFAULT default2 AS 0;
GO
EXEC sp_bindefault 'default2', '[t.3].c1' ;
-- The object contains two periods;
-- the first is part of the table name and the second
-- distinguishes the table name from the column name.
EXEC sp_unbindefault '[t.3].c1';

See Also
System Stored Procedures (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
CREATE DEFAULT (Transact-SQL)
DROP DEFAULT (Transact-SQL)
sp_bindefault (Transact-SQL)
sp_helptext (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_unbindrule (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Unbinds a rule from a column or an alias data type in the current database.

IMPORTANT
This feature will be removed in the next version of Microsoft SQL Server. Do not use this feature in new development work,
and modify applications that currently use this feature as soon as possible. We recommend that you create default
definitions by using the DEFAULT keyword in the ALTER TABLE or CREATE TABLE statements instead.

Transact-SQL Syntax Conventions

Syntax
sp_unbindrule [ @objname = ] 'object_name'
[ , [ @futureonly = ] 'futureonly_flag' ]

Arguments
[ @objname= ] 'object_name'
Is the name of the table and column or the alias data type from which the rule is unbound. object_name is
nvarchar(776), with no default. SQL Server attempts to resolve two-part identifiers to column names first, then to
alias data types. When unbinding a rule from an alias data type, any columns of the data type that have the same
rule are also unbound. Columns of that data type with rules bound directly to them are unaffected.

NOTE
object_name can contain brackets [] as delimited identifier characters. For more information, see Database Identifiers.

[ @futureonly= ] 'futureonly_flag'
Is used only when unbinding a rule from an alias data type. futureonly_flag is varchar(15), with a default of NULL.
When futureonly_flag is futureonly, existing columns of that data type do not lose the specified rule.

Return Code Values


0 (success) or 1 (failure)

Remarks
To display the text of a rule, execute sp_helptext with the rule name as the parameter.
When a rule is unbound, the information about the binding is removed from the sys.columns table if the rule was
bound to a column, and from the sys.types table if the rule was bound to an alias data type.
When a rule is unbound from an alias data type, it is also unbound from any columns having that alias data type.
The rule may also still be bound to columns whose data types were later changed by the ALTER COLUMN clause
of an ALTER TABLE statement, you must specifically unbind the rule from these columns by using sp_unbindrule
and specifying the column name.

Permissions
To unbind a rule from a table column requires ALTER permission on the table. To unbind a rule from an alias data
type requires CONTROL permission on the type or ALTER permission on the schema to which the type belongs.

Examples
A. Unbinding a rule from a column
The following example unbinds the rule from the startdate column of an employees table.

EXEC sp_unbindrule 'employees.startdate';

B. Unbinding a rule from an alias data type


The following example unbinds the rule from the alias data type ssn . It unbinds the rule from existing and future
columns of that type.

EXEC sp_unbindrule ssn;

C. Using futureonly_flag
The following example unbinds the rule from the alias data type ssn without affecting existing ssn columns.

EXEC sp_unbindrule 'ssn', 'futureonly';

D. Using delimited identifiers


The following example shows using delimited identifiers in the object_name parameter.

CREATE TABLE [t.4] (c1 int); -- Notice the period as part of the table
-- name.
GO
CREATE RULE rule2 AS @value > 100;
GO
EXEC sp_bindrule rule2, '[t.4].c1' -- The object contains two
-- periods; the first is part of the table name and the second
-- distinguishes the table name from the column name.
GO
EXEC sp_unbindrule '[t.4].c1';

See Also
System Stored Procedures (Transact-SQL)
Database Engine Stored Procedures (Transact-SQL)
CREATE RULE (Transact-SQL)
DROP RULE (Transact-SQL)
sp_bindrule (Transact-SQL)
sp_helptext (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_updateextendedproperty (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates the value of an existing extended property.
Transact-SQL Syntax Conventions

Syntax
sp_updateextendedproperty
[ @name = ]{ 'property_name' }
[ , [ @value = ]{ 'value' }
[, [ @level0type = ]{ 'level0_object_type' }
, [ @level0name = ]{ 'level0_object_name' }
[, [ @level1type = ]{ 'level1_object_type' }
, [ @level1name = ]{ 'level1_object_name' }
[, [ @level2type = ]{ 'level2_object_type' }
, [ @level2name = ]{ 'level2_object_name' }
]
]
]
]

Arguments
[ @name= ]{ 'property_name'}
Is the name of the property to be updated. property_name is sysname, and cannot be NULL.
[ @value= ]{ 'value'}
Is the value associated with the property. value is sql_variant, with a default of NULL. The size of value may not be
more than 7,500 bytes.
[ @level0type= ]{ 'level0_object_type'}
Is the user or user-defined type. level0_object_type is varchar(128), with a default of NULL. Valid inputs are
ASSEMBLY, CONTRACT, EVENT NOTIFICATION, FILEGROUP, MESSAGE TYPE, PARTITION FUNCTION, PARTITION
SCHEME, PLAN GUIDE, REMOTE SERVICE BINDING, ROUTE, SCHEMA, SERVICE, USER, TRIGGER, TYPE, and NULL.

IMPORTANT
USER and TYPE as level-0 types will be removed in a future version of SQL Server. Avoid using these features in new
development work, and plan to modify applications that currently use these features. Use SCHEMA as the level 0 type
instead of USER. For TYPE, use SCHEMA as the level 0 type and TYPE as the level 1 type.

[ @level0name= ]{ 'level0_object_name'}
Is the name of the level 1 object type specified. level0_object_name is sysname with a default of NULL.
[ @level1type= ]{ 'level1_object_type'}
Is the type of level 1 object. level1_object_type is varchar(128) with a default of NULL. Valid inputs are
AGGREGATE, DEFAULT, FUNCTION, LOGICAL FILE NAME, PROCEDURE, QUEUE, RULE, SYNONYM, TABLE,
TABLE_TYPE, TYPE, VIEW, XML SCHEMA COLLECTION, and NULL.
[ @level1name= ]{ 'level1_object_name'}
Is the name of the level 1 object type specified. level1_object_name is sysname with a default of NULL.
[ @level2type= ]{ 'level2_object_type'}
Is the type of level 2 object. level2_object_type is varchar(128) with a default of NULL. Valid inputs are COLUMN,
CONSTRAINT, EVENT NOTIFICATION, INDEX, PARAMETER, TRIGGER, and NULL.
[ @level2name= ]{ 'level2_object_name'}
Is the name of the level 2 object type specified. level2_object_name is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
For the purpose of specifying extended properties, the objects in a SQL Server database are classified into three
levels (0, 1, and 2). Level 0 is the highest level and is defined as objects contained at the database scope. Level 1
objects are contained in a schema or user scope, and level 2 objects are contained by level 1 objects. Extended
properties can be defined for objects at any of these levels. References to an object in one level must be qualified
with the names of the higher level objects that own or contain them.
Given a valid property_name and value, if all object types and names are null, the property updated belongs to the
current database.

Permissions
Members of the db_owner and db_ddladmin fixed database roles may update the extended properties of any
object with the following exception: db_ddladmin may not add properties to the database itself, or to users or
roles.
Users may update extended properties to objects they own, or on which they have ALTER or CONTROL
permissions.

Examples
A. Updating an extended property on a column
The following example updates the value of property Caption on column ID in table T1 .
USE AdventureWorks2012;
GO
CREATE TABLE T1 (id int , name char (20));
GO
EXEC sp_addextendedproperty
@name = N'Caption'
,@value = N'Employee ID'
,@level0type = N'Schema', @level0name = dbo
,@level1type = N'Table', @level1name = T1
,@level2type = N'Column', @level2name = id;
GO
--Update the extended property.
EXEC sp_updateextendedproperty
@name = N'Caption'
,@value = 'Employee ID must be unique.'
,@level0type = N'Schema', @level0name = dbo
,@level1type = N'Table', @level1name = T1
,@level2type = N'Column', @level2name = id;
GO

B. Updating an extended property on a database


The following example first creates an extended property on the AdventureWorks2012 sample database and
then updates the value of that property.

USE AdventureWorks2012;
GO
EXEC sp_addextendedproperty
@name = N'NewCaption', @value = 'AdventureWorks2012 Sample OLTP Database';
GO
USE AdventureWorks2012;
GO
EXEC sp_updateextendedproperty
@name = N'NewCaption', @value = 'AdventureWorks2012 Sample Database';
GO

See Also
Database Engine Stored Procedures (Transact-SQL)
sys.fn_listextendedproperty (Transact-SQL)
sp_addextendedproperty (Transact-SQL)
sp_dropextendedproperty (Transact-SQL)
sys.extended_properties (Transact-SQL)
sp_updatestats (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Runs UPDATE STATISTICS against all user-defined and internal tables in the current database.
For more information about UPDATE STATISTICS, see UPDATE STATISTICS (Transact-SQL). For more information
about statistics, see Statistics.
Transact-SQL Syntax Conventions

Syntax
sp_updatestats [ [ @resample = ] 'resample']

Return Code Values


0 (success) or 1 (failure)

Arguments
[ @resample =] 'resample'
Specifies that sp_updatestats will use the RESAMPLE option of the UPDATE STATISTICS statement. If 'resample'
is not specified, sp_updatestats updates statistics by using the default sampling. resample is varchar(8) with a
default value of NO.

Remarks
sp_updatestats executes UPDATE STATISTICS, by specifying the ALL keyword, on all user-defined and internal
tables in the database. sp_updatestats displays messages that indicate its progress. When the update is completed,
it reports that statistics have been updated for all tables.
sp_updatestats updates statistics on disabled nonclustered indexes and does not update statistics on disabled
clustered indexes.
For disk-based tables, sp_updatestats updates statistics based on the modification_counter information in the
sys.dm_db_stats_properties catalog view, updating statistics where at least one row has been modified. Statistics
on memory-optimized tables are always updated when executing sp_updatestats. Therefore do not execute
sp_updatestats more than necessary.
sp_updatestats can trigger a recompile of stored procedures or other compiled code. However, sp_updatestats
might not cause a recompile, if only one query plan is possible for the tables referenced and the indexes on them. A
recompilation would be unnecessary in these cases even if statistics are updated.
For databases with a compatibility level below 90, executing sp_updatestats does not preserve the latest
NORECOMPUTE setting for specific statistics. For databases with a compatibility level of 90 or higher,
sp_updatestats does preserve the latest NORECOMPUTE option for specific statistics. For more information about
disabling and re-enabling statistics updates, see Statistics.
Permissions
Requires membership in the sysadmin fixed server role, or ownership of the database (dbo).

Examples
The following example updates the statistics for tables in the AdventureWorks2012 database.

USE AdventureWorks2012;
GO
EXEC sp_updatestats;

See Also
ALTER DATABASE SET Options (Transact-SQL)
CREATE STATISTICS (Transact-SQL)
DBCC SHOW_STATISTICS (Transact-SQL)
DROP STATISTICS (Transact-SQL)
sp_autostats (Transact-SQL)
sp_createstats (Transact-SQL)
UPDATE STATISTICS (Transact-SQL)
System Stored Procedures
sp_validname (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Checks for valid SQL Server identifier names. All nonbinary and nonzero data, including Unicode data that can be
stored by using the nchar, nvarchar, or ntext data types, are accepted as valid characters for identifier names.
Transact-SQL Syntax Conventions

Syntax
sp_validname [@name =] 'name'
[, [@raise_error =] raise_error]

Arguments
[ @name= ] 'name'
Is the name of the identifiers for which to check validity. name is sysname, with no default. name cannot be NULL,
cannot be an empty string, and cannot contain a binary-zero character.
[ @raise_error= ] raise_error
Specifies whether to raise an error. raise_error is bit, with a default of 1. This means that errors will appear. 0
causes no error messages to appear.

Return Code Values


0 (success) or 1 (failure)

Permissions
Requires membership in the public role.

See Also
Database Engine Stored Procedures (Transact-SQL)
Data Types (Transact-SQL)
NCHAR (Transact-SQL)
nchar and nvarchar (Transact-SQL)
ntext, text, and image (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_who (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Provides information about current users, sessions, and processes in an instance of the Microsoft SQL Server
Database Engine. The information can be filtered to return only those processes that are not idle, that belong to a
specific user, or that belong to a specific session.
Transact-SQL Syntax Conventions

Syntax
sp_who [ [ @loginame = ] 'login' | session ID | 'ACTIVE' ]

Arguments
[ @loginame = ] 'login' | session ID | 'ACTIVE'
Is used to filter the result set.
login is sysname that identifies processes belonging to a particular login.
session ID is a session identification number belonging to the SQL Server instance. session ID is smallint.
ACTIVE excludes sessions that are waiting for the next command from the user.
If no value is provided, the procedure reports all sessions belonging to the instance.

Return Code Values


0 (success) or 1 (failure)

Result Sets
sp_who returns a result set with the following information.

COLUMN DATA TYPE DESCRIPTION

spid smallint Session ID.

ecid smallint Execution context ID of a given thread


associated with a specific session ID.

ECID = {0, 1, 2, 3, ...n}, where 0 always


represents the main or parent thread,
and {1, 2, 3, ...n} represent the
subthreads.
COLUMN DATA TYPE DESCRIPTION

status nchar(30) Process status. The possible values are:

dormant. SQL Server is resetting the


session.

running. The session is running one or


more batches. When Multiple Active
Result Sets (MARS) is enabled, a session
can run multiple batches. For more
information, see Using Multiple Active
Result Sets (MARS).

background. The session is running a


background task, such as deadlock
detection.

rollback. The session has a transaction


rollback in process.

pending. The session is waiting for a


worker thread to become available.

runnable. The session's task is in the


runnable queue of a scheduler while
waiting to get a time quantum.

spinloop. The session's task is waiting


for a spinlock to become free.

suspended. The session is waiting for


an event, such as I/O, to complete.

loginame nchar(128) Login name associated with the


particular process.

hostname nchar(128) Host or computer name for each


process.

blk char(5) Session ID for the blocking process, if


one exists. Otherwise, this column is
zero.

When a transaction associated with a


specified session ID is blocked by an
orphaned distributed transaction, this
column will return a '-2' for the
blocking orphaned transaction.

dbname nchar(128) Database used by the process.

cmd nchar(16) Database Engine command ( Transact-


SQL statement, internal Database
Engine process, and so on) executing
for the process.

request_id int ID for requests running in a specific


session.

In case of parallel processing, subthreads are created for the specific session ID. The main thread is indicated as
spid = <xxx> and ecid =0 . The other subthreads have the same spid = <xxx> , but with ecid > 0.

Remarks
A blocking process, which may have an exclusive lock, is one that is holding resources that another process needs.
All orphaned distributed transactions are assigned the session ID value of '-2'. Orphaned distributed transactions
are distributed transactions that are not associated with any session ID. For more information, see Use Marked
Transactions to Recover Related Databases Consistently (Full Recovery Model).
Query the is_user_process column of sys.dm_exec_sessions to separate system processes from user processes.

Permissions
Requires VIEW SERVER STATE permission on the server to see all executing sessions on the instance of SQL
Server. Otherwise, the user sees only the current session.

Examples
A. Listing all current processes
The following example uses sp_who without parameters to report all current users.

USE master;
GO
EXEC sp_who;
GO

B. Listing a specific user's process


The following example shows how to view information about a single current user by login name.

USE master;
GO
EXEC sp_who 'janetl';
GO

C. Displaying all active processes

USE master;
GO
EXEC sp_who 'active';
GO

D. Displaying a specific process identified by a session ID

USE master;
GO
EXEC sp_who '10' --specifies the process_id;
GO

See Also
sp_lock (Transact-SQL)
sys.sysprocesses (Transact-SQL)
System Stored Procedures (Transact-SQL)
sys.sp_flush_log (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Flushes to disk the transaction log of the current database, thereby hardening all previously committed delayed
durable transactions.
If you choose to use delayed transaction durability because of the performance benefits, but you also want to have
a guaranteed limit on the amount of data that is lost on server crash or failover, then execute sys.sp_flush_log on
a regular schedule. For example, if you want to make sure you don’t lose more than x seconds worth of data, you
would execute sp_flush_log every x seconds.
Executing sys.sp_flush_log guarantees that all previously committed delayed durable transactions are made
durable. See the conceptual topic Control Transaction Durability for more information.
Transact-SQL Syntax Conventions

Syntax
sys.sp_flush_log

Parameters
None.

Return Code Values


A return code of 1 indicates success. Any other value indicates failure.

Result Sets
None.

Sample code
.
EXECUTE sys.sp_flush_log
sys.sp_xtp_bind_db_resource_pool (Transact-SQL)
1/2/2018 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2014) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Binds the specified In-Memory OLTP database to the specified resource pool. Both the database and the resource
pool must exist prior to executing sys.sp_xtp_bind_db_resource_pool .
This system procedure creates a binding between the Resource Governor pool identified by resource_pool_name,
and the database identified by database_name. It is not required that the database has any memory-optimized
objects at the time of binding. In the absence of memory-optimized objects, there is no memory taken from the
resource pool. This binding will be used by Resource Governor to manage memory allocated by In-Memory OLTP
allocators as described below.
If there is already a binding in place for a given database, the procedure returns an error. In no event may a
database have more than one active binding.
Transact-SQL Syntax Conventions

Syntax
sys.sp_xtp_bind_db_resource_pool 'database_name', 'resource_pool_name'

Arguments
database_name
The name of an existing In-Memory OLTP enabled database.
resource_pool_name
The name of an existing resource pool.

Messages
When an error occurs sp_xtp_bind_db_resource_pool returns one of these messages.
Database does not exist
Database_name must refer to an existing database. If there is no database with the specified ID, the following
message is returned:
Database ID %d does not exist. Please use a valid database ID for this binding.

Msg 911, Level 16, State 18, Procedure sp_xtp_bind_db_resource_pool_internal, Line 51


Database 'Hekaton_DB213' does not exist. Make sure that the name is entered correctly.

Database is a system database


In-Memory OLTP tables cannot be created in system databases. Thus it is invalid to create a binding of In-Memory
OLTP memory for such a database. The following error is returned:
Database_name %s refers to a system database. Resource pools may only be bound to a user database.
Msg 41371, Level 16, State 1, Procedure sp_xtp_bind_db_resource_pool_internal, Line 51
Binding to a resource pool is not supported for system database 'master'. This operation can only be performed
on a user database.

Resource Pool does not exist


The resource pool identified by resource_pool_name must exist prior to executing sp_xtp_bind_db_resource_pool . If
there is no pool with the specified ID, the following error is returned:
Resource Pool %s does not exist. Please enter a valid resource pool name.

Msg 41370, Level 16, State 1, Procedure sp_xtp_bind_db_resource_pool_internal, Line 51


Resource pool 'Pool_Hekaton' does not exist or resource governor has not been reconfigured.

Pool_name refers to a reserved system pool


The pool names “INTERNAL” and “DEFAULT” are reserved for system pools. It is not valid to explicitly bind a
database to either of these. If a system pool name is entered, the following error is returned:
Resource Pool %s is a system resource pool. System resource pools may not be explicitly bound to a database using
this procedure.

Msg 41373, Level 16, State 1, Procedure sp_xtp_bind_db_resource_pool_internal, Line 51


Database 'Hekaton_DB' cannot be explicitly bound to the resource pool 'internal'. A database can only be bound
only to a user resource pool.

Database is already bound to another Resource Pool


A database can be bound to only one resource pool at any time. Database bindings to resource pools must be
explicitly removed before they can be bound to another pool. See sys.sp_xtp_unbind_db_resource_pool (Transact-
SQL).
Database %s is already bound to resource pool %s. You must unbind before you can create a new binding.

Msg 41372, Level 16, State 1, Procedure sp_xtp_bind_db_resource_pool_internal, Line 54


Database 'Hekaton_DB' is currently bound to a resource pool. A database must be unbound before creating a new
binding.

When successful, sp_xtp_bind_db_resource_pool returns the following message.


Successful Binding
When successful, the function returns the following success message, which is logged in the SQL ERRORLOG
A resource binding has been successfully created between the database with ID %d and the resource pool with ID
%d.

Examples
A. The following code example binds the database Hekaton_DB to the resource pool Pool_Hekaton.

sys.sp_xtp_bind_db_resource_pool N'Hekaton_DB', N'Pool_Hekaton'

The binding takes effect the next time the database is brought online.
B. Expanded example of above example which includes some basic checks. Execute the following Transact-SQL in
SQL Server Management Studio:
DECLARE @resourcePool sysname = N'Pool_Hekaton';
DECLARE @database sysname = N'Hekaton_DB';

-- Check whether resource pool exists


IF NOT EXISTS (
SELECT * FROM sys.resource_governor_resource_pools WHERE name = @resourcePool
)
BEGIN
SELECT N'Resource pool "' + @resourcePool + N'" does not exist or resource governor has not been
reconfigured.';
END
-- Check whether database is already bound to a resource pool
ELSE IF EXISTS (
SELECT p.name
FROM sys.databases d
JOIN sys.resource_governor_resource_pools p
ON d.resource_pool_id = p.pool_id
WHERE d.name = @database
)
BEGIN
SELECT N'Database "' + @database + N'" is currently bound to resource pool "' + @resourcePool + N'". A
database must be unbound before creating a new binding.';
END
-- Bind resource pool to database.
ELSE BEGIN
EXEC sp_xtp_bind_db_resource_pool @database, @resourcePool;
END

Requirements
Both the database specified by database_name and the resource pool specified by resource_pool_name must
exist prior to binding them.
Requires CONTROL SERVER permission.

See Also
Bind a Database with Memory-Optimized Tables to a Resource Pool
sys.sp_xtp_unbind_db_resource_pool (Transact-SQL)
sys.sp_xtp_checkpoint_force_garbage_collection
(Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2014) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Marks source files used in the merge operation with the log sequence number (LSN) after which they are not
needed and can be garbage collected. Also, it moves the files whose associated LSN is lower than the log truncation
point to filestream garbage collection.
Transact-SQL Syntax Conventions

Syntax
sys.sp_xtp_checkpoint_force_garbage_collection [[ @dbname=database_name]

Arguments
database_name
The database to run garbage collection on. The default is the current database.

Return Code Values


0 for success. Nonzero for failure.

Result Set
A returned row contains the following information:

COLUMN DESCRIPTION

num_collected_items Indicates the number of files that have been moved to


filestream garbage collection. These are the files whose log
sequence number (LSN) is less than the LSN of log truncation
point

num_marked_for_collection_items Indicates the number of data/delta files whose LSN has been
updated with the log blockID of the end-of-log LSN.

last_collected_xact_seqno Returns the last corresponding LSN up to which the files have
been moved to filestream garbage collection.

Permissions
Requires database owner permission.

Sample
exec [sys].[sp_xtp_checkpoint_force_garbage_collection] hkdb1

See Also
System Stored Procedures (Transact-SQL)
In-Memory OLTP (In-Memory Optimization)
sys.sp_xtp_control_proc_exec_stats (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2014) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Enables statistics collection for natively compiled stored procedures for the instance.
To enable statistics collection at the query level for natively compiled stored procedures, see
sys.sp_xtp_control_query_exec_stats (Transact-SQL).

Syntax
sp_xtp_control_proc_exec_stats [ [ @new_collection_value = ] collection_value ], [ @old_collection_value]

Arguments
@new_collection_value = value
Determines whether procedure-level statistics collection is on (1) or off (0).
@new_collection_value is set to zero when SQL Server or the database starts.
@old_collection_value = value
Returns the current status.

Return Code
0 for success. Nonzero for failure.

Permissions
Requires membership in the fixed sysadmin role.

Code Samples
To set @new_collection_value and query for the value of @new_collection_value:

exec [sys].[sp_xtp_control_proc_exec_stats] @new_collection_value = 1


declare @c bit
exec sp_xtp_control_proc_exec_stats @old_collection_value=@c output
select @c as 'collection status'

See Also
System Stored Procedures (Transact-SQL)
In-Memory OLTP (In-Memory Optimization)
sys.sp_xtp_control_query_exec_stats (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2014) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Enables per query statistics collection for all natively compiled stored procedures for the instance, or specific
natively compiled stored procedures.
Performance decreases when you enable statistics collection. If you only need to troubleshoot one, or a few
natively compiled stored procedures, you can enabling statistics collection for just those few natively compiled
stored procedures.
To enable statistics collection at the procedure level for all natively compiled stored procedures, see
sys.sp_xtp_control_proc_exec_stats (Transact-SQL).

Syntax
sp_xtp_control_query_exec_stats [ [ @new_collection_value = ] collection_value ],
[ [ @database_id = ] database_id
[ , [ @xtp_object_id = ] procedure_id ] ,
[ @old_collection_value] ]

Arguments
@new_collection_value = value
Determines whether procedure-level statistics collection is on (1) or off (0).
@new_collection_value is set to zero when SQL Server starts.
@database_id = = database_id, @xtp_object_id = procedure_id
The database ID and object ID for the natively compiled stored procedure. If statistics collection is enabled for the
instance (sys.sp_xtp_control_proc_exec_stats (Transact-SQL)), statistics on a natively compiled stored procedure are
collected. Turning off statistics collection on the instance does not turn off statistics collection for individual
natively compiled stored procedures.
Use sys.databases (Transact-SQL), sys.procedures (Transact-SQL), DB_ID (Transact-SQL), or OBJECT_ID (Transact-
SQL) to get IDs for a database and stored procedure.
@old_collection_value = value
Returns the current status.

Return Code
0 for success. Nonzero for failure.

Permissions
Requires membership in the fixed sysadmin role.

Code Sample
The following code sample shows how to enable statistics collection for all natively compiled stored procedures for
the instance and then for a specific natively compiled stored procedure.

DECLARE @c bit

EXEC [sys].[sp_xtp_control_query_exec_stats] @new_collection_value = 1;

EXEC sp_xtp_control_query_exec_stats @old_collection_value=@c output;


SELECT @c AS 'collection status';

EXEC [sys].[sp_xtp_control_query_exec_stats] @new_collection_value = 1,


@database_id = 5, @xtp_object_id = 341576255;

EXEC sp_xtp_control_query_exec_stats @database_id = 5,


@xtp_object_id = 341576255, @old_collection_value=@c output;

SELECT @c AS 'collection status';

See Also
System Stored Procedures (Transact-SQL)
In-Memory OLTP (In-Memory Optimization)
sys.sp_xtp_merge_checkpoint_files (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2014) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
sys.sp_xtp_merge_checkpoint_files merges all data and delta files in the transaction range specified.
For more information, see Creating and Managing Storage for Memory-Optimized Objects.
Transact-SQL Syntax Conventions
||
|-|
|Note: This stored procedure is deprecated in SQL Server 2016. It is no longer needed, and cannot be used, starting
SQL Server 2016.|

Syntax
sys.sp_xtp_merge_checkpoint_files database_name, @transaction_lower_bound, @transaction_upper_bound
[;]

Arguments
database_name
The name of the database on which to invoke the merge. If the database does not have in-memory tables, this
procedure returns with user error. If the database is offline, it returns an error.
lower_bound_Tid
The (bigint) lower bound of transactions for a data file as shown in sys.dm_db_xtp_checkpoint_files (Transact-SQL)
corresponding to the start checkpoint file of the merge. An error is generated for invalid transactonId value.
upper_bound_Tid
The (bigint) upper bound of transactions for a data file as shown in sys.dm_db_xtp_checkpoint_files (Transact-SQL).
An error is generated for invalid transactonId value.

Return Code Values


None

Cursors Returned
None

Permissions
Requires sysadmin fixed server role and the db_owner fixed database role.

Remarks
Merges all data and delta files in the valid range to produce a single data and delta file. This procedure does not
honor the merge policy.

See Also
System Stored Procedures (Transact-SQL)
In-Memory OLTP (In-Memory Optimization)
sys.sp_xtp_unbind_db_resource_pool (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2014) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
This system procedure removes an existing binding between a database and a resource pool for purposes of
tracking In-Memory OLTP memory usage. If there is no pool currently bound to the specified database, success is
returned. When the database is unbound, the previously allocated memory for memory-optimized objects stays
allocated to the previous resource pool. You need to restart the database to free up the allocated memory. Once a
database is unbound from the resource pool, the binding resorts to the DEFAULT resource pool.
Transact-SQL Syntax Conventions

Syntax
sys.sp_xtp_unbind_db_resource_pool 'database_name'

Arguments
database_name
The name of an existing In-Memory OLTP enabled database.
Parameters

Messages
If database was bound to a named resource pool, the procedure returns successfully. However, You must restart
the database for unbinding to take effect.
If there is no existing binding for the database specified, sp_xtp_unbind_db_resource_pool returns success, but gives
the informational message:

Msg 41374, Level 16, State 1, Procedure sp_xtp_unbind_db_resource_pool_internal, Line 140.


Database 'Hekaton_DB' does not have a binding to a resource pool.

Example
The following code unbinds the database Hekaton_DB from the In-Memory OLTP resource pool it is bound to. If
Hekaton_DB is not currently bound to a In-Memory OLTP resource pool, a message is given. The database must be
restarted for the unbinding to take effect.

sys.sp_xtp_unbind_db_resource_pool 'Hekaton_DB'

Requirements
The database specified by database_name must have a binding to an In-Memory OLTP resource pool.
Requires CONTROL SERVER permission.
See Also
Bind a Database with Memory-Optimized Tables to a Resource Pool
sys.sp_xtp_bind_db_resource_pool (Transact-SQL)
Database Mail Stored Procedures (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Microsoft SQL Server supports the following system stored procedures that are used to perform e-mail
operations from within an instance of SQL Server.

Database Mail Procedures

sp_send_dbmail sysmail_help_configure_sp

sysmail_add_account_sp sysmail_help_principalprofile_sp

sysmail_add_principalprofile_sp sysmail_help_profile_sp

sysmail_add_profile_sp sysmail_help_profileaccount_sp

sysmail_add_profileaccount_sp sysmail_help_queue_sp

sysmail_configure_sp sysmail_help_status_sp

sysmail_delete_account_sp sysmail_start_sp

sysmail_delete_log_sp sysmail_stop_sp

sysmail_delete_mailitems_sp sysmail_update_account_sp

sysmail_delete_principalprofile_sp sysmail_update_principalprofile_sp

sysmail_delete_profile_sp sysmail_update_profile_sp

sysmail_delete_profileaccount_sp sysmail_update_profileaccount_sp

sysmail_help_account_sp

See Also
Database Mail
sp_send_dbmail (Transact-SQL)
11/17/2017 • 10 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sends an e-mail message to the specified recipients. The message may include a query result set, file attachments,
or both. When mail is successfully placed in the Database Mail queue, sp_send_dbmail returns the mailitem_id
of the message. This stored procedure is in the msdb database.
Transact-SQL Syntax Conventions

Syntax
sp_send_dbmail [ [ @profile_name = ] 'profile_name' ]
[ , [ @recipients = ] 'recipients [ ; ...n ]' ]
[ , [ @copy_recipients = ] 'copy_recipient [ ; ...n ]' ]
[ , [ @blind_copy_recipients = ] 'blind_copy_recipient [ ; ...n ]' ]
[ , [ @from_address = ] 'from_address' ]
[ , [ @reply_to = ] 'reply_to' ]
[ , [ @subject = ] 'subject' ]
[ , [ @body = ] 'body' ]
[ , [ @body_format = ] 'body_format' ]
[ , [ @importance = ] 'importance' ]
[ , [ @sensitivity = ] 'sensitivity' ]
[ , [ @file_attachments = ] 'attachment [ ; ...n ]' ]
[ , [ @query = ] 'query' ]
[ , [ @execute_query_database = ] 'execute_query_database' ]
[ , [ @attach_query_result_as_file = ] attach_query_result_as_file ]
[ , [ @query_attachment_filename = ] query_attachment_filename ]
[ , [ @query_result_header = ] query_result_header ]
[ , [ @query_result_width = ] query_result_width ]
[ , [ @query_result_separator = ] 'query_result_separator' ]
[ , [ @exclude_query_output = ] exclude_query_output ]
[ , [ @append_query_error = ] append_query_error ]
[ , [ @query_no_truncate = ] query_no_truncate ]
[ , [ @query_result_no_padding = ] @query_result_no_padding ]
[ , [ @mailitem_id = ] mailitem_id ] [ OUTPUT ]

Arguments
[ @profile_name= ] 'profile_name'
Is the name of the profile to send the message from. The profile_name is of type sysname, with a default of NULL.
The profile_name must be the name of an existing Database Mail profile. When no profile_name is specified,
sp_send_dbmail uses the default private profile for the current user. If the user does not have a default private
profile, sp_send_dbmail uses the default public profile for the msdb database. If the user does not have a default
private profile and there is no default public profile for the database, @profile_name must be specified.
[ @recipients= ] 'recipients'
Is a semicolon-delimited list of e-mail addresses to send the message to. The recipients list is of type
varchar(max). Although this parameter is optional, at least one of @recipients, @copy_recipients, or
@blind_copy_recipients must be specified, or sp_send_dbmail returns an error.
[ @copy_recipients= ] 'copy_recipients'
Is a semicolon-delimited list of e-mail addresses to carbon copy the message to. The copy recipients list is of type
varchar(max). Although this parameter is optional, at least one of @recipients, @copy_recipients, or
@blind_copy_recipients must be specified, or sp_send_dbmail returns an error.
[ @blind_copy_recipients= ] 'blind_copy_recipients'
Is a semicolon-delimited list of e-mail addresses to blind carbon copy the message to. The blind copy recipients list
is of type varchar(max). Although this parameter is optional, at least one of @recipients, @copy_recipients, or
@blind_copy_recipients must be specified, or sp_send_dbmail returns an error.
[ @from_address= ] 'from_address'
Is the value of the 'from address' of the email message. This is an optional parameter used to override the settings
in the mail profile. This parameter is of type varchar(MAX). SMTP security settings determine if these overrides
are accepted. If no parameter is specified, the default is NULL.
[ @reply_to= ] 'reply_to'
Is the value of the 'reply to address' of the email message. It accepts only one email address as a valid value. This is
an optional parameter used to override the settings in the mail profile. This parameter is of type varchar(MAX).
SMTP security settings determine if these overrides are accepted. If no parameter is specified, the default is NULL.
[ @subject= ] 'subject'
Is the subject of the e-mail message. The subject is of type nvarchar(255). If no subject is specified, the default is
'SQL Server Message'.
[ @body= ] 'body'
Is the body of the e-mail message. The message body is of type nvarchar(max), with a default of NULL.
[ @body_format= ] 'body_format'
Is the format of the message body. The parameter is of type varchar(20), with a default of NULL. When specified,
the headers of the outgoing message are set to indicate that the message body has the specified format. The
parameter may contain one of the following values:
TEXT
HTML
Defaults to TEXT.
[ @importance= ] 'importance'
Is the importance of the message. The parameter is of type varchar(6). The parameter may contain one of
the following values:
Low
Normal
High
Defaults to Normal.
[ @sensitivity= ] 'sensitivity'
Is the sensitivity of the message. The parameter is of type varchar(12). The parameter may contain one of
the following values:
Normal
Personal
Private
Confidential
Defaults to Normal.
[ @file_attachments= ] 'file_attachments'
Is a semicolon-delimited list of file names to attach to the e-mail message. Files in the list must be specified
as absolute paths. The attachments list is of type nvarchar(max). By default, Database Mail limits file
attachments to 1 MB per file.
[ @query= ] 'query'
Is a query to execute. The results of the query can be attached as a file, or included in the body of the e-mail
message. The query is of type nvarchar(max), and can contain any valid Transact-SQL statements. Note
that the query is executed in a separate session, so local variables in the script calling sp_send_dbmail are
not available to the query.
[ @execute_query_database= ] 'execute_query_database'
Is the database context within which the stored procedure runs the query. The parameter is of type
sysname, with a default of the current database. This parameter is only applicable if @query is specified.
[ @attach_query_result_as_file= ] attach_query_result_as_file
Specifies whether the result set of the query is returned as an attached file. attach_query_result_as_file is of
type bit, with a default of 0.
When the value is 0, the query results are included in the body of the e-mail message, after the contents of
the @body parameter. When the value is 1, the results are returned as an attachment. This parameter is
only applicable if @query is specified.
[ @query_attachment_filename= ] query_attachment_filename
Specifies the file name to use for the result set of the query attachment. query_attachment_filename is of
type nvarchar(255), with a default of NULL. This parameter is ignored when attach_query_result is 0. When
attach_query_result is 1 and this parameter is NULL, Database Mail creates an arbitrary filename.
[ @query_result_header= ] query_result_header
Specifies whether the query results include column headers. The query_result_header value is of type bit.
When the value is 1, query results contain column headers. When the value is 0, query results do not include
column headers. This parameter defaults to 1. This parameter is only applicable if @query is specified.
[ @query_result_width = ] query_result_width
Is the line width, in characters, to use for formatting the results of the query. The query_result_width is of
type int, with a default of 256. The value provided must be between 10 and 32767. This parameter is only
applicable if @query is specified.
[ @query_result_separator= ] 'query_result_separator'
Is the character used to separate columns in the query output. The separator is of type char(1). Defaults to '
' (space).
[ @exclude_query_output= ] exclude_query_output
Specifies whether to return the output of the query execution in the e-mail message.
exclude_query_output is bit, with a default of 0. When this parameter is 0, the execution of the
sp_send_dbmail stored procedure prints the message returned as the result of the query execution on the
console. When this parameter is 1, the execution of the sp_send_dbmail stored procedure does not print
any of the query execution messages on the console.
[ @append_query_error= ] append_query_error
Specifies whether to send the e-mail when an error returns from the query specified in the @query
argument. append_query_error is bit, with a default of 0. When this parameter is 1, Database Mail sends
the e-mail message and includes the query error message in the body of the e-mail message. When this
parameter is 0, Database Mail does not send the e-mail message, and sp_send_dbmail ends with return
code 1, indicating failure.
[ @query_no_truncate= ] query_no_truncate
Specifies whether to execute the query with the option that avoids truncation of large variable length data
types (varchar(max), nvarchar(max), varbinary(max), xml, text, ntext, image, and user-defined data
types). When set, query results do not include column headers. The query_no_truncate value is of type bit.
When the value is 0 or not specified, columns in the query truncate to 256 characters. When the value is 1,
columns in the query are not truncated. This parameter defaults to 0.

NOTE
When used with large amounts of data, the @query_no_truncate option consumes additional resources and can slow
server performance.

[ @query_result_no_padding ] @query_result_no_padding
The type is bit. The default is 0. When you set to 1, the query results are not padded, possibly reducing the file
size.If you set @query_result_no_padding to 1 and you set the @query_result_width parameter, the
@query_result_no_padding parameter overwrites the @query_result_width parameter.
In this case no error occurs.
If you set the @query_result_no_padding to 1 and you set the @query_no_truncate parameter, an error is raised.
[ @mailitem_id= ] mailitem_id [ OUTPUT ]
Optional output parameter returns the mailitem_id of the message. The mailitem_id is of type int.

Return Code Values


A return code of 0 means success. Any other value means failure. The error code for the statement that failed is
stored in the @@ERROR variable.

Result Sets
On success, returns the message "Mail queued."

Remarks
Before use, Database Mail must be enabled using the Database Mail Configuration Wizard, or sp_configure.
sysmail_stop_sp stops Database Mail by stopping the Service Broker objects that the external program uses.
sp_send_dbmail still accepts mail when Database Mail is stopped using sysmail_stop_sp. To start Database Mail,
use sysmail_start_sp.
When @profile is not specified, sp_send_dbmail uses a default profile. If the user sending the e-mail message
has a default private profile, Database Mail uses that profile. If the user has no default private profile,
sp_send_dbmail uses the default public profile. If there is no default private profile for the user and no default
public profile, sp_send_dbmail returns an error.
sp_send_dbmail does not support e-mail messages with no content. To send an e-mail message, you must
specify at least one of @body, @query, @file_attachments, or @subject. Otherwise, sp_send_dbmail returns
an error.
Database Mail uses the Microsoft Windows security context of the current user to control access to files. Therefore,
users who are authenticated with SQL Server Authentication cannot attach files using @file_attachments.
Windows does not allow SQL Server to provide credentials from a remote computer to another remote computer.
Therefore, Database Mail may not be able to attach files from a network share in cases where the command is run
from a computer other than the computer that SQL Server runs on.
If both @query and @file_attachments are specified and the file cannot be found, the query is still executed but
the e-mail is not sent.
When a query is specified, the result set is formatted as inline text. Binary data in the result is sent in hexadecimal
format.
The parameters @recipients, @copy_recipients, and @blind_copy_recipients are semicolon-delimited lists of
e-mail addresses. At least one of these parameters must be provided, or sp_send_dbmail returns an error.
When executing sp_send_dbmail without a transaction context, Database Mail starts and commits an implicit
transaction. When executing sp_send_dbmail from within an existing transaction, Database Mail relies on the user
to either commit or roll back any changes. It does not start an inner transaction.

Permissions
Execute permissions for sp_send_dbmail default to all members of the DatabaseMailUser database role in the
msdb database. However, when the user sending the message does not have permission to use the profile for the
request, sp_send_dbmail returns an error and does not send the message.

Examples
A. Sending an e -mail message
This example sends an e-mail message to your friend using the e-mail address myfriend@Adventure-Works.com . The
message has the subject Automated Success Message . The body of the message contains the sentence
'The stored procedure finished successfully' .

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Adventure Works Administrator',
@recipients = 'yourfriend@Adventure-Works.com',
@body = 'The stored procedure finished successfully.',
@subject = 'Automated Success Message' ;

B. Sending an e -mail message with the results of a query


This example sends an e-mail message to your friend using the e-mail address yourfriend@Adventure-Works.com .
The message has the subject Work Order Count , and executes a query that shows the number of work orders with a
DueDate less than two days after April 30, 2004. Database Mail attaches the result as a text file.

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Adventure Works Administrator',
@recipients = 'yourfriend@Adventure-Works.com',
@query = 'SELECT COUNT(*) FROM AdventureWorks2012.Production.WorkOrder
WHERE DueDate > ''2004-04-30''
AND DATEDIFF(dd, ''2004-04-30'', DueDate) < 2' ,
@subject = 'Work Order Count',
@attach_query_result_as_file = 1 ;

C. Sending an HTML e -mail message


This example sends an e-mail message to your friend using the e-mail address yourfriend@Adventure-Works.com .
The message has the subject Work Order List , and contains an HTML document that shows the work orders with a
DueDate less than two days after April 30, 2004. Database Mail sends the message in HTML format.
DECLARE @tableHTML NVARCHAR(MAX) ;

SET @tableHTML =
N'<H1>Work Order Report</H1>' +
N'<table border="1">' +
N'<tr><th>Work Order ID</th><th>Product ID</th>' +
N'<th>Name</th><th>Order Qty</th><th>Due Date</th>' +
N'<th>Expected Revenue</th></tr>' +
CAST ( ( SELECT td = wo.WorkOrderID, '',
td = p.ProductID, '',
td = p.Name, '',
td = wo.OrderQty, '',
td = wo.DueDate, '',
td = (p.ListPrice - p.StandardCost) * wo.OrderQty
FROM AdventureWorks.Production.WorkOrder as wo
JOIN AdventureWorks.Production.Product AS p
ON wo.ProductID = p.ProductID
WHERE DueDate > '2004-04-30'
AND DATEDIFF(dd, '2004-04-30', DueDate) < 2
ORDER BY DueDate ASC,
(p.ListPrice - p.StandardCost) * wo.OrderQty DESC
FOR XML PATH('tr'), TYPE
) AS NVARCHAR(MAX) ) +
N'</table>' ;

EXEC msdb.dbo.sp_send_dbmail @recipients='yourfriend@Adventure-Works.com',


@subject = 'Work Order List',
@body = @tableHTML,
@body_format = 'HTML' ;

See Also
Database Mail
Database Mail Configuration Objects
Database Mail Stored Procedures (Transact-SQL)
sp_addrolemember (Transact-SQL)
sysmail_add_account_sp (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a new Database Mail account holding information about an SMTP account.
Transact-SQL Syntax Conventions

Syntax
sysmail_add_account_sp [ @account_name = ] 'account_name',
[ @email_address = ] 'email_address' ,
[ [ @display_name = ] 'display_name' , ]
[ [ @replyto_address = ] 'replyto_address' , ]
[ [ @description = ] 'description' , ]
[ @mailserver_name = ] 'server_name'
[ , [ @mailserver_type = ] 'server_type' ]
[ , [ @port = ] port_number ]
[ , [ @username = ] 'username' ]
[ , [ @password = ] 'password' ]
[ , [ @use_default_credentials = ] use_default_credentials ]
[ , [ @enable_ssl = ] enable_ssl ]
[ , [ @account_id = ] account_id OUTPUT ]

Arguments
[ @account_name = ] 'account_name'
The name of the account to add. account_name is sysname, with no default.
[ @email_address = ] 'email_address'
The e-mail address to send the message from. This address must be an internet e-mail address. email_address is
nvarchar(128), with no default. For example, an account for SQL Server Agent may send e-mail from the address
SqlAgent@Adventure-Works.com.
[ @display_name = ] 'display_name'
The display name to use on e-mail messages from this account. display_name is nvarchar(128), with a default of
NULL. For example, an account for SQL Server Agent may display the name SQL Server Agent Automated
Mailer on e-mail messages.
[ @replyto_address = ] 'replyto_address'
The address that responses to messages from this account are sent to. replyto_address is nvarchar(128), with a
default of NULL. For example, replies to an account for SQL Server Agent may go to the database administrator,
danw@Adventure-Works.com.
[ @description = ] 'description'
Is a description for the account. description is nvarchar(256), with a default of NULL.
[ @mailserver_name = ] 'server_name'
The name or IP address of the SMTP mail server to use for this account. The computer that runs SQL Server must
be able to resolve the server_name to an IP address. server_name is sysname, with no default.
[ @mailserver_type = ] 'server_type'
The type of e-mail server. server_type is sysname, with a default of 'SMTP'..
[ @port = ] port_number
The port number for the e-mail server. port_number is int, with a default of 25.
[ @username = ] 'username'
The user name to use to log on to the e-mail server. username is nvarchar(128), with a default of NULL. When this
parameter is NULL, Database Mail does not use authentication for this account. If the mail server does not require
authentication, use NULL for the username.
[ @password = ] 'password'
The password to use to log on to the e-mail server. password is nvarchar(128), with a default of NULL. There is no
need to provide a password unless a username is specified.
[ @use_default_credentials = ] use_default_credentials
Specifies whether to send the mail to the SMTP server using the credentials of the SQL Server Database Engine.
use_default_credentials is bit, with a default of 0. When this parameter is 1, Database Mail uses the credentials of
the Database Engine. When this parameter is 0, Database Mail sends the @username and @password
parameters if present, otherwise sends mail without @username and @password parameters.
[ @enable_ssl = ] enable_ssl
Specifies whether Database Mail encrypts communication using Secure Sockets Layer. Enable_ssl is bit, with a
default of 0.
[ @account_id = ] account_id OUTPUT
Returns the account id for the new account. account_id is int, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
Database Mail provides separate parameters for @email_address, @display_name, and @replyto_address. The
@email_address parameter is the address from which the message is sent. The @display_name parameter is the
name shown in the From: field of the e-mail message. The @replyto_address parameter is the address where
replies to the e-mail message will be sent. For example, an account used for SQL Server Agent may send e-mail
messages from an e-mail address that is only used for SQL Server Agent. Messages from that address should
display a friendly name, so recipients can easily determine that SQL Server Agent sent the message. If a recipient
replies to the message, the reply should go to the database administrator rather than the address used by SQL
Server Agent. For this scenario, the account uses SqlAgent@Adventure-Works.com as the e-mail address. The
display name is set to SQL Server Agent Automated Mailer. The account uses danw@Adventure-Works.com
as the reply to address, so replies to messages sent from this account go to the database administrator rather than
the e-mail address for SQL Server Agent. By providing independent settings for these three parameters, Database
Mail allows you to configure messages to suit your needs.
The @mailserver_type parameter supports the value 'SMTP'.
When @use_default_credentials is 1 mail is sent to the SMTP server using the credentials of the SQL Server
Database Engine. When @use_default_credentials is 0 and a @username and @password are specified for an
account, the account uses SMTP authentication. The @username and @password are the credentials the account
uses for the SMTP server, not credentials for SQL Server or the network that the computer is on.
The stored procedure sysmail_add_account_sp is in the msdb database and is owned by the dbo schema. The
procedure must be executed with a three-part name if the current database is not msdb.
Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
The following example creates an account named AdventureWorks Administrator . The account uses the e-mail
address dba@Adventure-Works.com and sends mail to the SMTP mail server smtp.Adventure-Works.com . E-mail
messages sent from this account show AdventureWorks Automated Mailer on the From: line of the message. Replies
to the messages are directed to danw@Adventure-Works.com .

EXECUTE msdb.dbo.sysmail_add_account_sp
@account_name = 'AdventureWorks Administrator',
@description = 'Mail account for administrative e-mail.',
@email_address = 'dba@Adventure-Works.com',
@display_name = 'AdventureWorks Automated Mailer',
@mailserver_name = 'smtp.Adventure-Works.com' ;

See Also
Database Mail
Create a Database Mail Account
Database Mail Stored Procedures (Transact-SQL)
sysmail_add_principalprofile_sp (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Grants permission for a database user or role to use a Database Mail profile.
Transact-SQL Syntax Conventions

Syntax
sysmail_add_principalprofile_sp { [ @principal_id = ] principal_id | [ @principal_name = ] 'principal_name' }
,
{ [ @profile_id = ] profile_id | [ @profile_name = ] 'profile_name' }
[ , [ @is_default ] = 'is_default' ]

Arguments
[ @principal_id = ] principal_id
The ID of the database user or role in the msdb database for the association. principal_id is int, with a default of
NULL. Either principal_id or principal_name must be specified. A principal_id of 0 makes this profile a public
profile, granting access to all principals in the database.
[ @principal_name = ] 'principal_name'
The name of the database user or role in the msdb database for the association. principal_name is sysname, with
a default of NULL. Either principal_id or principal_name must be specified. A principal_name of 'public' makes
this profile a public profile, granting access to all principals in the database.
[ @profile_id = ] profile_id
The id of the profile for the association. profile_id is int, with a default of NULL. Either profile_id or profile_name
must be specified.
[ @profile_name = ] 'profile_name'
The name of the profile for the association. profile_name is sysname, with no default. Either profile_id or
profile_name must be specified.
[ @is_default = ] is_default
Specifies whether this profile is the default profile for the principal. A principal must have exactly one default
profile. is_default is bit, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
To make a profile public, specify a @principal_id of 0 or a @principal_name of public. A public profile is
available to all users in the msdb database, though users must also be a member of DatabaseMailUserRole to
execute sp_send_dbmail.
A database user may only have one default profile. When @is_default is '1' and the user is already associated with
one or more profiles, the specified profile becomes the default profile for the user. The profile that was previously
the default profile is still associated with the user, but is no longer the default profile.
When @is_default is '0' and no other association exists, the stored procedure returns an error.
The stored procedure sysmail_add_principalprofile_sp is in the msdb database and is owned by the dbo
schema. The procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
A. Creating an association, setting the default profile
The following example creates an association between the profile named AdventureWorks Administrator Profile
and the msdb database user ApplicationUser . The profile is the default profile for the user.

EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@principal_name = 'ApplicationUser',
@profile_name = 'AdventureWorks Administrator Profile',
@is_default = 1 ;

B. Making a profile the default public profile


The following example makes the profile AdventureWorks Public Profile the default public profile for users in the
msdb database.

EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@principal_name = 'public',
@profile_name = 'AdventureWorks Public Profile',
@is_default = 1 ;

See Also
Database Mail
Database Mail Configuration Objects
Database Mail Stored Procedures (Transact-SQL)
sysmail_add_profile_sp (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Creates a new Database Mail profile.
Transact-SQL Syntax Conventions

Syntax
sysmail_add_profile_sp [ @profile_name = ] 'profile_name'
[ , [ @description = ] 'description' ]
[ , [ @profile_id = ] new_profile_id OUTPUT ]

Arguments
[ @profile_name = ] 'profile_name'
The name for the new profile. profile_name is sysname, with no default.
[ @description = ] 'description'
The optional description for the new profile. description is nvarchar(256), with no default.
[ @profile_id = ] new_profile_idOUTPUT
Returns the ID for the new profile. new_profile_id is int, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
A Database Mail profile holds any number of Database Mail accounts. Database Mail stored procedures can refer to
a profile by either the profile name or the profile id generated by this procedure. For more information about
adding an account to a profile, see sysmail_add_profileaccount_sp (Transact-SQL).
The profile name and description can be changed with the stored procedure sysmail_update_profile_sp, while
the profile id remains constant for the life of the profile.
The profile name must be unique for the Microsoft SQL Server Database Engine or the stored procedure returns an
error.
The stored procedure sysmail_add_profile_sp is in the msdb database and is owned by the dbo schema. The
procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
A. Creating a new profile
The following example creates a new Database Mail profile named AdventureWorks Administrator .

EXECUTE msdb.dbo.sysmail_add_profile_sp
@profile_name = 'AdventureWorks Administrator',
@description = 'Profile used for administrative mail.' ;

B. Creating a new profile, saving the profile id in a variable


The following example creates a new Database Mail profile named AdventureWorks Administrator . The example
stores the profile id number in the variable @profileId and returns a result set containing the profile id number
for the new profile.

DECLARE @profileId INT ;

EXECUTE msdb.dbo.sysmail_add_profile_sp
@profile_name = 'AdventureWorks Administrator',
@description = 'Profile used for administrative mail.',
@profile_id = @profileId OUTPUT ;

SELECT @profileId ;

See Also
Database Mail
Create a Database Mail Account
Database Mail Configuration Objects
Database Mail Stored Procedures (Transact-SQL)
sysmail_add_profileaccount_sp (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a Database Mail account to a Database Mail profile. Execute sysmail_add_profileaccount_sp after a
Database Account is created with sysmail_add_account_sp (Transact-SQL), and a Database Profile is created with
sysmail_add_profile_sp (Transact-SQL).
Transact-SQL Syntax Conventions

Syntax
sysmail_add_profileaccount_sp { [ @profile_id = ] profile_id | [ @profile_name = ] 'profile_name' } ,
{ [ @account_id = ] account_id | [ @account_name = ] 'account_name' }
[ , [ @sequence_number = ] sequence_number ]

Arguments
[ @profile_id = ] profile_id
The profile id to add the account to. profile_id is int, with a default of NULL. Either the profile_id or the
profile_name must be specified.
[ @profile_name = ] 'profile_name'
The profile name to add the account to. profile_name is sysname, with a default of NULL. Either the profile_id or
the profile_name must be specified.
[ @account_id = ] account_id
The account id to add to the profile. account_id is int, with a default of NULL. Either the account_id or the
account_name must be specified.
[ @account_name = ] 'account_name'
The name of the account to add to the profile. account_name is sysname, with a default of NULL. Either the
account_id or the account_name must be specified.
[ @sequence_number = ] sequence_number
The sequence number of the account within the profile. sequence_number is int, with no default. The sequence
number determines the order in which accounts are used in the profile.

Return Code Values


0 (success) or 1 (failure)

Remarks
Both the profile and the account must already exist. Otherwise, the stored procedure returns an error.
Notice that this stored procedure does not change the sequence number of an account already associated with the
specified profile. For more information about updating the sequence number of an account, see
sysmail_update_profileaccount_sp (Transact-SQL).
The sequence number determines the order in which Database Mail uses accounts in the profile. For a new e-mail
message, Database Mail starts with the account that has the lowest sequence number. Should that account fail,
Database Mail uses the account with the next highest sequence number, and so on until either Database Mail sends
the message successfully, or the account with the highest sequence number fails. If the account with the highest
sequence number fails, the Database Mail pauses attempts to send the mail for the amount of time configured in
the AccountRetryDelay parameter of sysmail_configure_sp, then starts the process of attempting to send the
mail again, starting with the lowest sequence number. Use the AccountRetryAttempts parameter of
sysmail_configure_sp, to configure the number of times that the external mail process attempts to send the e-
mail message using each account in the specified profile.
If more than one account exists with the same sequence number, Database Mail will only use one of those
accounts for a given e-mail message. In this case, Database Mail makes no guarantees as to which of the accounts
is used for that sequence number or that the same account is used from message to message.
The stored procedure sysmail_add_profileaccount_sp is in the msdb database and is owned by the dbo
schema. The procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
The following example associates the profile AdventureWorks Administrator with the account Audit Account . The
audit account has a sequence number of 1.

EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = 'AdventureWorks Administrator',
@account_name = 'Audit Account',
@sequence_number = 1 ;

See Also
Database Mail
Create a Database Mail Account
Database Mail Configuration Objects
Database Mail Stored Procedures (Transact-SQL)
sysmail_configure_sp (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes configuration settings for Database Mail. The configuration settings specified with sysmail_configure_sp
apply to the entire SQL Server instance.
Transact-SQL Syntax Conventions

Syntax
sysmail_configure_sp [ [ @parameter_name = ] 'parameter_name' ]
[ , [ @parameter_value = ] 'parameter_value' ]
[ , [ @description = ] 'description' ]

Arguments
[@parameter_name = ] 'parameter_name'
The name of the parameter to change.
[@parameter_value = ] 'parameter_value'
The new value of the parameter.
[@description = ] 'description'
A description of the parameter.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Database Mail uses the following parameters:

Parameter name Description Default Value

AccountRetryAttempts The number of times that the external 1


mail process attempts to send the e-
mail message using each account in the
specified profile.
AccountRetryDelay The amount of time, in seconds, for the 5000
external mail process to wait between
attempts to send a message.

DatabaseMailExeMinimumLifeTime The minimum amount of time, in 600


seconds, that the external mail process
remains active. When Database Mail is
sending many messages, increase this
value to keep Database Mail active and
avoid the overhead of frequent starts
and stops.

DefaultAttachmentEncoding The default encoding for e-mail MIME


attachments.

MaxFileSize The maximum size of an attachment, in 1000000


bytes.

ProhibitedExtensions A comma-separated list of extensions exe,dll,vbs,js


which cannot be sent as an attachment
to an e-mail message.

LoggingLevel Specify which messages are recorded in 2


the Database Mail log. One of the
following numeric values:

1 - This is normal mode. Logs only


errors.

2 - This is extended mode. Logs errors,


warnings, and informational messages.

3 - This is verbose mode. Logs errors,


warnings, informational messages,
success messages, and additional
internal messages. Use this mode for
troubleshooting.

The stored procedure sysmail_configure_sp is in the msdb database and is owned by the dbo schema. The
procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
A. Setting Database Mail to retry each account 10 times
The following example shows setting Database Mail to retry each account ten times before considering the account
to be unreachable.

EXECUTE msdb.dbo.sysmail_configure_sp
'AccountRetryAttempts', '10' ;

B. Setting the maximum attachment size to two megabytes


The following example shows setting the maximum attachment size to 2 megabytes.

EXECUTE msdb.dbo.sysmail_configure_sp
'MaxFileSize', '2097152' ;

See Also
Database Mail
sysmail_help_configure_sp (Transact-SQL)
Database Mail Stored Procedures (Transact-SQL)
sysmail_delete_account_sp (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes a Database Mail SMTP account. You can also use the Database Mail Configuration Wizard to delete an
account.
Transact-SQL Syntax Conventions

Syntax
sysmail_delete_account_sp { [ @account_id = ] account_id | [ @account_name = ] 'account_name' }

Arguments
[ @account_id = ] account_id
The ID number of the account to delete. account_id is int, with no default. Either account_id or account_name must
be specified.
[ @account_name = ] 'account_name'
The name of the account to delete. account_name is sysname, with no default. Either account_id or account_name
must be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
This procedure deletes the account specified, regardless of whether the account is in use by a profile. A profile that
contains no accounts cannot successfully send e-mail.
The stored procedure sysmail_delete_account_sp is in the msdb database and is owned by the dbo schema. The
procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
The following example shows deleting the Database Mail account named AdventureWorks Administrator .
EXECUTE msdb.dbo.sysmail_delete_account_sp
@account_name = 'AdventureWorks Administrator' ;

See Also
Database Mail
Create a Database Mail Account
Database Mail Configuration Objects
sysmail_add_account_sp (Transact-SQL)
sysmail_delete_profile_sp (Transact-SQL)
sysmail_delete_profileaccount_sp (Transact-SQL)
sysmail_help_account_sp (Transact-SQL)
sysmail_help_profile_sp (Transact-SQL)
sysmail_help_profileaccount_sp (Transact-SQL)
sysmail_update_profileaccount_sp (Transact-SQL)
sysmail_delete_log_sp (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes events from the Database Mail log. Deletes all events in the log or those events meeting a date or type
criteria.
Transact-SQL Syntax Conventions

Syntax
sysmail_delete_log_sp [ [ @logged_before = ] 'logged_before' ]
[, [ @event_type = ] 'event_type' ]

Arguments
[ @logged_before = ] 'logged_before'
Deletes entries up to the date and time specified by the logged_before argument. logged_before is datetime with
NULL as default. NULL indicates all dates.
[ @event_type = ] 'event_type'
Deletes log entries of the type specified as the event_type. event_type is varchar(15) with no default. Valid entries
are success, warning, error, and informational. NULL indicates all event types.

Return Code Values


0 (success) or 1 (failure)

Remarks
Use the sysmail_delete_log_sp stored procedure to permanently delete entries from the Database Mail log. An
optional argument allows you to delete only the older records by providing a date and time. Events older than that
argument will be deleted. An optional argument allows you to delete only events of a certain type, specified as the
event_type argument.
Deleting entries in the Database Mail log does not delete the e-mails entries from the Database Mail tables. Use
sysmail_delete_mailitems_sp to delete e-mail from the Database Mail tables.

Permissions
Only members of the sysadmin fixed server role can access this procedure.

Examples
A. Deleting all events
The following example deletes all events in the Database Mail log.
EXECUTE msdb.dbo.sysmail_delete_log_sp ;
GO

B. Deleting the oldest events


The following example deletes events in the Database Mail log that are older than October 9, 2005.

EXECUTE msdb.dbo.sysmail_delete_log_sp
@logged_before = 'October 9, 2005' ;
GO

C. Deleting all events of a certain type


The following example deletes success messages in the Database Mail log.

EXECUTE msdb.dbo.sysmail_delete_log_sp
@event_type = 'success' ;
GO

See Also
sysmail_event_log (Transact-SQL)
sysmail_delete_mailitems_sp (Transact-SQL)
Create a SQL Server Agent Job to Archive Database Mail Messages and Event Logs
sysmail_delete_mailitems_sp (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Permanently deletes e-mail messages from the Database Mail internal tables.
Transact-SQL Syntax Conventions

Syntax
sysmail_delete_mailitems_sp [ [ @sent_before = ] 'sent_before' ]
[ , [ @sent_status = ] 'sent_status' ]

Arguments
[ @sent_before= ] 'sent_before'
Deletes e-mails up to the date and time provided as the sent_before argument. sent_before is datetime with NULL
as default. NULL indicates all dates.
[ @sent_status= ] 'sent_status'
Deletes e-mails of the type specified by sent_status. sent_status is varchar(8) with no default. Valid entries are
sent, unsent, retrying, and failed. NULL indicates all statuses.

Return Code Values


0 (success) or 1 (failure)

Remarks
Database Mail messages and their attachments are stored in the msdb database. Messages should be periodically
deleted to prevent msdb from growing larger than expected and to comply with your organizations document
retention program. Use the sysmail_delete_mailitems_sp stored procedure to permanently delete e-mail
messages from the Database Mail tables. An optional argument allows you to delete only older e-mails by
providing a date and time. E-mails older than that argument will be deleted. Another optional argument allows
you to delete only e-mails of a certain type, specified as the sent_status argument. You must provide an argument
either for @sent_before or @sent_status. To delete all messages, use @sent_before = getdate().
Deleting e-mail also deletes attachments related to those messages. Deleting e-mail does not delete the
corresponding entries in sysmail_event_log. Use sysmail_delete_log_sp to delete items from the log.

Permissions
By default, this stored procedure is granted for execution to members off the sysadmin fixed server role and
DatabaseMailUserRole. Members of the sysadmin fixed server role can execute this procedure to delete e-mails
sent by all users. Members of DatabaseMailUserRole can only delete e-mails sent by that user.

Examples
A. Deleting all e -mails
The following example deletes all e-mails in the Database Mail system.

DECLARE @GETDATE datetime


SET @GETDATE = GETDATE();
EXECUTE msdb.dbo.sysmail_delete_mailitems_sp @sent_before = @GETDATE;
GO

B. Deleting the oldest e -mails


The following example deletes e-mails in the Database Mail log that are older than October 9, 2005 .

EXECUTE msdb.dbo.sysmail_delete_mailitems_sp
@sent_before = 'October 9, 2005' ;
GO

C. Deleting all e -mails of a certain type


The following example deletes all failed e-mails in the Database Mail log.

EXECUTE msdb.dbo.sysmail_delete_mailitems_sp
@sent_status = 'failed' ;
GO

See Also
sysmail_allitems (Transact-SQL)
sysmail_event_log (Transact-SQL)
sysmail_mailattachments (Transact-SQL)
Create a SQL Server Agent Job to Archive Database Mail Messages and Event Logs
sysmail_delete_principalprofile_sp (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes permission for a database user or role to use a public or private Database Mail profile.
Transact-SQL Syntax Conventions

Syntax
sysmail_delete_principalprofile_sp { [ @principal_id = ] principal_id | [ @principal_name = ]
'principal_name' } ,
{ [ @profile_id = ] profile_id | [ @profile_name = ] 'profile_name' }

Arguments
[ @principal_id = ] principal_id
Is the ID of the database user or role in the msdb database for the association to delete. principal_id is int, with a
default of NULL. To make a public profile into a private profile, provide the principal ID 0 or the principal name
'public'. Either principal_id or principal_name must be specified.
[ @principal_name = ] 'principal_name'
Is the name of the database user or role in the msdb database for the association to delete. principal_name is
sysname, with a default of NULL. To make a public profile into a private profile, provide the principal ID 0 or the
principal name 'public'. Either principal_id or principal_name must be specified.
[ @profile_id = ] profile_id
Is the ID of the profile for the association to delete. profile_id is int, with a default of NULL. Either profile_id or
profile_name must be specified.
[ @profile_name = ] 'profile_name'
Is the name of the profile for the association to delete. profile_name is sysname, with a default of NULL. Either
profile_id or profile_name must be specified.

Return Code Values


0 (success) or 1 (failure)

Remarks
To make a public profile into a private profile, provide 'public' for the principal name or 0 for the principal id.
Use caution when removing permissions for the default private profile for a user or the default public profile. When
no default profile is available, sp_send_dbmail requires the name of a profile as an argument. Therefore,
removing a default profile may cause calls to sp_send_dbmail to fail. For more information, see sp_send_dbmail
(Transact-SQL).
The stored procedure sysmail_delete_principalprofile_sp is in the msdb database and is owned by the dbo
schema. The procedure must be executed with a three-part name if the current database is not msdb.
Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
The following example shows deleting the association between the profile AdventureWorks Administrator and
the login ApplicationUser in the msdb database.

EXECUTE msdb.dbo.sysmail_delete_principalprofile_sp
@principal_name = 'ApplicationUser',
@profile_name = 'AdventureWorks Administrator' ;

See Also
Database Mail
Database Mail Configuration Objects
Database Mail Stored Procedures (Transact-SQL)
sysmail_delete_profile_sp (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes a mail profile used by Database Mail.
Transact-SQL Syntax Conventions

Syntax
sysmail_delete_profile_sp { [ @profile_id = ] profile_id | [ @profile_name = ] 'profile_name' }

Arguments
[ @profile_id = ] profile_id
Is the profile id of the profile to be deleted. profile_id is int, with a default of NULL. Either profile_id or
profile_name must be specified.
[ @profile_name = ] 'profile_name'
Is the name of the profile to be deleted. profile_name is sysname, with a default of NULL. Either profile_id or
profile_name must be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Deleting a profile does not delete the accounts used by the profile.
This stored procedure deletes the profile regardless of whether users have access to the profile. Use caution when
removing the default private profile for a user or the default public profile for the msdb database. When no default
profile is available, sp_send_dbmail requires the name of a profile as an argument. Therefore, removing a default
profile may cause calls to sp_send_dbmail to fail. For more information, see sp_send_dbmail (Transact-SQL).
The stored procedure sysmail_delete_profile_sp is in the msdb database and is owned by the dbo schema. The
procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
The following example shows deleting the profile named AdventureWorks Administrator .

EXECUTE msdb.dbo.sysmail_delete_profile_sp
@profile_name = 'AdventureWorks Administrator' ;

See Also
Database Mail
Database Mail Configuration Objects
Database Mail Stored Procedures (Transact-SQL)
sysmail_delete_profileaccount_sp (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes an account from a Database Mail profile.
Transact-SQL Syntax Conventions

Syntax
sysmail_delete_profileaccount_sp { [ @profile_id = ] profile_id | [ @profile_name = ] 'profile_name' } ,
{ [ @account_id = ] account_id | [ @account_name = ] 'account_name' }

Arguments
[ @profile_id = ] profile_id
The profile ID of the profile to delete. profile_id is int, with a default of NULL. Either the profile_id or the
profile_name may be specified.
[ @profile_name = ] 'profile_name'
The profile name of the profile to delete. profile_name is sysname, with a default of NULL. Either the profile_id or
the profile_name may be specified.
[ @account_id = ] account_id
The account ID to delete. account_id is int, with a default of NULL. Either the account_id or the account_name may
be specified.
[ @account_name = ] 'account_name'
The name of the account to delete. account_name is sysname, with a default of NULL. Either the account_id or the
account_name may be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Returns an error if the account specified is not associated with the profile specified.
When an account is specified but no profile is specified, this stored procedure removes the specified account from
all profiles. For example, if you are preparing to shut down an existing SMTP server, you remove accounts that use
that SMTP server from all profiles, rather than removing each account from each profile.
When a profile is specified but no account is specified, this stored procedure removes all accounts from the
specified profile. For example, if you are changing the SMTP servers a profile uses, it may be convenient to remove
all accounts from the profile and then add new accounts as necessary.
The stored procedure sysmail_delete_profileaccount_sp is in the msdb database and is owned by the dbo
schema. The procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
The following example shows removing the account Audit Account from the profile AdventureWorks Administrator
.

EXECUTE msdb.dbo.sysmail_delete_profileaccount_sp
@profile_name = 'AdventureWorks Administrator',
@account_name = 'Audit Account' ;

See Also
Database Mail
Create a Database Mail Account
Database Mail Configuration Objects
Database Mail Stored Procedures (Transact-SQL)
sysmail_help_account_sp (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Lists information (except passwords) about Database Mail accounts.
Transact-SQL Syntax Conventions

Syntax
sysmail_help_account_sp [ [ @account_id = ] account_id | [ @account_name = ] 'account_name' ]

Arguments
[ @account_id = ] account_id
The account ID of the account to list information for. account_id is int, with a default of NULL.
[ @account_name = ] 'account_name'
The name of the account to list information for. account_name is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Returns a result set containing the columns listed below.

Column name Data type Description

account_id int The ID of the account.

name sysname The name of the account.

description nvarchar(256) The description for the account.

email_address nvarchar(128) The e-mail address to send messages


from.

display_name nvarchar(128) The display name for the account.

replyto_address nvarchar(128) The address where replies to messages


from this account are sent.

servertype sysname The type of e-mail server for the


account.
servername sysname The name of the e-mail server for the
account.

port int The port number of the e-mail server


uses.

username nvarchar(128) The user name to use to sign in to the


e-mail server, if the e-mail server uses
authentication. When username is
NULL, Database Mail does not use
authentication for this account.

use_default_credentials bit Specifies whether to send the mail to


the SMTP server using the credentials
of the SQL Server Database Engine.
use_default_credentials is bit, with no
default. When this parameter is 1,
Database Mail uses the credentials of
the SQL Server Database Engine service.
When this parameter is 0, Database
Mail uses the @username and
@password for authentication on the
SMTP server. If @username and
@password are NULL, then Database
Mail uses anonymous authentication.
Consult you SMTP administrator before
specifying this parameter.

enable_ssl bit Specifies whether Database Mail


encrypts communication using Secure
Sockets Layer (SSL). Use this option if
SSL is required on your SMTP server.
enable_ssl is bit, with no default. 1
indicates Database Mail encrypts
communication using SSL. 0 indicates
Database Mail sends the mail without
SSL encryption.

Remarks
When no account_id or account_name is provided, sysmail_help_account lists information on all Database Mail
accounts in the Microsoft SQL Server instance.
The stored procedure sysmail_help_account_sp is in the msdb database and is owned by the dbo schema. The
procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
A. Listing the information for all accounts
The following example shows listing the account information for all accounts in the instance.
EXECUTE msdb.dbo.sysmail_help_account_sp ;

Here is a sample result set, edited for line length:

account_id name description email_address


display_name replyto_address servertype servername port username
use_default_credentials enable_ssl
----------- ---------------------------- --------------------------------------- ------------------------- ---
----------------------------- --------------- ---------- ------------------------- ----------- -------- ------
----------------- ----------
148 AdventureWorks Administrator Mail account for administrative e-mail. dba@Adventure-Works.com
AdventureWorks Automated Mailer NULL SMTP smtp.Adventure-Works.com 25 NULL 0
0
149 Audit Account Account for audit e-mail. audit@Adventure-Works.com
Automated Mailer (Audit) NULL SMTP smtp.Adventure-Works.com 25 NULL 0
0

B. Listing the information for a specific account


The following example shows listing the account information for the account named AdventureWorks Administrator
.

EXECUTE msdb.dbo.sysmail_help_account_sp
@account_name = 'AdventureWorks Administrator' ;

Here is a sample result set, edited for line length:

account_id name description email_address


display_name replyto_address servertype servername port username
use_default_credentials enable_ssl
----------- ---------------------------- ------------------------------------------------------ --------------
----------- ---------------- ---------- ------------------------- ----------- -------- -----------------------
----------
148 AdventureWorks Administrator Mail account for administrative e-mail. dba@Adventure-Works.com
AdventureWorks Automated Mailer NULL SMTP smtp.Adventure-Works.com 25 NULL 0
0

See Also
Database Mail
Create a Database Mail Account
Database Mail Stored Procedures (Transact-SQL)
sysmail_help_configure_sp (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Displays configuration settings for Database Mail.
Transact-SQL Syntax Conventions

Syntax
sysmail_help_configure_sp [ [ @parameter_name = ] 'parameter_name' ]

Arguments
[@parameter_name = ] 'parameter_name'
The name of the configuration setting to retrieve. When specified, the value of the configuration setting is returned
in the @parameter_value OUTPUT parameter. When no @parameter_name is specified, this stored procedure
returns a result set containing all of the Database Mail configuration settings in the instance.

Return Code Values


0 (success) or 1 (failure)

Result Sets
When no @parameter_name is specified, returns a result set with the following columns.

Column name Data type Description

paramname nvarchar(256) The name of the configuration


parameter.

paramvalue nvarchar(256) The value of the configuration


parameter.

description nvarchar(256) A description of the configuration


parameter.

Remarks
The stored procedure sysmail_help_configure_sp lists the current Database Mail configuration settings for the
instance.
When a @parameter_name is specified, but no output parameter is provided for @parameter_value, this stored
procedure produces no output.
The stored procedure sysmail_help_configure_sp is in the msdb database and is owned by the dbo schema. The
procedure must be invoked with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
The following example shows listing the Database Mail configuration settings for the SQL Server instance.

EXECUTE msdb.dbo.sysmail_help_configure_sp ;

Here is a sample result set, edited for line length:

paramname paramvalue description


------------------------------- --------------- --------------------------------------------------------------
---------------
AccountRetryAttempts 1 Number of retry attempts for a mail server
AccountRetryDelay 5000 Delay between each retry attempt to mail server
DatabaseMailExeMinimumLifeTime 600 Minimum process lifetime in seconds
DefaultAttachmentEncoding MIME Default attachment encoding
LoggingLevel 2 Database Mail logging level: normal - 1, extended - 2
(default), verbose - 3
MaxFileSize 1000000 Default maximum file size
ProhibitedExtensions exe,dll,vbs,js Extensions not allowed in outgoing mails

See Also
Database Mail
Database Mail Stored Procedures (Transact-SQL)
sysmail_help_principalprofile_sp (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Lists information about associations between Database Mail profiles and database principals.
Transact-SQL Syntax Conventions

Syntax
sysmail_help_principalprofile_sp [ { [ @principal_id = ] principal_id | [ @principal_name = ]
'principal_name' } ]
[ [ , ] { [ @profile_id = ] profile_id | [ @profile_name = ] 'profile_name' } ]

Arguments
[ @principal_id= ] principal_id
Is the ID of the database user or role in the msdb database for the association to list. principal_id is int, with a
default of NULL. Either principal_id or principal_name may be specified.
[ @principal_name= ] 'principal_name'
Is the name of the database user or role in the msdb database for the association to list. principal_name is
sysname, with a default of NULL. Either principal_id or principal_name may be specified.
[ @profile_id= ] profile_id
Is the ID of the profile for the association to list. profile_id is int, with a default of NULL. Either profile_id or
profile_name may be specified.
[ @profile_name= ] 'profile_name'
Is the name of the profile for the association to list. profile_name is sysname, with a default of NULL. Either
profile_id or profile_name may be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Returns a result set that contains the columns listed in the following table.

Column name Data type Description

principal_id int The ID of the database user.

principal_name sysname The name of the database user.


profile_id int The ID number of the Database Mail
profile.

profile_name sysname The name of the Database Mail profile.

is_default bit The flag that states whether the profile


is the default profile for the user.

Remarks
If sysmail_help_principalprofile_sp is invoked without parameters, the result set returned lists all of the
associations in the instance of SQL Server. Otherwise, the result set contains information for associations that
match the provided parameters. For example, the procedure lists all of the associations for a profile when the
profile name is provided.
sysmail_help_principalprofile_sp is in the msdb database and is owned by the dbo schema. The procedure
must be executed with a three-part name if the current database is not msdb.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
A. Listing information for a specific association
The following example shows listing the information for all associations between the AdventureWorks Administrator
profile and the ApplicationLogin principal in the msdb database.

EXECUTE msdb.dbo.sysmail_help_principalprofile_sp
@principal_name = 'danw',
@profile_name = 'AdventureWorks Administrator' ;

Here is a sample result set, reformatted for line length.

principal_id principal_name profile_id profile_name is_default


------------ ------------------ ----------- ------------------------------ ----------
5 danw 9 AdventureWorks Administrator 1

B. Listing information for all associations


The following example shows listing the information for all associations in the instance.

EXECUTE msdb.dbo.sysmail_help_principalprofile_sp ;

Here is a sample result set, reformatted for line length.

principal_id principal_name profile_id profile_name is_default


------------ ------------------ ----------- ------------------------------ ----------
6 terrid 3 Product Update Profile 1
5 danw 9 AdventureWorks Administrator 1
See Also
Database Mail
Database Mail Stored Procedures (Transact-SQL)
sysmail_help_profile_sp (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Lists information about one or more mail profiles.
Transact-SQL Syntax Conventions

Syntax
sysmail_help_profile_sp [ [ @profile_id = ] profile_id | [ @profile_name = ] 'profile_name' ]

Arguments
[ @profile_id = ] profile_id
The profile id to return information for. profile_id is int, with a default of NULL.
[ @profile_name = ] 'profile_name'
The profile name to return information for. profile_name is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Returns a result set with the following columns.

Column name Data type Description

profile_id int The profile id for the profile.

name sysname The profile name for the profile.

description nvarchar(256) The description for the profile.

Remarks
When a profile name or profile id is specified, sysmail_help_profile_sp returns information about that profile.
Otherwise, sysmail_help_profile_sp returns information about every profile in the SQL Server instance.
The stored procedure sysmail_help_profile_sp is in the msdb database and is owned by the dbo schema. The
procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
A. Listing all profiles
The following example shows listing all profiles in the instance.

EXECUTE msdb.dbo.sysmail_help_profile_sp;

Here is a sample result set, reformatted for line length:

profile_id name description


----------- ----------------------------- ------------------------------
56 AdventureWorks Administrator Administrative mail profile.
57 AdventureWorks Operator Operator mail profile.

B. Listing a specific profile


The following example shows listing information for the profile AdventureWorks Administrator .

EXECUTE msdb.dbo.sysmail_help_profile_sp
@profile_name = 'AdventureWorks Administrator' ;

Here is a sample result set, reformatted for line length:

profile_id name description


----------- ----------------------------- ------------------------------
56 AdventureWorks Administrator Administrative mail profile.

See Also
Database Mail
Database Mail Stored Procedures (Transact-SQL)
sysmail_help_profileaccount_sp (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Lists the accounts associated with one or more Database Mail profiles.
Transact-SQL Syntax Conventions

Syntax
sysmail_help_profileaccount_sp
{ [ @profile_id = ] profile_id
| [ @profile_name = ] 'profile_name' }
[ , { [ @account_id = ] account_id
| [ @account_name = ] 'account_name' } ]

Arguments
[ @profile_id = ] profile_id
Is the profile ID of the profile to list. profile_id is int, with a default of NULL. Either profile_id or profile_name must
be specified.
[ @profile_name = ] 'profile_name'
Is the profile name of the profile to list. profile_name is sysname, with a default of NULL. Either profile_id or
profile_name must be specified.
[ @account_id = ] account_id
Is the account ID to list. account_id is int, with a default of NULL. When account_id and account_name are both
NULL, lists all the accounts in the profile.
[ @account_name = ] 'account_name'
Is the name of the account to list. account_name is sysname, with a default of NULL. When account_id and
account_name are both NULL, lists all the accounts in the profile.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Returns a result set with the following columns.

Column name Data type Description

profile_id int The profile ID of the profile.

profile_name sysname The name of the profile.


account_id int The account ID of the account.

account_name sysname The name of the account.

sequence_number int The sequence number of the account


within the profile.

Remarks
When no profile_id or profile_name is specified, this stored procedure returns information for every profile in the
instance.
The stored procedure sysmail_help_profileaccount_sp is in the msdb database and is owned by the dbo
schema. The procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
A. Listing the accounts for a specific profile by name
The following example shows listing the information for the AdventureWorks Administrator profile by specifying
the profile name.

EXECUTE msdb.dbo.sysmail_help_profileaccount_sp
@profile_name = 'AdventureWorks Administrator';

Here is a sample result set, edited for line length:

profile_id profile_name account_id account_name sequence_number


----------- ---------------------------- ----------- -------------------- ---------------
131 AdventureWorks Administrator 197 Admin-MainServer 1
131 AdventureWorks Administrator 198 Admin-BackupServer 2

B. Listing the accounts for a specific profile by profile ID


The following example shows listing the information for the AdventureWorks Administrator profile by specifying
the profile ID for the profile.

EXECUTE msdb.dbo.sysmail_help_profileaccount_sp
@profile_id = 131 ;

Here is a sample result set, edited for line length:

profile_id profile_name account_id account_name sequence_number


----------- ---------------------------- ----------- -------------------- ---------------
131 AdventureWorks Administrator 197 Admin-MainServer 1
131 AdventureWorks Administrator 198 Admin-BackupServer 2

C. Listing the accounts for all profiles


The following example shows listing the accounts for all profiles in the instance.

EXECUTE msdb.dbo.sysmail_help_profileaccount_sp;

Here is a sample result set, edited for line length:

profile_id profile_name account_id account_name sequence_number


----------- ---------------------------- ----------- -------------------- ---------------
131 AdventureWorks Administrator 197 Admin-MainServer 1
131 AdventureWorks Administrator 198 Admin-BackupServer 2
106 AdventureWorks Operator 210 Operator-MainServer 1

See Also
Database Mail
Create a Database Mail Account
Database Mail Configuration Objects
Database Mail Stored Procedures (Transact-SQL)
sysmail_help_queue_sp (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
There are two queues in Database Mail: the mail queue and status queue. The mail queue stores mail items that are
waiting to be sent. The status queue stores the status of items that have already been sent. This stored procedure
allows viewing the state of the mail or status queues. If the parameter @queue_type is not specified, the stored
procedure returns one row for each of the queues.
Transact-SQL Syntax Conventions

Syntax
sysmail_help_queue_sp [ @queue_type = ] 'queue_type'

Arguments
[ @queue_type = ] 'queue_type'
Optional argument deletes e-mails of the type specified as the queue_type. queue_type is nvarchar(6) with no
default. Valid entries are mail and status.

Return Code Values


0 (success) or 1 (failure)

Result Set
COLUMN NAME DATA TYPE DESCRIPTION

queue_type nvarchar(6) The type of queue. Possible values are


mail and status.

length int The number of mail items in the


specified queue.

state nvarchar(64) The state of the monitor. Possible


values are INACTIVE (queue is inactive),
NOTIFIED (queue has been notified
receipt to occur), and
RECEIVES_OCCURRING (queue is
receiving).

last_empty_rowset_time DATETIME The date and time that the queue was
last empty. In military time format and
GMT time zone.
COLUMN NAME DATA TYPE DESCRIPTION

last_activated_time DATETIME The date and time the queue was last
activated. In military time format and
GMT time zone.

Remarks
When troubleshooting Database Mail, use sysmail_help_queue_sp to see how many items are in the queue, the
status of the queue, and when it was last activated.

Permissions
By default, only members of the sysadmin fixed server role can access this procedure.

Examples
The following example returns both the mail and status queues.

EXECUTE msdb.dbo.sysmail_help_queue_sp ;
GO

This is a sample result set has been edited for length.

queue_type length state last_empty_rowset_time last_activated_time


---------- -------- ------------------ ----------------------- -----------------------
mail 0 RECEIVES_OCCURRING 2005-10-07 21:14:47.010 2005-10-10 20:52:51.517
status 0 INACTIVE 2005-10-07 21:04:47.003 2005-10-10 21:04:47.003

(2 row(s) affected)

See Also
Database Mail
sysmail_help_status_sp (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Displays the status of Database Mail queues. Use sysmail_start_sp to start the Database Mail queues and
sysmail_stop_sp to stop the Database Mail queues.
Transact-SQL Syntax Conventions

Syntax
sysmail_help_status_sp

Return Code Values


0 (success) or 1 (failure)

Result Set
COLUMN NAME DATA TYPE DESCRIPTION

Status nvarchar(7) The status of the Database Mail.


Possible values are STARTED and
STOPPED.

Permissions
By default, only members of the sysadmin fixed server role can access this procedure.

Examples
The following example displays the status of Database Mail.

EXECUTE msdb.dbo.sysmail_help_status_sp ;
GO

Result set:

Status
-------
STARTED

See Also
Database Mail External Program
sysmail_start_sp (Transact-SQL)
sysmail_stop_sp (Transact-SQL)
sysmail_start_sp (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Starts Database Mail by starting the Service Broker objects that the external program uses.
Transact-SQL Syntax Conventions

Syntax
sysmail_start_sp

Arguments
None

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Database Mail is not enabled or installed upon SQL Server installation. Use the Database Mail Configuration
wizard to enable and install the Database Mail objects.
This stored procedure is in the msdb database. This stored procedure starts the Database Mail queue that holds
outgoing message requests and enables the Service Broker activation for the external program.
When the queues are started, the Database Mail external program can process messages. This procedure allows
you to restart the queues after the queues have been stopped with the sysmail_stop_sp stored procedure.

NOTE
This stored procedure only starts the queues for Database Mail. This stored procedure does not activate Service Broker
message delivery in the database.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
The following example shows starting Database Mail in the msdb database. The example assumes that Database
Mail has been enabled.

USE msdb ;
GO

EXECUTE dbo.sysmail_start_sp ;
GO

See Also
Database Mail
Database Mail XPs Server Configuration Option
sysmail_stop_sp (Transact-SQL)
Database Mail Stored Procedures (Transact-SQL)
sysmail_stop_sp (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Stops Database Mail by stopping the Service Broker objects that the external program uses.
Transact-SQL Syntax Conventions

Syntax
sysmail_stop_sp

Arguments
None

Return Code Values


0 (success) or 1 (failure)

Remarks
This stored procedure is in the msdb database.
This stored procedure stops the Database Mail queue that holds outgoing message requests and turns off Service
Broker activation for the external program.
When the queues are stopped, the Database Mail external program does not process messages. This stored
procedure allows you to stop Database Mail for troubleshooting or maintenance purposes.
To start Database Mail, use sysmail_start_sp. Notice that sp_send_dbmail still accepts mail when the Service
Broker objects are stopped.

NOTE
This stored procedure only stops the queues for Database Mail. This stored procedure does not deactivate Service Broker
message delivery in the database. This stored procedure does not disable the Database Mail extended stored procedures to
reduce the surface area. To disable the extended stored procedures, see the Database Mail XPs option of the sp_configure
system stored procedure.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
The following example shows stopping Database Mail in the msdb database. The example assumes that Database
Mail has been enabled.
USE msdb ;
GO

EXECUTE dbo.sysmail_stop_sp ;
GO

See Also
Database Mail
sysmail_start_sp (Transact-SQL)
Database Mail Stored Procedures (Transact-SQL)
sysmail_update_account_sp (Transact-SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the information in an existing Database Mail account.
Transact-SQL Syntax Conventions

Syntax
sysmail_update_account_sp [ [ @account_id = ] account_id ] [ , ] [ [ @account_name = ] 'account_name' ] ,
[ @email_address = ] 'email_address' ,
[ @display_name = ] 'display_name' ,
[ @replyto_address = ] 'replyto_address' ,
[ @description = ] 'description' ,
[ @mailserver_name = ] 'server_name' ,
[ @mailserver_type = ] 'server_type' ,
[ @port = ] port_number ,
[ @timeout = ] 'timeout' ,
[ @username = ] 'username' ,
[ @password = ] 'password' ,
[ @use_default_credentials = ] use_default_credentials ,
[ @enable_ssl = ] enable_ssl

Arguments
[ @account_id = ] account_id
The account ID to update. account_id is int, with a default of NULL. At least one of account_id or account_name
must be specified. If both are specified, the procedure changes the name of the account.
[ @account_name = ] 'account_name'
The name of the account to update. account_name is sysname, with a default of NULL. At least one of account_id
or account_name must be specified. If both are specified, the procedure changes the name of the account.
[ @email_address = ] 'email_address'
The new e-mail address to send the message from. This address must be an internet e-mail address. The server
name in the address is the server that Database Mail uses to send mail from this account. email_address is
nvarchar(128), with a default of NULL.
[ @display_name = ] 'display_name'
The new display name to use on e-mail messages from this account. display_name is nvarchar(128), with no
default.
[ @replyto_address = ] 'replyto_address'
The new address to use in the Reply-To header of e-mail messages from this account. replyto_address is
nvarchar(128), with no default.
[ @description = ] 'description'
The new description for the account. description is nvarchar(256), with a default of NULL.
[ @mailserver_name = ] 'server_name'
The new name of the SMTP mail server to use for this account. The computer that runs SQL Server must be able to
resolve the server_name to an IP address. server_name is sysname, with no default.
[ @mailserver_type = ] 'server_type'
The new type of the mail server. server_type is sysname, with no default. Only a value of 'SMTP' is supported.
[ @port = ] port_number
The new port number of the mail server. port_number is int, with no default.
[ @timeout = ] 'timeout'
Timeout parameter for SmtpClient.Send of a single email message. Timeout is int in seconds, with no default.
[ @username = ] 'username'
The new user name to use to log on to the mail server. User name is sysname, with no default.
[ @password = ] 'password'
The new password to use to log on to the mail server. password is sysname, with no default.
[ @use_default_credentials = ] use_default_credentials
Specifies whether to send the mail to the SMTP server using the credentials of the SQL Server Database Engine
service. use_default_credentials is bit, with no default. When this parameter is 1, Database Mail uses the
credentials of the Database Engine. When this parameter is 0, Database Mail uses the @username and
@password for authentication on the SMTP server. If @username and @password are NULL then it will use
anonymous authentication. Consult with your SMTP administrator before specifying this parameter
[ @enable_ssl = ] enable_ssl
Specifies whether Database Mail encrypts communication using Secure Sockets Layer (SSL). Use this option if SSL
is required on your SMTP server. enable_ssl is bit, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
When both the account name and the account id are specified, the stored procedure changes the account name in
addition to updating the information for the account. Changing the account name may be useful to correct errors
in the account name.
The stored procedure sysmail_update_account_sp is in the msdb database and is owned by the dbo schema.
The procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
A. Changing the information for an account
The following example updates the account AdventureWorks Administrator In the msdb database. The information
for the account is set to the values provided.
EXECUTE msdb.dbo.sysmail_update_account_sp
@account_name = 'AdventureWorks Administrator'
,@description = 'Mail account for administrative e-mail.'
,@email_address = 'dba@Adventure-Works.com'
,@display_name = 'AdventureWorks Automated Mailer'
,@replyto_address = NULL
,@mailserver_name = 'smtp.Adventure-Works.com'
,@mailserver_type = 'SMTP'
,@port = 25
,@timeout = 60
,@username = NULL
,@password = NULL
,@use_default_credentials = 0
,@enable_ssl = 0;

B. Changing the name of an account and the information for an account


The following example changes the name and updates the account information for the with account id 125 . The
new name of the account is Backup Mail Server .

EXECUTE msdb.dbo.sysmail_update_account_sp
@account_id = 125
,@account_name = 'Backup Mail Server'
,@description = 'Mail account for administrative e-mail.'
,@email_address = 'dba@Adventure-Works.com'
,@display_name = 'AdventureWorks Automated Mailer'
,@replyto_address = NULL
,@mailserver_name = 'smtp-backup.Adventure-Works.com'
,@mailserver_type = 'SMTP'
,@port = 25
,@timeout = 60
,@username = NULL
,@password = NULL
,@use_default_credentials = 0
,@enable_ssl = 0;

See Also
Database Mail
Create a Database Mail Account
Database Mail Stored Procedures (Transact-SQL)
sysmail_update_principalprofile_sp (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Updates the information for an association between a principal and a profile.
Transact-SQL Syntax Conventions

Syntax
sysmail_update_principalprofile_sp { @principal_id = principal_id | @principal_name = 'principal_name' } ,
{ [ @profile_id = ] profile_id | [ @profile_name = ] 'profile_name' } ,
[ @is_default = ] 'is_default'

Arguments
[ @principal_id = ] principal_id
The ID of the database user or role in the msdb database for the association to change. principal_id is int, with a
default of NULL. Either principal_id or principal_name must be specified.
[ @principal_name = ] 'principal_name'
The name of the database user or role in the msdb database for the association to update. principal_name is
sysname, with a default of NULL. Either principal_id or principal_name may be specified.
[ @profile_id = ] profile_id
The id of the profile for the association to change. profile_id is int, with a default of NULL. Either profile_id or
profile_name must be specified.
[ @profile_name = ] 'profile_name'
The name of the profile for the association to change. profile_name is sysname, with a default of NULL. Either
profile_id or profile_name must be specified.
[ @is_default = ] 'is_default'
Is whether this profile is the default profile for the database user. A database user may only have one default
profile. is_default is bit, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
This stored procedure changes whether the profile specified is the default profile for the database user. A database
user may only have one default private profile.
When the principal name for the association is public or the principal id for the association is 0, this stored
procedure changes the public profile. There can only be one default public profile.
When @is_default is '1' and the principal is associated with more than one profile, the specified profile becomes
the default profile for the principal. The profile that was previously the default profile is still associated with the
principal, but is no longer the default profile.
The stored procedure sysmail_update_principalprofile_sp is in the msdb database and is owned by the dbo
schema. The procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
A. Setting a profile to be the default public profile for a database
The following example sets the profile General Use Profile to be the default public profile for users in the msdb
database.

EXECUTE msdb.dbo.sysmail_update_principalprofile_sp
@principal_name = 'public',
@profile_name = 'General Use Profile',
@is_default = '1';

B. Setting a profile to be the default private profile for a user


The following example sets the profile AdventureWorks Administrator to be the default profile for the principal
ApplicationUser in the msdb database. The profile must already be associated with the principal. The profile that
was previously the default profile is still associated with the principal, but is no longer the default profile.

EXECUTE msdb.dbo.sysmail_update_principalprofile_sp
@principal_name = 'ApplicationUser',
@profile_name = 'AdventureWorks Administrator',
@is_default = '1' ;

See Also
Database Mail
Database Mail Configuration Objects
Database Mail Stored Procedures (Transact-SQL)
sysmail_update_profile_sp (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the description or name of a Database Mail profile.
Transact-SQL Syntax Conventions

Syntax
sysmail_update_profile_sp [ [ @profile_id = ] profile_id , ] [ [ @profile_name = ] 'profile_name' , ]
[ [ @description = ] 'description' ]

Arguments
[ @profile_id = ] profile_id
The profile id to update. profile_id is int, with a default of NULL. At least one of profile_id or profile_name must be
specified. If both are specified, the procedure changes the name of the profile.
[ @profile_name = ] 'profile_name'
The name of the profile to update or the new name for the profile. profile_name is sysname, with a default of
NULL. At least one of profile_id or profile_name must be specified. If both are specified, the procedure changes the
name of the profile.
[ @description = ] 'description'
The new description for the profile. description is nvarchar(256), with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
When both the profile id and the profile name are specified, the procedure changes the name of the profile to the
provided name and updates the description for the profile. When only one of these arguments is provided, the
procedure updates the description for the profile.
The stored procedure sysmail_update_profile_sp is in the msdb database and is owned by the dbo schema. The
procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
A. Changing the description of a profile
The following example changes the description for the profile named AdventureWorks Administrator in the msdb
database.

EXECUTE msdb.dbo.sysmail_update_profile_sp
@profile_name = 'AdventureWorks Administrator'
,@description = 'Administrative mail profile.';

B. Changing the name and description of a profile


The following example changes the name and description of the profile with the profile id 750 .

EXECUTE msdb.dbo.sysmail_update_profile_sp
@profile_id = 750
,@profile_name = 'Operator'
,@description = 'Profile to send alert e-mail to operators.';

See Also
Database Mail
Database Mail Configuration Objects
Create a Database Mail Account
Database Mail Stored Procedures (Transact-SQL)
sysmail_update_profileaccount_sp (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates the sequence number of an account within a Database Mail profile.
Transact-SQL Syntax Conventions

Syntax
sysmail_update_profileaccount_sp { [ @profile_id = ] profile_id
| [ @profile_name = ] 'profile_name' } ,
{ [ @account_id = ] account_id | [ @account_name = ] 'account_name' } ,
[ @sequence_number = ] sequence_number

Arguments
[ @profile_id = ] profile_id
The profile ID of the profile to update. profile_id is int, with a default of NULL. Either the profile_id or the
profile_name must be specified.
[ @profile_name = ] 'profile_name'
The profile name of the profile to update. profile_name is sysname, with a default of NULL. Either the profile_id or
the profile_name must be specified.
[ @account_id = ] account_id
The account ID to update. account_id is int, with a default of NULL. Either the account_id or the account_name
must be specified.
[ @account_name = ] 'account_name'
The name of the account to update. account_name is sysname, with a default of NULL. Either the account_id or
the account_name must be specified.
[ @sequence_number = ] sequence_number
The new sequence number for the account. sequence_number is int, with no default. The sequence number
determines the order in which accounts are used in the profile.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Returns an error if the account specified is not associated with the profile specified.
The sequence number determines the order in which Database Mail uses accounts in the profile. For a new e-mail
message, Database Mail starts with the account that has the lowest sequence number. Should that account fail,
Database Mail uses the account with the next highest sequence number, and so on until either Database Mail
sends the message successfully, or the account with the highest sequence number fails. If the account with the
highest sequence number fails, the e-mail message fails.
If more than one account exists with the same sequence number, Database Mail only uses one of those accounts
for a given e-mail message. In this case, Database Mail makes no guarantees as to which of the accounts is used
for that sequence number or that the same account is used from message to message.
The stored procedure sysmail_update_profileaccount_sp is in the msdb database and is owned by the dbo
schema. The procedure must be executed with a three-part name if the current database is not msdb.

Permissions
Execute permissions for this procedure default to members of the sysadmin fixed server role.

Examples
The following example changes the sequence number of the account Admin-BackupServer within the profile
AdventureWorks Administrator in the msdb database. After executing this code, the sequence number for the
account is 3 , indicating it will be tried if the first two accounts fail.

EXECUTE msdb.dbo.sysmail_update_profileaccount_sp
@profile_name = 'AdventureWorks Administrator'
,@account_name = 'Admin-BackupServer',
,@sequence_number = 3;

See Also
Database Mail
Create a Database Mail Account
Database Mail Configuration Objects
Database Mail Stored Procedures (Transact-SQL)
Database Maintenance Plan Stored Procedures
(Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Microsoft SQL Server supports the following system stored procedures that are used to set up maintenance tasks.
These stored procedures are used with database maintenance plans. This feature has been replaced with
maintenance plans which do not use these stored procedures. Use these procedures to maintain database
maintenance plans on installations that were upgraded from a previous version of SQL Server.
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature.

sp_add_maintenance_plan sp_delete_maintenance_plan_db

sp_add_maintenance_plan_db sp_delete_maintenance_plan_job

sp_add_maintenance_plan_job sp_help_maintenance_plan

sp_delete_maintenance_plan

See Also
System Stored Procedures (Transact-SQL)
Maintenance Plans
sp_add_maintenance_plan (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adds a maintenance plan and returns the plan ID.

NOTE
This stored procedure is used with database maintenance plans. This feature has been replaced with maintenance plans which
do not use this stored procedure. Use this procedure to maintain database maintenance plans on installations that were
upgraded from a previous version of SQL Server.

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature.
Transact-SQL Syntax Conventions

Syntax
sp_add_maintenance_plan [ @plan_name = ] 'plan_name' ,
@plan_id = 'plan_id' OUTPUT

Arguments
[ @plan_name =] 'plan_name'
Specifies the name of the maintenance plan to be added. plan_name is varchar(128).
@plan_id = ' plan_id '
Specifies the ID of the maintenance plan. plan_id is uniqueidentifier.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_add_maintenance_plan must be run from the msdb database and creates a new, but empty, maintenance
plan. To add one or more databases and associate them with a job or jobs, execute
sp_add_maintenance_plan_db and sp_add_maintenance_plan_job.

Permissions
Only members of the sysadmin fixed server role can execute sp_add_maintenance_plan.

Examples
Create a maintenance plan called Myplan.
DECLARE @myplan_id UNIQUEIDENTIFIER;
EXECUTE sp_add_maintenance_plan N'Myplan',@plan_id=@myplan_id OUTPUT
PRINT 'The id for the maintenance plan "Myplan" is:'+convert(varchar(256),@myplan_id);
GO

Success in creating the maintenance plan will return the plan ID.

'The id for the maintenance plan "Myplan" is:' FAD6F2AB-3571-11D3-9D4A-00C04FB925FC

See Also
Maintenance Plans
Database Maintenance Plan Stored Procedures (Transact-SQL)
sp_add_maintenance_plan_db (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Associates a database with a maintenance plan.

NOTE
This stored procedure is used with database maintenance plans. This feature has been replaced with maintenance plans which
do not use this stored procedure. Use this procedure to maintain database maintenance plans on installations that were
upgraded from a previous version of SQL Server.

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature.
Transact-SQL Syntax Conventions

Syntax
sp_add_maintenance_plan_db [ @plan_id = ] 'plan_id' ,
[ @db_name = ] 'database_name'

Arguments
[ @plan_id =] 'plan_id'
Specifies the plan ID of the maintenance plan. plan_id is uniqueidentifier, and must be a valid ID.
[ @db_name =] 'database_name'
Specifies the name of the database to be added to the maintenance plan. The database must be created or exist
before its addition to the plan. database_name is sysname.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_add_maintenance_plan_db must be run from the msdb database.

Permissions
Only members of the sysadmin fixed server role can execute sp_add_maintenance_plan_db.

Examples
This example adds the AdventureWorks2012 database to the maintenance plan created in
sp_add_maintenance_plan.
EXECUTE sp_add_maintenance_plan_db N'FAD6F2AB-3571-11D3-9D4A-00C04FB925FC',N'AdventureWorks2012';

See Also
Maintenance Plans
Database Maintenance Plan Stored Procedures (Transact-SQL)
sp_add_maintenance_plan_job (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Associates a maintenance plan with an existing job.

NOTE
This stored procedure is used with database maintenance plans. This feature has been replaced with maintenance plans which
do not use this stored procedure. Use this procedure to maintain database maintenance plans on installations that were
upgraded from a previous version of SQL Server.

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature.
Transact-SQL Syntax Conventions

Syntax
sp_add_maintenance_plan_job [ @plan_id = ] 'plan_id' , [ @job_id = ] 'job_id'

Arguments
[ @plan_id =] 'plan_id'
Specifies the ID of the maintenance plan. plan_id is uniqueidentifier, and must be a valid ID.
[ @job_id =] 'job_id'
Specifies the ID of the job to be associated with the maintenance plan. job_id is uniqueidentifier, and must be a
valid ID. To create a job or jobs, execute sp_add_job, or use SQL Server Management Studio.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_add_maintenance_plan_job must be run from the msdb database.

Permissions
Only members of the sysadmin fixed server role can execute sp_add_maintenance_plan_job.

Examples
This example adds the job "B8FCECB1-E22C-11D2-AA64-00C04F688EAE" to the maintenance plan created by
using sp_add_maintenance_plan_job.
EXECUTE sp_add_maintenance_plan_job N'FAD6F2AB-3571-11D3-9D4A-00C04FB925FC', N'B8FCECB1-E22C-11D2-AA64-
00C04F688EAE';

See Also
Maintenance Plans
Database Maintenance Plan Stored Procedures (Transact-SQL)
sp_delete_maintenance_plan (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes the specified maintenance plan.

NOTE
This stored procedure is used with database maintenance plans. This feature has been replaced with maintenance plans which
do not use this stored procedure. Use this procedure to maintain database maintenance plans on installations that were
upgraded from a previous version of SQL Server.

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature.
Transact-SQL Syntax Conventions

Syntax
sp_delete_maintenance_plan [ @plan_id = ] 'plan_id'

Arguments
[ @plan_id =] 'plan_id'
Specifies the ID of the maintenance plan to be deleted. plan_id is uniqueidentifier, and must be a valid ID.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_delete_maintenance_plan must be run from the msdb database.

Permissions
Only members of the sysadmin fixed server role can execute sp_delete_maintenance_plan.

Examples
Deletes the maintenance plan created by using sp_add_maintenance_plan.

EXECUTE sp_delete_maintenance_plan 'FAD6F2AB-3571-11D3-9D4A-00C04FB925FC';

See Also
Maintenance Plans
Database Maintenance Plan Stored Procedures (Transact-SQL)
sp_delete_maintenance_plan_db (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Disassociates the specified maintenance plan from the specified database.

NOTE
This stored procedure is used with database maintenance plans. This feature has been replaced with maintenance plans which
do not use this stored procedure. Use this procedure to maintain database maintenance plans on installations that were
upgraded from a previous version of SQL Server.

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature.
Transact-SQL Syntax Conventions

Syntax
sp_delete_maintenance_plan_db [ @plan_id = ] 'plan_id' ,
[ @db_name = ] 'database_name'

Arguments
[ @plan_id =] 'plan_id'
Specifies the maintenance plan ID. plan_id is uniqueidentifier.
[ @db_name =] 'database_name'
Specifies the database name to be deleted from the maintenance plan. database_name is sysname.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_delete_maintenance_plan_db must be run from the msdb database.
The sp_delete_maintenance_plan_db stored procedure removes the association between the maintenance plan
and the specified database; it does not drop or destroy the database.
When sp_delete_maintenance_plan_db removes the last database from the maintenance plan, the stored
procedure also deletes the maintenance plan.

Permissions
Only members of the sysadmin fixed server role can execute sp_delete_maintenance_plan_db.
Examples
Deletes the maintenance plan in the AdventureWorks2012 database, previously added by using
sp_add_maintenance_plan_db.

EXECUTE sp_delete_maintenance_plan_db N'FAD6F2AB-3571-11D3-9D4A-00C04FB925FC', N'AdventureWorks2012';

See Also
Maintenance Plans
Database Maintenance Plan Stored Procedures (Transact-SQL)
sp_delete_maintenance_plan_job (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Disassociates the specified maintenance plan from the specified job.

NOTE
This stored procedure is used with database maintenance plans. This feature has been replaced with maintenance plans which
do not use this stored procedure. Use this procedure to maintain database maintenance plans on installations that were
upgraded from a previous version of SQL Server.

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature.
Transact-SQL Syntax Conventions

Syntax
sp_delete_maintenance_plan_job [ @plan_id = ] 'plan_id' ,
[ @job_id = ] 'job_id'

Arguments
[ @plan_id =] 'plan_id'
Specifies the ID of the maintenance plan. plan_id is uniqueidentifier, and must be a valid ID.
[ @job_id =] 'job_id'
Specifies the ID of the job with which the maintenance plan is associated. job_id is uniqueidentifier, and must be
a valid ID.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_delete_maintenance_plan_job must be run from the msdb database.
When all jobs have been removed from the maintenance plan, we recommend that users execute
sp_delete_maintenance_plan_db to remove the remaining databases from the plan.

Permissions
Only members of the sysadmin fixed server role can execute sp_delete_maintenance_plan_job.

Examples
This example deletes the job "B8FCECB1-E22C-11D2-AA64-00C04F688EAE" from the maintenance plan.

EXECUTE sp_delete_maintenance_plan_job N'FAD6F2AB-3571-11D3-9D4A-00C04FB925FC', N'B8FCECB1-E22C-11D2-AA64-


00C04F688EAE';

See Also
Maintenance Plans
Database Maintenance Plan Stored Procedures (Transact-SQL)
sp_help_maintenance_plan (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns information about the specified maintenance plan. If a plan is not specified, this stored procedure returns
information about all maintenance plans.

NOTE: This stored procedure is used with database maintenance plans. This feature has been replaced with
maintenance plans which do not use this stored procedure. Use this procedure to maintain database
maintenance plans on installations that were upgraded from a previous version of SQL Server.

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature.
Transact-SQL Syntax Conventions

Syntax
sp_help_maintenance_plan [ [ @plan_id = ] 'plan_id' ]

Arguments
[ @plan_id =] 'plan_id'
Specifies the plan ID of the maintenance plan. plan_id is UNIQUEIDENTIFIER. The default is NULL.

Return Code Values


None

Result Sets
If plan_id is specified, sp_help_maintenance_plan will return three tables: Plan, Database, and Job.
Plan Table
COLUMN NAME DATA TYPE DESCRIPTION

plan_id uniqueidentifier Maintenance plan ID.

plan_name sysname Maintenance plan name.

date_created datetime Date the maintenance plan was created.

owner sysname Owner of the maintenance plan.


COLUMN NAME DATA TYPE DESCRIPTION

max_history_rows int Maximum number of rows allocated for


recording the history of the
maintenance plan in the system table.

remote_history_server int The name of the remote server to which


the history report could be written.

max_remote_history_rows int Maximum number of rows allocated in


the system table on a remote server to
which the history report could be
written.

user_defined_1 int Default is NULL.

user_defined_2 nvarchar(100) Default is NULL.

user_defined_3 datetime Default is NULL.

user_defined_4 uniqueidentifier Default is NULL.

Database Table
COLUMN NAME DESCRIPTION

database_name Name of all databases associated with the maintenance plan.


database_name is sysname.

Job Table
COLUMN NAME DESCRIPTION

job_id ID of all jobs associated with the maintenance plan. job_id is


uniqueidentifier.

Remarks
sp_help_maintenance_plan is in the msdb database.

Permissions
Only members of the sysadmin fixed server role can execute sp_help_maintenance_plan.

Examples
This example descriptive information about the maintenance plan FAD6F2AB-3571-11D3-9D4A-00C04FB925FC.

EXECUTE sp_help_maintenance_plan
N'FAD6F2AB-3571-11D3-9D4A-00C04FB925FC';

See Also
Maintenance Plans
Database Maintenance Plan Stored Procedures (Transact-SQL)
Distributed Queries Stored Procedures (Transact-
SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
SQL Server supports the following system stored procedures that are used to implement and manage Distributed
Queries.

sp_addlinkedserver sp_indexes

sp_addlinkedsrvlogin sp_linkedservers

sp_catalogs sp_primarykeys

sp_column_privileges_ex sp_serveroption

sp_columns_ex sp_table_privileges_ex

sp_droplinkedsrvlogin sp_tables_ex

sp_dropserver (Transact-SQL) sp_testlinkedserver (Transact-SQL)

sp_foreignkeys

See Also
System Stored Procedures (Transact-SQL)
sp_addlinkedserver (Transact-SQL)
11/21/2017 • 10 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a linked server. A linked server allows for access to distributed, heterogeneous queries against OLE DB
data sources. After a linked server is created by using sp_addlinkedserver, distributed queries can be run against
this server. If the linked server is defined as an instance of SQL Server, remote stored procedures can be executed.
Transact-SQL Syntax Conventions

Syntax
sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ]
[ , [ @provider= ] 'provider_name' ]
[ , [ @datasrc= ] 'data_source' ]
[ , [ @location= ] 'location' ]
[ , [ @provstr= ] 'provider_string' ]
[ , [ @catalog= ] 'catalog' ]

Arguments
[ @server= ] 'server'
Is the name of the linked server to create. server is sysname, with no default.
[ @srvproduct= ] 'product_name'
Is the product name of the OLE DB data source to add as a linked server. product_name is nvarchar(128), with a
default of NULL. If SQL Server, provider_name, data_source, location, provider_string, and catalog do not have to
be specified.
[ @provider= ] 'provider_name'
Is the unique programmatic identifier (PROGID) of the OLE DB provider that corresponds to this data source.
provider_name must be unique for the specified OLE DB provider installed on the current computer.
provider_name is nvarchar(128), with a default of NULL; however, if provider_name is omitted, SQLNCLI is used.
(Use SQLNCLI and SQL Server will redirect to the latest version of SQL Server Native Client OLE DB Provider.) The
OLE DB provider is expected to be registered with the specified PROGID in the registry.
[ @datasrc= ] 'data_source'
Is the name of the data source as interpreted by the OLE DB provider. data_source is nvarchar(4000).
data_source is passed as the DBPROP_INIT_DATASOURCE property to initialize the OLE DB provider.
[ @location= ] 'location'
Is the location of the database as interpreted by the OLE DB provider. location is nvarchar(4000), with a default
of NULL. location is passed as the DBPROP_INIT_LOCATION property to initialize the OLE DB provider.
[ @provstr= ] 'provider_string'
Is the OLE DB provider-specific connection string that identifies a unique data source. provider_string is
nvarchar(4000), with a default of NULL. provstr is either passed to IDataInitialize or set as the
DBPROP_INIT_PROVIDERSTRING property to initialize the OLE DB provider.
When the linked server is created against the SQL Server Native Client OLE DB provider, the instance can be
specified by using the SERVER keyword as SERVER=servername\instancename to specify a specific instance of
SQL Server. servername is the name of the computer on which SQL Server is running, and instancename is the
name of the specific instance of SQL Server to which the user will be connected.

NOTE
To access a mirrored database, a connection string must contain the database name. This name is necessary to enable
failover attempts by the data access provider. The database can be specified in the @provstr or @catalog parameter.
Optionally, the connection string can also supply a failover partner name.

[ @catalog= ] 'catalog'
Is the catalog to be used when a connection is made to the OLE DB provider. catalog is sysname, with a default of
NULL. catalog is passed as the DBPROP_INIT_CATALOG property to initialize the OLE DB provider. When the
linked server is defined against an instance of SQL Server, catalog refers to the default database to which the
linked server is mapped.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Remarks
The following table shows the ways that a linked server can be set up for data sources that can be accessed
through OLE DB. A linked server can be set up more than one way for a particular data source; there can be more
than one row for a data source type. This table also shows the sp_addlinkedserver parameter values to be used
for setting up the linked server.

REMOTE OLE
DB DATA OLE DB PRODUCT_N PROVIDER_N DATA_SOUR PROVIDER_S
SOURCE PROVIDER AME AME CE LOCATION TRING CATALOG

SQL Server Microsoft SQL Server


SQL Server 1 (default)
Native
Client OLE
DB Provider

SQL Server Microsoft SQLNCLI Network Database


SQL Server name of name
Native SQL Server (optional)
Client OLE (for default
DB Provider instance)

SQL Server Microsoft SQLNCLI servername Database


SQL Server \instancena name
Native me (for (optional)
Client OLE specific
DB Provider instance)

Oracle, Oracle Any OraOLEDB. Alias for the


version 8 Provider for Oracle Oracle
and later OLE DB database
REMOTE OLE
DB DATA OLE DB PRODUCT_N PROVIDER_N DATA_SOUR PROVIDER_S
SOURCE PROVIDER AME AME CE LOCATION TRING CATALOG

Access/Jet Microsoft Any Microsoft. Full path of


OLE DB Jet.OLEDB. Jet
Provider for 4.0 database
Jet file

ODBC data Microsoft Any MSDASQL System


source OLE DB DSN of
Provider for ODBC data
ODBC source

ODBC data Microsoft Any MSDASQL ODBC


source OLE DB connection
Provider for string
ODBC

File system Microsoft Any MSIDXS Indexing


OLE DB Service
Provider for catalog
Indexing name
Service

Microsoft Microsoft Any Microsoft. Full path of Excel 5.0


Excel OLE DB Jet.OLEDB. Excel file
Spreadshee Provider for 4.0
t Jet

IBM DB2 Microsoft Any DB2OLEDB See Catalog


Database OLE DB Microsoft name of
Provider for OLE DB DB2
DB2 Provider for database
DB2
documentat
ion.

1 This way of setting up a linked server


forces the name of the linked server to be the same as the network name
of the remote instance of SQL Server. Use data_source to specify the server.
2 "Any" indicates that the product name can be anything.

The Microsoft SQL Server Native Client OLE DB provider is the provider that is used with SQL Server if no
provider name is specified or if SQL Server is specified as the product name. Even if you specify the older
provider name, SQLOLEDB, it will be changed to SQLNCLI when persisted to the catalog.
The data_source, location, provider_string, and catalog parameters identify the database or databases the linked
server points to. If any one of these parameters is NULL, the corresponding OLE DB initialization property is not
set.
In a clustered environment, when you specify file names to point to OLE DB data sources, use the universal
naming convention name (UNC) or a shared drive to specify the location.
sp_addlinkedserver cannot be executed within a user-defined transaction.
IMPORTANT
When a linked server is created by using sp_addlinkedserver, a default self-mapping is added for all local logins. For non-
SQL Server providers, SQL Server Authenticated logins may be able to gain access to the provider under the SQL Server
service account. Administrators should consider using sp_droplinkedsrvlogin <linkedserver_name>, NULL to remove
the global mapping.

Permissions
The sp_addlinkedserver statement requires the ALTER ANY LINKED SERVER permission. (The SSMS New Linked
Server dialog box is implemented in a way that requires membership in the sysadmin fixed server role.)

Examples
A. Using the Microsoft SQL Server Native Client OLE DB Provider
The following example creates a linked server named SEATTLESales . The product name is SQL Server , and no
provider name is used.

USE master;
GO
EXEC sp_addlinkedserver
N'SEATTLESales',
N'SQL Server';
GO

The following example creates a linked server S1_instance1 on an instance of SQL Server by using the SQL
Server Native Client OLE DB provider.

EXEC sp_addlinkedserver
@server=N'S1_instance1',
@srvproduct=N'',
@provider=N'SQLNCLI',
@datasrc=N'S1\instance1';

B. Using the Microsoft OLE DB Provider for Microsoft Access


The Microsoft.Jet.OLEDB.4.0 provider connects to Microsoft Access databases that use the 2002-2003 format. The
following example creates a linked server named SEATTLE Mktg .

NOTE
This example assumes that both Microsoft Access and the sample Northwind database are installed and that the
Northwind database resides in C:\Msoffice\Access\Samples.

EXEC sp_addlinkedserver
@server = N'SEATTLE Mktg',
@provider = N'Microsoft.Jet.OLEDB.4.0',
@srvproduct = N'OLE DB Provider for Jet',
@datasrc = N'C:\MSOffice\Access\Samples\Northwind.mdb';
GO

The Microsoft.ACE.OLEDB.12.0 provider connects to Microsoft Access databases that use the 2007 format. The
following example creates a linked server named SEATTLE Mktg .
NOTE
This example assumes that both Microsoft Access and the sample Northwind database are installed and that the
Northwind database resides in C:\Msoffice\Access\Samples.

EXEC sp_addlinkedserver
@server = N'SEATTLE Mktg',
@provider = N'Microsoft.ACE.OLEDB.12.0',
@srvproduct = N'OLE DB Provider for ACE',
@datasrc = N'C:\MSOffice\Access\Samples\Northwind.accdb';
GO

C. Using the Microsoft OLE DB Provider for ODBC with the data_source parameter
The following example creates a linked server named SEATTLE Payroll that uses the Microsoft OLE DB Provider
for ODBC ( MSDASQL ) and the data_source parameter.

NOTE
The specified ODBC data source name must be defined as System DSN in the server before you use the linked server.

EXEC sp_addlinkedserver
@server = N'SEATTLE Payroll',
@srvproduct = N'',
@provider = N'MSDASQL',
@datasrc = N'LocalServer';
GO

D. Using the Microsoft OLE DB Provider for Excel spreadsheet


To create a linked server definition using the Microsoft OLE DB Provider for Jet to access an Excel spreadsheet in
the 1997 - 2003 format, first create a named range in Excel by specifying the columns and rows of the Excel
worksheet to select. The name of the range can then be referenced as a table name in a distributed query.

EXEC sp_addlinkedserver 'ExcelSource',


'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
'c:\MyData\DistExcl.xls',
NULL,
'Excel 5.0';
GO

To access data from an Excel spreadsheet, associate a range of cells with a name. The following query can be used
to access the specified named range SalesData as a table by using the linked server set up previously.

SELECT *
FROM ExcelSource...SalesData;
GO

If SQL Server is running under a domain account that has access to a remote share, a UNC path can be used
instead of a mapped drive.
EXEC sp_addlinkedserver 'ExcelShare',
'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
'\\MyServer\MyShare\Spreadsheets\DistExcl.xls',
NULL,
'Excel 5.0';

To connect to an Excel spreadsheet in the Excel 2007 format use the ACE provider.

EXEC sp_addlinkedserver @server = N'ExcelDataSource',


@srvproduct=N'ExcelData', @provider=N'Microsoft.ACE.OLEDB.12.0',
@datasrc=N'C:\DataFolder\People.xlsx',
@provstr=N'EXCEL 12.0' ;

E. Using the Microsoft OLE DB Provider for Jet to access a text file
The following example creates a linked server for directly accessing text files, without linking the files as tables in
an Access .mdb file. The provider is Microsoft.Jet.OLEDB.4.0 and the provider string is Text .
The data source is the full path of the directory that contains the text files. A schema.ini file, which describes the
structure of the text files, must exist in the same directory as the text files. For more information about how to
create a Schema.ini file, see the Jet Database Engine documentation.

--Create a linked server.


EXEC sp_addlinkedserver txtsrv, N'Jet 4.0',
N'Microsoft.Jet.OLEDB.4.0',
N'c:\data\distqry',
NULL,
N'Text';
GO

--Set up login mappings.


EXEC sp_addlinkedsrvlogin txtsrv, FALSE, Admin, NULL;
GO

--List the tables in the linked server.


EXEC sp_tables_ex txtsrv;
GO

--Query one of the tables: file1#txt


--using a four-part name.
SELECT *
FROM txtsrv...[file1#txt];

F. Using the Microsoft OLE DB Provider for DB2


The following example creates a linked server named DB2 that uses the Microsoft OLE DB Provider for DB2 .

EXEC sp_addlinkedserver
@server=N'DB2',
@srvproduct=N'Microsoft OLE DB Provider for DB2',
@catalog=N'DB2',
@provider=N'DB2OLEDB',
@provstr=N'Initial Catalog=PUBS;
Data Source=DB2;
HostCCSID=1252;
Network Address=XYZ;
Network Port=50000;
Package Collection=admin;
Default Schema=admin;';
G. Add a Azure SQL Database as a Linked Server For Use With Distributed Queries on Cloud and On-Premise
Databases
You can add a Azure SQL Database as a linked server and then use it with distributed queries that span the on-
premises and cloud databases. This is a component for database hybrid solutions spanning on-premises
corporate networks and the Windows Azure cloud.
The SQL Server box product contains the distributed query feature, which allows you to write queries to combine
data from local data sources and data from remote sources (including data from non- SQL Server data sources)
defined as linked servers. Every Azure SQL Database (except the virtual master) can be added as an individual
linked server and then used directly in your database applications as any other database.
The benefits of using Azure SQL Database include manageability, high availability, scalability, working with a
familiar development model, and a relational data model. The requirements of your database application
determine how it would use Azure SQL Database in the cloud. You can move all of your data at once to Azure SQL
Database, or progressively move some of your data while keeping the remaining data on-premises. For such a
hybrid database application, Azure SQL Database can now be added as linked servers and the database
application can issue distributed queries to combine data from Azure SQL Database and on-premise data sources.
Here’s a simple example explaining how to connect to a Azure SQL Database using distributed queries:

------ Configure the linked server


-- Add one Windows Azure SQL DB as Linked Server
EXEC sp_addlinkedserver
@server='myLinkedServer', -- here you can specify the name of the linked server
@srvproduct='',
@provider='sqlncli', -- using SQL Server Native Client
@datasrc='myServer.database.windows.net', -- add here your server name
@location='',
@provstr='',
@catalog='myDatabase' -- add here your database name as initial catalog (you cannot connect to the master
database)
-- Add credentials and options to this linked server
EXEC sp_addlinkedsrvlogin
@rmtsrvname = 'myLinkedServer',
@useself = 'false',
@rmtuser = 'myLogin', -- add here your login on Azure DB
@rmtpassword = 'myPassword' -- add here your password on Azure DB
EXEC sp_serveroption 'myLinkedServer', 'rpc out', true;
------ Now you can use the linked server to execute 4-part queries
-- You can create a new table in the Azure DB
exec ('CREATE TABLE t1tutut2(col1 int not null CONSTRAINT PK_col1 PRIMARY KEY CLUSTERED (col1) )') at
myLinkedServer
-- Insert data from your local SQL Server
exec ('INSERT INTO t1tutut2 VALUES(1),(2),(3)') at myLinkedServer

-- Query the data using 4-part names


select * from myLinkedServer.myDatabase.dbo.myTable

See Also
Distributed Queries Stored Procedures (Transact-SQL)
sp_addlinkedsrvlogin (Transact-SQL)
sp_addserver (Transact-SQL)
sp_dropserver (Transact-SQL)
sp_serveroption (Transact-SQL)
sp_setnetname (Transact-SQL)
System Stored Procedures (Transact-SQL)
System Tables (Transact-SQL)
sp_addlinkedsrvlogin (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates or updates a mapping between a login on the local instance of SQL Server and a security account on a
remote server.
Transact-SQL Syntax Conventions

Syntax
sp_addlinkedsrvlogin [ @rmtsrvname = ] 'rmtsrvname'
[ , [ @useself = ] 'TRUE' | 'FALSE' | NULL ]
[ , [ @locallogin = ] 'locallogin' ]
[ , [ @rmtuser = ] 'rmtuser' ]
[ , [ @rmtpassword = ] 'rmtpassword' ]

Arguments
[ @rmtsrvname = ] 'rmtsrvname'
Is the name of a linked server that the login mapping applies to. rmtsrvname is sysname, with no default.
[ @useself = ] 'TRUE' | 'FALSE' | 'NULL'
Determines whether to connect to rmtsrvname by impersonating local logins or explicitly submitting a login and
password. The data type is varchar(8), with a default of TRUE.
A value of TRUE specifies that logins use their own credentials to connect to rmtsrvname, with the rmtuser and
rmtpassword arguments being ignored. FALSE specifies that the rmtuser and rmtpassword arguments are used to
connect to rmtsrvname for the specified locallogin. If rmtuser and rmtpassword are also set to NULL, no login or
password is used to connect to the linked server.
[ @locallogin = ] 'locallogin'
Is a login on the local server. locallogin is sysname, with a default of NULL. NULL specifies that this entry applies
to all local logins that connect to rmtsrvname. If not NULL, locallogin can be a SQL Server login or a Windows
login. The Windows login must have been granted access to SQL Server either directly, or through its membership
in a Windows group granted access.
[ @rmtuser = ] 'rmtuser'
Is the remote login used to connect to rmtsrvname when @useself is FALSE. When the remote server is an
instance of SQL Server that does not use Windows Authentication, rmtuser is a SQL Server login. rmtuser is
sysname, with a default of NULL.
[ @rmtpassword = ] 'rmtpassword'
Is the password associated with rmtuser. rmtpassword is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)
Remarks
When a user logs on to the local server and executes a distributed query that accesses a table on the linked server,
the local server must log on to the linked server on behalf of the user to access that table. Use
sp_addlinkedsrvlogin to specify the login credentials that the local server uses to log on to the linked server.

NOTE
To create the best query plans when you are using a table on a linked server, the query processor must have data
distribution statistics from the linked server. Users that have limited permissions on any columns of the table might not
have sufficient permissions to obtain all the useful statistics, and might receive a less efficient query plan and experience
poor performance. If the linked server is an instance of SQL Server, to obtain all available statistics, the user must own the
table or be a member of the sysadmin fixed server role, the db_owner fixed database role, or the db_ddladmin fixed
database role on the linked server. SQL Server 2012 SP1 modifies the permission restrictions for obtaining statistics and
allows users with SELECT permission to access statistics available through DBCC SHOW_STATISTICS. For more information,
see the Permissions section of DBCC SHOW_STATISTICS (Transact-SQL).

A default mapping between all logins on the local server and remote logins on the linked server is automatically
created by executing sp_addlinkedserver. The default mapping states that SQL Server uses the user credentials of
the local login when connecting to the linked server on behalf of the login. This is equivalent to executing
sp_addlinkedsrvlogin with @useself set to true for the linked server, without specifying a local user name. Use
sp_addlinkedsrvlogin only to change the default mapping or to add new mappings for specific local logins. To
delete the default mapping or any other mapping, use sp_droplinkedsrvlogin.
Instead of having to use sp_addlinkedsrvlogin to create a predetermined login mapping, SQL Server can
automatically use the Windows security credentials (Windows login name and password) of a user issuing the
query to connect to a linked server when all the following conditions exist:
A user is connected to SQL Server by using Windows Authentication Mode.
Security account delegation is available on the client and sending server.
The provider supports Windows Authentication Mode; for example, SQL Server running on Windows.

NOTE
Delegation does not have to be enabled for single-hop scenarios, but it is required for multiple-hop scenarios.

After the authentication has been performed by the linked server by using the mappings that are defined by
executing sp_addlinkedsrvlogin on the local instance of SQL Server, the permissions on individual objects in the
remote database are determined by the linked server, not the local server.
sp_addlinkedsrvlogin cannot be executed from within a user-defined transaction.

Permissions
Requires ALTER ANY LOGIN permission on the server.

Examples
A. Connecting all local logins to the linked server by using their own user credentials
The following example creates a mapping to make sure that all logins to the local server connect through to the
linked server Accounts by using their own user credentials.
EXEC sp_addlinkedsrvlogin 'Accounts';

Or

EXEC sp_addlinkedsrvlogin 'Accounts', 'true';

NOTE
If there are explicit mappings created for individual logins, they take precedence over any global mappings that may exist for
that linked server.

B. Connecting a specific login to the linked server by using different user credentials
The following example creates a mapping to make sure that the Windows user Domain\Mary connects through to
the linked server Accounts by using the login MaryP and password d89q3w4u .

EXEC sp_addlinkedsrvlogin 'Accounts', 'false', 'Domain\Mary', 'MaryP', 'd89q3w4u';

IMPORTANT
This example does not use Windows Authentication. Passwords will be transmitted unencrypted. Passwords may be visible
in data source definitions and scripts that are saved to disk, in backups, and in log files. Never use an administrator
password in this kind of connection. Consult your network administrator for security guidance specific to your environment.

See Also
Linked Servers Catalog Views (Transact-SQL)
sp_addlinkedserver (Transact-SQL)
sp_droplinkedsrvlogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_catalogs (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the list of catalogs in the specified linked server. This is equivalent to databases in SQL Server.
Transact-SQL Syntax Conventions

Syntax
sp_catalogs [ @server_name = ] 'linked_svr'

Arguments
[ @server_name =] 'linked_svr'
Is the name of a linked server. linked_svr is sysname, with no default.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

Catalog_name nvarchar(128) Name of the catalog

Description nvarchar(4000) Description of the catalog

Permissions
Requires SELECT permission on the schema.

Examples
The following example returns catalog information for the linked server named OLE DB ODBC Linked Server #3 .

NOTE
For sp_catalogs to provide useful information, the OLE DB ODBC Linked Server #3 must already exist.

USE master;
GO
EXEC sp_catalogs 'OLE DB ODBC Linked Server #3';

See Also
sp_addlinkedserver (Transact-SQL)
sp_columns_ex (Transact-SQL)
sp_column_privileges (Transact-SQL)
sp_foreignkeys (Transact-SQL)
sp_indexes (Transact-SQL)
sp_linkedservers (Transact-SQL)
sp_primarykeys (Transact-SQL)
sp_tables_ex (Transact-SQL)
sp_table_privileges (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_column_privileges_ex (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns column privileges for the specified table on the specified linked server.
Transact-SQL Syntax Conventions

Syntax
sp_column_privileges_ex [ @table_server = ] 'table_server'
[ , [ @table_name = ] 'table_name' ]
[ , [ @table_schema = ] 'table_schema' ]
[ , [ @table_catalog = ] 'table_catalog' ]
[ , [ @column_name = ] 'column_name' ]

Arguments
[ @table_server = ] 'table_server'
Is the name of the linked server for which to return information. table_server is sysname, with no default.
[ @table_name = ] 'table_name'
Is the name of the table that contains the specified column. table_name is sysname, with a default of NULL.
[ @table_schema = ] 'table_schema'
Is the table schema. table_schema is sysname, with a default of NULL.
[ @table_catalog = ] 'table_catalog'
Is the name of the database in which the specified table_name resides. table_catalog is sysname, with a default of
NULL.
[ @column_name = ] 'column_name'
Is the name of the column for which to provide privilege information. column_name is sysname, with a default of
NULL (all common).

Result Sets
The following table shows the result set columns. The results returned are ordered by TABLE_QUALIFIER,
TABLE_OWNER, TABLE_NAME, COLUMN_NAME, and PRIVILEGE.

COLUMN NAME DATA TYPE DESCRIPTION

TABLE_CAT sysname Table qualifier name. Various DBMS


products support three-part naming for
tables (qualifier.owner.name). In SQL
Server, this column represents the
database name. In some products, it
represents the server name of the
table's database environment. This field
can be NULL.
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_SCHEM sysname Table owner name. In SQL Server, this


column represents the name of the
database user who created the table.
This field always returns a value.

TABLE_NAME sysname Table name. This field always returns a


value.

COLUMN_NAME sysname Column name, for each column of the


TABLE_NAME returned. This field
always returns a value.

GRANTOR sysname Database user name that has granted


permissions on this COLUMN_NAME
to the listed GRANTEE. In SQL Server,
this column is always the same as the
TABLE_OWNER. This field always
returns a value.

The GRANTOR column can be either


the database owner (TABLE_OWNER)
or someone to whom the database
owner granted permissions by using
the WITH GRANT OPTION clause in the
GRANT statement.

GRANTEE sysname Database user name that has been


granted permissions on this
COLUMN_NAME by the listed
GRANTOR. This field always returns a
value.

PRIVILEGE varchar(32) One of the available column


permissions. Column permissions can
be one of the following values (or other
values supported by the data source
when implementation is defined):

SELECT = GRANTEE can retrieve data


for the columns.

INSERT = GRANTEE can provide data


for this column when new rows are
inserted (by the GRANTEE) into the
table.

UPDATE = GRANTEE can modify


existing data in the column.

REFERENCES = GRANTEE can reference


a column in a foreign table in a primary
key/foreign key relationship. Primary
key/foreign key relationships are
defined with table constraints.
COLUMN NAME DATA TYPE DESCRIPTION

IS_GRANTABLE varchar(3) Indicates whether the GRANTEE is


permitted to grant permissions to other
users (often referred to as "grant with
grant" permission). Can be YES, NO, or
NULL. An unknown, or NULL, value
refers to a data source where "grant
with grant" is not applicable.

Permissions
Requires SELECT permission on the schema.

Examples
The following example returns column privilege information for the HumanResources.Department table in the
AdventureWorks2012 database on the Seattle1 linked server.

EXEC sp_column_privileges_ex @table_server = 'Seattle1',


@table_name = 'Department',
@table_schema = 'HumanResources',
@table_catalog ='AdventureWorks2012';

See Also
sp_table_privileges_ex (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_columns_ex (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the column information, one row per column, for the specified linked server tables. sp_columns_ex
returns column information for only the specific column if column is specified.
Transact-SQL Syntax Conventions

Syntax
sp_columns_ex [ @table_server = ] 'table_server'
[ , [ @table_name = ] 'table_name' ]
[ , [ @table_schema = ] 'table_schema' ]
[ , [ @table_catalog = ] 'table_catalog' ]
[ , [ @column_name = ] 'column' ]
[ , [ @ODBCVer = ] 'ODBCVer' ]

Arguments
[ @table_server = ] 'table_server'
Is the name of the linked server for which to return column information. table_server is sysname, with no default.
[ @table_name = ] 'table_name'
Is the name of the table for which to return column information. table_name is sysname, with a default of NULL.
[ @table_schema = ] 'table_schema'
Is the schema name of the table for which to return column information. table_schema is sysname, with a default
of NULL.
[ @table_catalog = ] 'table_catalog'
Is the catalog name of the table for which to return column information. table_catalog is sysname, with a default
of NULL.
[ @column_name = ] 'column'
Is the name of the database column for which to provide information. column is sysname, with a default of NULL.
[ @ODBCVer = ] 'ODBCVer'
Is the version of ODBC that is being used. ODBCVer is int, with a default of 2. This indicates ODBC Version 2. Valid
values are 2 or 3. For information about the behavior differences between versions 2 and 3, see the ODBC
SQLColumns specification.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_CAT sysname Table or view qualifier name. Various


DBMS products support three-part
naming for tables
(qualifier.owner.name). In SQL Server
this column represents the database
name. In some products, it represents
the server name of the table's database
environment. This field can be NULL.

TABLE_SCHEM sysname Table or view owner name. In SQL


Server, this column represents the
name of the database user that created
the table. This field always returns a
value.

TABLE_NAME sysname Table or view name. This field always


returns a value.

COLUMN_NAME sysname Column name, for each column of the


TABLE_NAME returned. This field
always returns a value.

DATA_TYPE smallint Integer value that correspond to ODBC


type indicators. If this is a data type
that cannot be mapped to an ODBC
type, this value is NULL. The native data
type name is returned in the
TYPE_NAME column.

TYPE_NAME varchar(13) String representing a data type. The


underlying DBMS presents this data
type name.

COLUMN_SIZE int Number of significant digits. The return


value for the PRECISION column is in
base 10.

BUFFER_LENGTH int Transfer size of the data.1

DECIMAL_DIGITS smallint Number of digits to the right of the


decimal point.

NUM_PREC_RADIX smallint Is the base for numeric data types.

NULLABLE smallint Specifies nullability.

1 = NULL is possible.

0 = NOT NULL.

REMARKS varchar(254) This field always returns NULL.

COLUMN_DEF varchar(254) Default value of the column.


COLUMN NAME DATA TYPE DESCRIPTION

SQL_DATA_TYPE smallint Value of the SQL data type as it


appears in the TYPE field of the
descriptor. This column is the same as
the DATA_TYPE column, except for the
datetime and SQL-92 interval data
types. This column always returns a
value.

SQL_DATETIME_SUB smallint Subtype code for datetime and SQL-


92 interval data types. For other data
types, this column returns NULL.

CHAR_OCTET_LENGTH int Maximum length in bytes of a character


or integer data type column. For all
other data types, this column returns
NULL.

ORDINAL_POSITION int Ordinal position of the column in the


table. The first column in the table is 1.
This column always returns a value.

IS_NULLABLE varchar(254) Nullability of the column in the table.


ISO rules are followed to determine
nullability. An ISO SQL-compliant
DBMS cannot return an empty string.

YES = Column can include NULLS.

NO = Column cannot include NULLS.

This column returns a zero-length


string if nullability is unknown.

The value returned for this column is


different from the value returned for
the NULLABLE column.

SS_DATA_TYPE tinyint SQL Server data type, used by extended


stored procedures.

For more information, see the Microsoft ODBC documentation.

Remarks
sp_columns_ex is executed by querying the COLUMNS rowset of the IDBSchemaRowset interface of the OLE
DB provider corresponding to table_server. The table_name, table_schema, table_catalog, and column parameters
are passed to this interface to restrict the rows returned.
sp_columns_ex returns an empty result set if the OLE DB provider of the specified linked server does not support
the COLUMNS rowset of the IDBSchemaRowset interface.

Permissions
Requires SELECT permission on the schema.

Remarks
sp_columns_ex follows the requirements for delimited identifiers. For more information, see Database Identifiers.

Examples
The following example returns the data type of the JobTitle column of the HumanResources.Employee table in the
AdventureWorks2012 database on the linked server Seattle1 .

EXEC sp_columns_ex 'Seattle1',


'Employee',
'HumanResources',
'AdventureWorks2012',
'JobTitle';

See Also
sp_catalogs (Transact-SQL)
sp_foreignkeys (Transact-SQL)
sp_indexes (Transact-SQL)
sp_linkedservers (Transact-SQL)
sp_primarykeys (Transact-SQL)
sp_tables_ex (Transact-SQL)
sp_table_privileges (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_droplinkedsrvlogin (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes an existing mapping between a login on the local server running SQL Server and a login on the linked
server.
Transact-SQL Syntax Conventions

Syntax
sp_droplinkedsrvlogin [ @rmtsrvname= ] 'rmtsrvname' ,
[ @locallogin= ] 'locallogin'

Arguments
[ @rmtsrvname = ] 'rmtsrvname'
Is the name of a linked server that the SQL Server login mapping applies to. rmtsrvname is sysname, with no
default. rmtsrvname must already exist.
[ @locallogin = ] 'locallogin'
Is the SQL Server login on the local server that has a mapping to the linked server rmtsrvname. locallogin is
sysname, with no default. A mapping for locallogin to rmtsrvname must already exist. If NULL, the default
mapping created by sp_addlinkedserver, which maps all logins on the local server to logins on the linked server,
is deleted.

Return Code Values


0 (success) or 1 (failure)

Remarks
When the existing mapping for a login is deleted, the local server uses the default mapping created by
sp_addlinkedserver when it connects to the linked server on behalf of that login. To change the default mapping,
use sp_addlinkedsrvlogin.
If the default mapping is also deleted, only logins that have been explicitly given a login mapping to the linked
server, by using sp_addlinkedsrvlogin, can access the linked server.
sp_droplinkedsrvlogin cannot be executed from within a user-defined transaction.

Permissions
Requires ALTER ANY LOGIN permission on the server.

Examples
A. Removing the login mapping for an existing user
The following example removes the mapping for the login Mary from the local server to the linked server
Accounts . Therefore, login Mary uses the default login mapping.

EXEC sp_droplinkedsrvlogin 'Accounts', 'Mary';

B. Removing the default login mapping


The following example removes the default login mapping originally created by executing sp_addlinkedserver on
the linked server Accounts .

EXEC sp_droplinkedsrvlogin 'Accounts', NULL;

See Also
sp_addlinkedserver (Transact-SQL)
sp_addlinkedsrvlogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_foreignkeys (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the foreign keys that reference primary keys on the table in the linked server.
Transact-SQL Syntax Conventions

Syntax
sp_foreignkeys [ @table_server = ] 'table_server'
[ , [ @pktab_name = ] 'pktab_name' ]
[ , [ @pktab_schema = ] 'pktab_schema' ]
[ , [ @pktab_catalog = ] 'pktab_catalog' ]
[ , [ @fktab_name = ] 'fktab_name' ]
[ , [ @fktab_schema = ] 'fktab_schema' ]
[ , [ @fktab_catalog = ] 'fktab_catalog' ]

Arguments
[ @table_server = ] 'table_server'
Is the name of the linked server for which to return table information. table_server is sysname, with no default.
[ @pktab_name = ] 'pktab_name'
Is the name of the table with a primary key. pktab_name is sysname, with a default of NULL.
[ @pktab_schema = ] 'pktab_schema'
Is the name of the schema with a primary key. pktab_schemais sysname, with a default of NULL. In SQL Server,
this contains the owner name.
[ @pktab_catalog = ] 'pktab_catalog'
Is the name of the catalog with a primary key. pktab_catalogis sysname, with a default of NULL. In SQL Server,
this contains the database name.
[ @fktab_name = ] 'fktab_name'
Is the name of the table with a foreign key. fktab_nameis sysname, with a default of NULL.
[ @fktab_schema = ] 'fktab_schema'
Is the name of the schema with a foreign key. fktab_schemais sysname, with a default of NULL.
[ @fktab_catalog = ] 'fktab_catalog'
Is the name of the catalog with a foreign key. fktab_catalogis sysname, with a default of NULL.

Return Code Values


None

Result Sets
Various DBMS products support three-part naming for tables (catalog.schema.table), which is represented in the
result set.

COLUMN NAME DATA TYPE DESCRIPTION

PKTABLE_CAT sysname Catalog for the table in which the


primary key resides.

PKTABLE_SCHEM sysname Schema for the table in which the


primary key resides.

PKTABLE_NAME sysname Name of the table (with the primary


key). This field always returns a value.

PKCOLUMN_NAME sysname Name of the primary key column or


columns, for each column of the
TABLE_NAME returned. This field
always returns a value.

FKTABLE_CAT sysname Catalog for the table in which the


foreign key resides.

FKTABLE_SCHEM sysname Schema for the table in which the


foreign key resides.

FKTABLE_NAME sysname Name of the table (with a foreign key).


This field always returns a value.

FKCOLUMN_NAME sysname Name of the foreign key columns, for


each column of the TABLE_NAME
returned. This field always returns a
value.

KEY_SEQ smallint Sequence number of the column in a


multicolumn primary key. This field
always returns a value.

UPDATE_RULE smallint Action applied to the foreign key when


the SQL operation is an update. SQL
Server returns 0, 1, or 2 for these
columns:

0=CASCADE changes to foreign key.

1=NO ACTION changes if foreign key is


present.

2=SET_NULL; set foreign key to NULL.

DELETE_RULE smallint Action applied to the foreign key when


the SQL operation is a deletion. SQL
Server returns 0, 1, or 2 for these
columns:

0=CASCADE changes to foreign key.

1=NO ACTION changes if foreign key is


present.

2=SET_NULL; set foreign key to NULL.


COLUMN NAME DATA TYPE DESCRIPTION

FK_NAME sysname Foreign key identifier. It is NULL if not


applicable to the data source. SQL
Server returns the FOREIGN KEY
constraint name.

PK_NAME sysname Primary key identifier. It is NULL if not


applicable to the data source. SQL
Server returns the PRIMARY KEY
constraint name.

DEFERRABILITY smallint Indicates whether constraint checking is


deferrable.

In the result set, the FK_NAME and PK_NAME columns always return NULL.

Remarks
sp_foreignkeys queries the FOREIGN_KEYS rowset of the IDBSchemaRowset interface of the OLE DB provider
that corresponds to table_server. The table_name, table_schema, table_catalog, and column parameters are
passed to this interface to restrict the rows returned.

Permissions
Requires SELECT permission on the schema.

Examples
The following example returns foreign key information about the Department table in the AdventureWorks2012
database on the linked server, Seattle1 .

EXEC sp_foreignkeys @table_server = N'Seattle1',


@pktab_name = N'Department',
@pktab_catalog = N'AdventureWorks2012';

See Also
sp_catalogs (Transact-SQL)
sp_column_privileges (Transact-SQL)
sp_indexes (Transact-SQL)
sp_linkedservers (Transact-SQL)
sp_primarykeys (Transact-SQL)
sp_tables_ex (Transact-SQL)
sp_table_privileges (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_indexes (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns index information for the specified remote table.
Transact-SQL Syntax Conventions

Syntax
sp_indexes [ @table_server = ] 'table_server'
[ , [ @table_name = ] 'table_name' ]
[ , [ @table_schema = ] 'table_schema' ]
[ , [ @table_catalog = ] 'table_db' ]
[ , [ @index_name = ] 'index_name' ]
[ , [ @is_unique = ] 'is_unique' ]

Arguments
[ @table_server= ] 'table_server'
Is the name of a linked server running SQL Server for which table information is being requested. table_server is
sysname, with no default.
[ @table_name= ] 'table_name'
Is the name of the remote table for which to provide index information. table_name is sysname, with a default of
NULL. If NULL, all tables in the specified database are returned.
[ @table_schema= ] 'table_schema'
Specifies the table schema. In the SQL Server environment, this corresponds to the table owner. table_schema is
sysname, with a default of NULL.
[ @table_catalog= ] 'table_db'
Is the name of the database in which table_name resides. table_db is sysname, with a default of NULL. If NULL,
table_db defaults to master.
[ @index_name= ] 'index_name'
Is the name of the index for which information is being requested. index is sysname, with a default of NULL.
[ @is_unique= ] 'is_unique'
Is the type of index for which to return information. is_unique is bit, with a default of NULL, and can be one of the
following values.

VALUE DESCRIPTION

1 Returns information about unique indexes.

0 Returns information about indexes that are not unique.

NULL Returns information about all indexes.


Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_CAT sysname Name of the database in which the


specified table resides.

TABLE_SCHEM sysname Schema for the table.

TABLE_NAME sysname Name of the remote table.

NON_UNIQUE smallint Whether the index is unique or not


unique:

0 = Unique

1 = Not unique

INDEX_QUALIFER sysname Name of the index owner. Some DBMS


products allow for users other than the
table owner to create indexes. In SQL
Server, this column is always the same
as TABLE_NAME.

INDEX_NAME sysname Name of the index.

TYPE smallint Type of index:

0 = Statistics for a table

1 = Clustered

2 = Hashed

3 = Other

ORDINAL_POSITION int Ordinal position of the column in the


index. The first column in the index is 1.
This column always returns a value.

COLUMN_NAME sysname Is the corresponding name of the


column for each column of the
TABLE_NAME returned.

ASC_OR_DESC varchar Is the order used in collation:

A = Ascending

D = Descending

NULL = Not applicable

SQL Server always returns A.

CARDINALITY int Is the number of rows in the table or


unique values in the index.
COLUMN NAME DATA TYPE DESCRIPTION

PAGES int Is the number of pages to store the


index or table.

FILTER_CONDITION nvarchar(4000) SQL Server does not return a value.

Permissions
Requires SELECT permission on the schema.

Examples
The following example returns all index information from the Employees table of the AdventureWorks2012
database on the Seattle1 linked server.

EXEC sp_indexes @table_server = 'Seattle1',


@table_name = 'Employee',
@table_schema = 'HumanResources',
@table_catalog = 'AdventureWorks2012';

See Also
Distributed Queries Stored Procedures (Transact-SQL)
sp_catalogs (Transact-SQL)
sp_column_privileges (Transact-SQL)
sp_foreignkeys (Transact-SQL)
sp_linkedservers (Transact-SQL)
sp_tables_ex (Transact-SQL)
sp_table_privileges (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_linkedservers (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the list of linked servers defined in the local server.
Transact-SQL Syntax Conventions

Syntax
sp_linkedservers

Return Code Values


0 (success) or a nonzero number (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

SRV_NAME sysname Name of the linked server.

SRV_PROVIDERNAME nvarchar(128) Friendly name of the OLE DB provider


managing access to the specified linked
server.

SRV_PRODUCT nvarchar(128) Product name of the linked server.

SRV_DATASOURCE nvarchar(4000) OLE DB data source property


corresponding to the specified linked
server.

SRV_PROVIDERSTRING nvarchar(4000) OLE DB provider string property


corresponding to the linked server.

SRV_LOCATION nvarchar(4000) OLE DB location property


corresponding to the specified linked
server.

SRV_CAT sysname OLE DB catalog property


corresponding to the specified linked
server.

Permissions
Requires SELECT permission on the schema.
See Also
sp_catalogs (Transact-SQL)
sp_column_privileges (Transact-SQL)
sp_columns_ex (Transact-SQL)
sp_foreignkeys (Transact-SQL)
sp_indexes (Transact-SQL)
sp_primarykeys (Transact-SQL)
sp_table_privileges (Transact-SQL)
sp_tables_ex (Transact-SQL)
System Stored Procedures (Transact-SQL)
Distributed Queries Stored Procedures (Transact-SQL)
sp_primarykeys (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the primary key columns, one row per key column, for the specified remote table.
Transact-SQL Syntax Conventions

Syntax
sp_primarykeys [ @table_server = ] 'table_server'
[ , [ @table_name = ] 'table_name' ]
[ , [ @table_schema = ] 'table_schema' ]
[ , [ @table_catalog = ] 'table_catalog' ]

Arguments
[ @table_server = ] 'table_server'
Is the name of the linked server from which to return primary key information. table_server is sysname, with no
default.
[ @table_name = ] 'table_name'
Is the name of the table for which to provide primary key information. table_nameis sysname, with a default of
NULL.
[ @table_schema = ] 'table_schema'
Is the table schema. table_schema is sysname, with a default of NULL. In the SQL Server environment, this
corresponds to the table owner.
[ @table_catalog = ] 'table_catalog'
Is the name of the catalog in which the specified table_name resides. In the SQL Server environment, this
corresponds to the database name. table_catalog is sysname, with a default of NULL.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_CAT sysname Table catalog.

TABLE_SCHEM sysname Table schema.

TABLE_NAME sysname Name of the table.

COLUMN_NAME sysname Name of the column.


COLUMN NAME DATA TYPE DESCRIPTION

KEY_SEQ int Sequence number of the column in a


multicolumn primary key.

PK_NAME sysname Primary key identifier. Returns NULL if


not applicable to the data source.

Remarks
sp_primarykeys is executed by querying the PRIMARY_KEYS rowset of the IDBSchemaRowset interface of the
OLE DB provider corresponding to table_server. The table_name, table_schema, table_catalog, and column
parameters are passed to this interface to restrict the rows returned.
sp_primarykeys returns an empty result set if the OLE DB provider of the specified linked server does not
support the PRIMARY_KEYS rowset of the IDBSchemaRowset interface.

Permissions
Requires SELECT permission on the schema.

Examples
The following example returns primary key columns from the LONDON1 server for the
HumanResources.JobCandidate table in the AdventureWorks2012 database.

EXEC sp_primarykeys @table_server = N'LONDON1',


@table_name = N'JobCandidate',
@table_catalog = N'AdventureWorks2012',
@table_schema = N'HumanResources';

See Also
Distributed Queries Stored Procedures (Transact-SQL)
sp_catalogs (Transact-SQL)
sp_column_privileges (Transact-SQL)
sp_foreignkeys (Transact-SQL)
sp_indexes (Transact-SQL)
sp_linkedservers (Transact-SQL)
sp_tables_ex (Transact-SQL)
sp_table_privileges (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_serveroption (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sets server options for remote servers and linked servers.
Transact-SQL Syntax Conventions

Syntax
sp_serveroption [@server = ] 'server'
,[@optname = ] 'option_name'
,[@optvalue = ] 'option_value' ;

Arguments
[ @server = ] 'server'
Is the name of the server for which to set the option. server is sysname, with no default.
[ @optname = ] 'option_name'
Is the option to set for the specified server. option_name is varchar(35), with no default. option_name can be any
of the following values.

VALUE DESCRIPTION

collation compatible Affects Distributed Query execution against linked servers. If


this option is set to true, SQL Server assumes that all
characters in the linked server are compatible with the local
server, with regard to character set and collation sequence (or
sort order). This enables SQL Server to send comparisons on
character columns to the provider. If this option is not set,
SQL Server always evaluates comparisons on character
columns locally.

This option should be set only if it is certain that the data


source corresponding to the linked server has the same
character set and sort order as the local server.

collation name Specifies the name of the collation used by the remote data
source if use remote collation is true and the data source is
not a SQL Server data source. The name must be one of the
collations supported by SQL Server.

Use this option when accessing an OLE DB data source other


than SQL Server, but whose collation matches one of the SQL
Server collations.

The linked server must support a single collation to be used


for all columns in that server. Do not set this option if the
linked server supports multiple collations within a single data
source, or if the linked server's collation cannot be determined
to match one of the SQL Server collations.
VALUE DESCRIPTION

connect timeout Time-out valuein seconds for connecting to a linked server.

If 0, use the sp_configure default.

data access Enables and disables a linked server for distributed query
access. Can be used only for sys.server entries added
through sp_addlinkedserver.

dist Distributor.

lazy schema validation Determines whether the schema of remote tables will be
checked.

If true, skip schema checking of remote tables at the


beginning of the query.

pub Publisher.

query timeout Time-out value for queries against a linked server.

If 0, use the sp_configure default.

rpc Enables RPC from the given server.

rpc out Enables RPC to the given server.

sub Subscriber.

system Identified for informational purposes only. Not supported.


Future compatibility is not guaranteed.

use remote collation Determines whether the collation of a remote column or of a


local server will be used.

If true, the collation of remote columns is used for SQL Server


data sources, and the collation specified in collation name is
used for non- SQL Server data sources.

If false, distributed queries will always use the default


collation of the local server, while collation name and the
collation of remote columns are ignored. The default is false.
(The false value is compatible with the collation semantics
used in SQL Server 7.0.)
VALUE DESCRIPTION

remote proc transaction promotion Use this option to protect the actions of a server-to-server
procedure through a Microsoft Distributed Transaction
Coordinator (MS DTC) transaction. When this option is TRUE
(or ON) calling a remote stored procedure starts a distributed
transaction and enlists the transaction with MS DTC. The
instance of SQL Server making the remote stored procedure
call is the transaction originator and controls the completion
of the transaction. When a subsequent COMMIT
TRANSACTION or ROLLBACK TRANSACTION statement is
issued for the connection, the controlling instance requests
that MS DTC manage the completion of the distributed
transaction across the computers involved.

After a Transact-SQL distributed transaction has been started,


remote stored procedure calls can be made to other instances
of SQL Server that have been defined as linked servers. The
linked servers are all enlisted in the Transact-SQL distributed
transaction, and MS DTC ensures that the transaction is
completed against each linked server.

If this option is set to FALSE (or OFF), a local transaction will


not be promoted to a distributed transaction while calling a
remote procedure call on a linked server.

If before making a server-to-server procedure call, the


transaction is already a distributed transaction, then this
option does not have effect. The procedure call against linked
server will run under the same distributed transaction.

If before making a server-to-server procedure call, there is no


transaction active in the connection, then this option does not
have effect. The procedure then runs against linked server
without active transactions.

The default value for this option is TRUE (or ON).

[ @optvalue =] 'option_value'
Specifies whether or not the option_name should be enabled (TRUE or on) or disabled (FALSE or off).
option_value is varchar(10), with no default.
option_value may be a nonnegative integer for the connect timeout and query timeout options. For the
collation name option, option_value may be a collation name or NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
If the collation compatible option is set to TRUE, collation name automatically will be set to NULL. If collation
name is set to a nonnull value, collation compatible automatically will be set to FALSE.

Permissions
Requires ALTER ANY LINKED SERVER permission on the server.

Examples
The following example configures a linked server corresponding to another instance of SQL Server, SEATTLE3 , to
be collation compatible with the local instance of SQL Server.

USE master;
EXEC sp_serveroption 'SEATTLE3', 'collation compatible', 'true';

See Also
Distributed Queries Stored Procedures (Transact-SQL)
sp_adddistpublisher (Transact-SQL)
sp_addlinkedserver (Transact-SQL)
sp_dropdistpublisher (Transact-SQL)
sp_helpserver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_table_privileges_ex (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns privilege information about the specified table from the specified linked server.
Transact-SQL Syntax Conventions

Syntax
sp_table_privileges_ex [ @table_server = ] 'table_server'
[ , [ @table_name = ] 'table_name' ]
[ , [ @table_schema = ] 'table_schema' ]
[ , [ @table_catalog = ] 'table_catalog' ]
[ , [@fUsePattern =] 'fUsePattern']

Arguments
[ @table_server = ] 'table_server'
Is the name of the linked server for which to return information. table_server is sysname, with no default.
[ @table_name = ] 'table_name']
Is the name of the table for which to provide table privilege information. table_name is sysname, with a default of
NULL.
[ @table_schema = ] 'table_schema'
Is the table schema. This in some DBMS environments is the table owner. table_schema is sysname, with a default
of NULL.
[ @table_catalog = ] 'table_catalog'
Is the name of the database in which the specified table_name resides. table_catalog is sysname, with a default of
NULL.
[ @fUsePattern =] 'fUsePattern'
Determines whether the characters '_', '%', '[', and ']' are interpreted as wildcard characters. Valid values are 0
(pattern matching is off) and 1 (pattern matching is on). fUsePattern is bit, with a default of 1.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_CAT sysname Table qualifier name. Various DBMS


products support three-part naming for
tables (qualifier.owner.name). In SQL
Server, this column represents the
database name. In some products, it
represents the server name of the
table's database environment. This field
can be NULL.

TABLE_SCHEM sysname Table owner name. In SQL Server, this


column represents the name of the
database user who created the table.
This field always returns a value.

TABLE_NAME sysname Table name. This field always returns a


value.

GRANTOR sysname Database username that has granted


permissions on this TABLE_NAME to
the listed GRANTEE. In SQL Server, this
column is always the same as the
TABLE_OWNER. This field always
returns a value. Also, the GRANTOR
column may be either the database
owner (TABLE_OWNER) or a user to
whom the database owner granted
permission by using the WITH GRANT
OPTION clause in the GRANT
statement.

GRANTEE sysname Database username that has been


granted permissions on this
TABLE_NAME by the listed GRANTOR.
This field always returns a value.
COLUMN NAME DATA TYPE DESCRIPTION

PRIVILEGE varchar(32) One of the available table permissions.


Table permissions can be one of the
following values, or other values
supported by the data source when
implementation is defined.

SELECT = GRANTEE can retrieve data


for one or more of the columns.

INSERT = GRANTEE can provide data


for new rows for one or more of the
columns.

UPDATE = GRANTEE can modify


existing data for one or more of the
columns.

DELETE = GRANTEE can remove rows


from the table.

REFERENCES = GRANTEE can reference


a column in a foreign table in a primary
key/foreign key relationship. In SQL
Server, primary key/foreign key
relationships are defined by using table
constraints.

The scope of action given to the


GRANTEE by a specific table privilege is
data source-dependent. For example,
the UPDATE permission could enable
the GRANTEE to update all columns in
a table on one data source and only
those columns for which the GRANTOR
has UPDATE permission on another
data source.

IS_GRANTABLE varchar(3) Indicates whether the GRANTEE is


permitted to grant permissions to other
users. This is often referred to as "grant
with grant" permission. Can be YES, NO,
or NULL. An unknown, or NULL, value
refers to a data source in which "grant
with grant" is not applicable.

Remarks
The results returned are ordered by TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, and PRIVILEGE.

Permissions
Requires SELECT permission on the schema.

Examples
The following example returns privilege information about tables with names that start with Product in the
AdventureWorks2012 database from the specified linked server Seattle1 . ( SQL Server is assumed as the linked
server).
EXEC sp_table_privileges_ex @table_server = 'Seattle1',
@table_name = 'Product%',
@table_schema = 'Production',
@table_catalog ='AdventureWorks2012';

See Also
sp_column_privileges_ex (Transact-SQL)
System Stored Procedures (Transact-SQL)
Distributed Queries Stored Procedures (Transact-SQL)
sp_tables_ex (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns table information about the tables from the specified linked server.
Transact-SQL Syntax Conventions

Syntax
sp_tables_ex [ @table_server = ] 'table_server'
[ , [ @table_name = ] 'table_name' ]
[ , [ @table_schema = ] 'table_schema' ]
[ , [ @table_catalog = ] 'table_catalog' ]
[ , [ @table_type = ] 'table_type' ]
[ , [@fUsePattern = ] 'fUsePattern' ]

Arguments
[ @table_server= ] 'table_server'
Is the name of the linked server for which to return table information. table_server is sysname, with no default.
[ , [ @table_name= ] 'table_name']
Is the name of the table for which to return data type information. table_nameis sysname, with a default of
NULL.
[ @table_schema= ] 'table_schema']
Is the table schema. table_schemais sysname, with a default of NULL.
[ @table_catalog= ] 'table_catalog'
Is the name of the database in which the specified table_name resides. table_catalog is sysname, with a default
of NULL.
[ @table_type= ] 'table_type'
Is the type of the table to return. table_type is sysname, with a default of NULL, and can have one of the
following values.

VALUE DESCRIPTION

ALIAS Name of an alias.

GLOBAL TEMPORARY Name of a temporary table available system wide.

LOCAL TEMPORARY Name of a temporary table available only to the current job.

SYNONYM Name of a synonym.

SYSTEM TABLE Name of a system table.


VALUE DESCRIPTION

SYSTEM VIEW Name of a system view.

TABLE Name of a user table.

VIEW Name of a view.

[ @fUsePattern= ] 'fUsePattern'
Determines whether the characters _, %, [, and ] are interpreted as wildcard characters. Valid values are 0 (pattern
matching is off) and 1 (pattern matching is on). fUsePattern is bit, with a default of 1.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_CAT sysname Table qualifier name. Various DBMS


products support three-part naming
for tables (qualifier.owner.name). In
SQL Server, this column represents the
database name. In some other
products, it represents the server name
of the database environment of the
table. This field can be NULL.

TABLE_SCHEM sysname Table owner name. In SQL Server, this


column represents the name of the
database user who created the table.
This field always returns a value.

TABLE_NAME sysname Table name. This field always returns a


value.

TABLE_TYPE varchar(32) Table, system table, or view.

REMARKS varchar(254) SQL Server does not return a value for


this column.

Remarks
sp_tables_ex is executed by querying the TABLES rowset of the IDBSchemaRowset interface of the OLE DB
provider corresponding to table_server. The table_name, table_schema, table_catalog, and column parameters
are passed to this interface to restrict the rows returned.
sp_tables_ex returns an empty result set if the OLE DB provider of the specified linked server does not support
the TABLES rowset of the IDBSchemaRowset interface.

Permissions
Requires SELECT permission on the schema.
Examples
The following example returns information about the tables that are contained in the HumanResources schema in
the AdventureWorks2012 database on the LONDON2 linked server.

EXEC sp_tables_ex @table_server = 'LONDON2',


@table_catalog = 'AdventureWorks2012',
@table_schema = 'HumanResources',
@table_type = 'TABLE';

See Also
Distributed Queries Stored Procedures (Transact-SQL)
sp_catalogs (Transact-SQL)
sp_columns_ex (Transact-SQL)
sp_column_privileges (Transact-SQL)
sp_foreignkeys (Transact-SQL)
sp_indexes (Transact-SQL)
sp_linkedservers (Transact-SQL)
sp_table_privileges (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_testlinkedserver (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Tests the connection to a linked server. If the test is unsuccessful the procedure raises an exception with the reason
of the failure.
Transact-SQL Syntax Conventions

Syntax
sp_testlinkedserver [ @servername ] = servername

Arguments
[ @servername = ]servername
Is the name of the linked server. servername is sysname, with no default value.

Result Sets
None

Permissions
No permissions are checked; however, the caller must have the appropriate login mapping.

Examples
The following example creates a linked server named SEATTLESales , and then tests the connection.

USE master;
GO
EXEC sp_addlinkedserver
'SEATTLESales',
N'SQL Server';
GO
sp_testlinkedserver SEATTLESales;
GO

See Also
sp_addlinkedserver (Transact-SQL)
sp_addlinkedsrvlogin (Transact-SQL)
Firewall Rules Stored Procedures (Azure SQL
Database)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
This section contains the following stored procedures that set or delete firewall rules. Transact-SQL firewall rules
can be used with SQL Database and SQL Data Warehouse. For more information, see Configure Azure SQL
Database firewall rules - overview.

sp_set_firewall_rule (Azure SQL Database) sp_delete_firewall_rule (Azure SQL Database)

sp_set_database_firewall_rule (Azure SQL Database) sp_delete_database_firewall_rule (Azure SQL Database)

For SQL Server, use Window firewall rules. For more information, see Configure a Windows Firewall for Database
Engine Access.
sp_set_firewall_rule (Azure SQL Database)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
Creates or updates the server-level firewall settings for your SQL Database server. This stored procedure is only
available in the master database to the server-level principal login or assigned Azure Active Directory principal.

Syntax
sp_set_firewall_rule [@name =] 'name',
[@start_ip_address =] 'start_ip_address',
[@end_ip_address =] 'end_ip_address'
[ ; ]

Arguments
The following table demonstrates the supported arguments and options in Microsoft Azure SQL Database.

NAME DATATYPE DESCRIPTION

[@name =] 'name' NVARCHAR(128) The name used to describe and


distinguish the server-level firewall
setting.

[@start_ip_address =] 'start_ip_address' VARCHAR(50) The lowest IP address in the range of


the server-level firewall setting. IP
addresses equal to or greater than this
can attempt to connect to the SQL
Database server. The lowest possible IP
address is 0.0.0.0 .

[@end_ip_address =] 'end_ip_address' VARCHAR(50) The highest IP address in the range of


the server-level firewall setting. IP
addresses equal to or less than this can
attempt to connect to the SQL
Database server. The highest possible IP
address is 255.255.255.255 .

Note: Azure connection attempts are


allowed when both this field and the
start_ip_address field equals 0.0.0.0 .

Remarks
The names of server-level firewall settings must be unique. If the name of the setting provided for the stored
procedure already exists in the firewall settings table, the starting and ending IP addresses will be updated.
Otherwise, a new server-level firewall setting will be created.
When you add a server-level firewall setting where the beginning and ending IP addresses are equal to 0.0.0.0 ,
you enable access to your SQL Database server from Azure. Provide a value to the name parameter that will help
you remember what the server-level firewall setting is for.
In SQL Database, login data required to authenticate a connection and server-level firewall rules are temporarily
cached in each database. This cache is periodically refreshed. To force a refresh of the authentication cache and
make sure that a database has the latest version of the logins table, execute DBCC FLUSHAUTHCACHE (Transact-
SQL).

Permissions
Only the server-level principal login created by the provisioning process or an Azure Active Directory principal
assigned as admin can create or modify server level firewall rules. The user must be connected to the master
database to execute sp_set_firewall_rule.

Examples
The following code creates a server-level firewall setting called Allow Azure that enables access from Azure.
Execute the following in the virtual master database.

-- Enable Windows Azure connections.


exec sp_set_firewall_rule N'Allow Azure', '0.0.0.0', '0.0.0.0';

The following code creates a server-level firewall setting called Example setting 1 for only the IP address 0.0.0.2
. Then, the sp_set_firewall_rule stored procedure is called again to update the end IP address to 0.0.0.4 , in that
firewall setting. This creates a range which allows IP addresses 0.0.0.2 , 0.0.0.3 , and 0.0.0.4 to access the
server.

-- Create server-level firewall setting for only IP 0.0.0.2


exec sp_set_firewall_rule N'Example setting 1', '0.0.0.2', '0.0.0.2';

-- Update server-level firewall setting to create a range of allowed IP addresses


exec sp_set_firewall_rule N'Example setting 1', '0.0.0.2', '0.0.0.4';

See Also
Azure SQL Database Firewall
How to: Configure Firewall Settings (Azure SQL Database)
sys.firewall_rules (Azure SQL Database)
sp_set_database_firewall_rule (Azure SQL Database)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
Creates or updates the database-level firewall rules for your Azure SQL Database. Database firewall rules can be
configured for the master database, and for user databases on SQL Database. Database firewall rules are
particularly useful when using contained database users. For more information, see Contained Database Users -
Making Your Database Portable.

Syntax
sp_set_database_firewall_rule [@name = ] [N]'name'
, [@start_ip_address =] 'start_ip_address'
, [@end_ip_address =] 'end_ip_address'
[ ; ]

Arguments
[@name = ] [N]'name'
The name used to describe and distinguish the database-level firewall setting. name is nvarchar(128) with no
default value. The Unicode identifier N is optional for SQL Database.
[@start_ip_address =] 'start_ip_address'
The lowest IP address in the range of the database-level firewall setting. IP addresses equal to or greater than this
can attempt to connect to the SQL Database instance. The lowest possible IP address is 0.0.0.0 . start_ip_address is
varchar(50) with no default value.
[@end_ip_address =] 'end_ip_address'
The highest IP address in the range of the database-level firewall setting. IP addresses equal to or less than this can
attempt to connect to the SQL Database instance. The highest possible IP address is 255.255.255.255 .
end_ip_address is varchar(50) with no default value.
The following table demonstrates the supported arguments and options in SQL Database.

NOTE
Azure connection attempts are allowed when both this field and the start_ip_address field equals 0.0.0.0 .

Remarks
The names of database-level firewall settings for a database must be unique. If the name of the database-level
firewall setting provided for the stored procedure already exists in the database-level firewall settings table, the
starting and ending IP addresses will be updated. Otherwise, a new database-level firewall setting will be created.
When you add a database-level firewall setting where the beginning and ending IP addresses are equal to 0.0.0.0
, you enable access to your database in the SQL Database server from any Azure resource. Provide a value to the
name parameter that will help you remember what the firewall setting is for.
Permissions
Requires CONTROL permission on the database.

Examples
The following code creates a database-level firewall setting called Allow Azure that enables access to your
database from Azure.

-- Enable Azure connections.


EXECUTE sp_set_database_firewall_rule N'Allow Azure', '0.0.0.0', '0.0.0.0';

The following code creates a database-level firewall setting called Example DB Setting 1 for only the IP address
0.0.0.4 . Then, the sp_set_database firewall_rule stored procedure is called again to update the end IP address to
0.0.0.6 , in that firewall setting. This creates a range which allows IP addresses 0.0.0.4 , 0.0.0.5 , and 0.0.0.6 to
access the database.

-- Create database-level firewall setting for only IP 0.0.0.4


EXECUTE sp_set_database_firewall_rule N'Example DB Setting 1', '0.0.0.4', '0.0.0.4';

-- Update database-level firewall setting to create a range of allowed IP addresses


EXECUTE sp_set_database_firewall_rule N'Example DB Setting 1', '0.0.0.4', '0.0.0.6';

See Also
Azure SQL Database Firewall
How to: Configure Firewall Settings (Azure SQL Database)
sp_set_firewall_rule (Azure SQL Database)
sp_delete_database_firewall_rule (Azure SQL Database)
sys.database_firewall_rules (Azure SQL Database)
sp_delete_firewall_rule (Azure SQL Database)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
Removes server-level firewall settings from your SQL Database server. This stored procedure is only available in
the master database to the server-level principal login.

Syntax
sp_delete_firewall_rule [@name =] 'name'
[ ; ]

Arguments
The argument of the stored procedure is:
[@name =] 'name'
The name of the server-level firewall setting that will be removed. name is nvarchar (128) with no default.

Remarks
In SQL Database, login data required to authenticate a connection and server-level firewall rules are temporarily
cached in each database. This cache is periodically refreshed. To force a refresh of the authentication cache and
make sure that a database has the latest version of the logins table, execute DBCC FLUSHAUTHCACHE (Transact-
SQL).

Permissions
Only the server-level principal login created by the provisioning process can delete server level firewall rules. The
user must be connected to the master database to execute sp_delete_firewall_rule.

Example
The following example removes the server-level firewall setting named 'Example setting 1'. Execute the statement
in the virtual master database.

EXEC sp_delete_firewall_rule N'Example setting 1';

See Also
Azure SQL Database Firewall
How to: Configure Firewall Settings (Azure SQL Database)
sp_set_firewall_rule (Azure SQL Database)
sys.firewall_rules (Azure SQL Database)
sp_delete_database_firewall_rule (Azure SQL
Database)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
Removes database-level firewall setting from your Azure SQL Database. Database firewall rules can be configured
and deleted for the master database, and for user databases on SQL Database.

Syntax
sp_delete_database_firewall_rule [@name =] [N]'name'
[ ; ]

Arguments
[@name =] 'name'
The name of the database-level firewall setting that will be removed. name is nvarchar(128) with no default value.
The Unicode identifier N is optional for SQL Database.

Permissions
Only the server-level principal login created by the provisioning process or an Azure Active Directory principal
assigned as admin can delete database-level firewall rules.

Example
The following example removes the database-level firewall setting named Example DB Setting 1 .

-- Remove database-level firewall setting


EXECUTE sp_delete_database_firewall_rule N'Example DB Setting 1';

See Also
Azure SQL Database Firewall
How to: Configure Firewall Settings (Azure SQL Database)
sp_set_firewall_rule (Azure SQL Database)
sp_set_database_firewall_rule (Azure SQL Database)
sys.database_firewall_rules (Azure SQL Database)
Full-Text Search and Semantic Search Stored
Procedures (Transact-SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
SQL Server supports the following system stored procedures that are used to implement and query full-text
indexes and semantic indexes.

Full-Text Search Stored Procedures


sp_fulltext_catalog
Creates and drops a full-text catalog, and starts and stops the indexing action for a catalog. Multiple full-text
catalogs can be created for each database.
This feature will be removed in a future version of Microsoft SQL Server. Do not use this feature in new
development work, and modify applications that currently use this feature as soon as possible. Use CREATE
FULLTEXT CATALOG, ALTER FULLTEXT CATALOG, and DROP FULLTEXT CATALOG instead.
sp_fulltext_column
Specifies whether or not a particular column of a table participates in full-text indexing.
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature. Use ALTER FULLTEXT INDEX
instead.
sp_fulltext_database
Has no effect on full-text catalogs in SQL Server 2008 and later versions and is supported for backward
compatibility only.
This feature will be removed in a future version of Microsoft SQL Server. Do not use this feature in new
development work, and modify applications that currently use this feature as soon as possible.
sp_fulltext_keymappings
Returns mappings between document identifiers (DocIds) and full-text key values.
sp_fulltext_load_thesaurus_file
Parses and loads the data from an updated thesaurus file that corresponds to an LCID and causes recompilation of
full-text queries that use the thesaurus.
sp_fulltext_pendingchanges
Returns unprocessed changes, such as pending inserts, updates, and deletes, for a specified table that is using
change tracking.
sp_fulltext_service
Changes the server properties of full-text search for SQL Server.
sp_fulltext_table
Marks or unmarks a table for full-text indexing.
This feature will be removed in a future version of Microsoft SQL Server. Do not use this feature in new
development work, and modify applications that currently use this feature as soon as possible. Use CREATE
FULLTEXT INDEX, ALTER FULLTEXT INDEX, and DROP FULLTEXT INDEX instead.
sp_help_fulltext_catalog_components
Returns a list of all components (filters, word-breakers, and protocol handlers), used for all full-text catalogs in the
current database.
This feature will be removed in a future version of Microsoft SQL Server. Do not use this feature in new
development work, and modify applications that currently use this feature as soon as possible.
sp_help_fulltext_catalogs
Returns the ID, name, root directory, status, and number of full-text indexed tables for the specified full-text
catalog.
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature. Use the sys.fulltext_catalogs
catalog view instead.
sp_help_fulltext_catalogs_cursor
Uses a cursor to return the ID, name, root directory, status, and number of full-text indexed tables for the specified
full-text catalog.
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature. Use the sys.fulltext_catalogs
catalog view instead.
sp_help_fulltext_columns
Returns the columns designated for full-text indexing.
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature. Use the
sys.fulltext_index_columns catalog view instead.
sp_help_fulltext_columns_cursor
Uses a cursor to return the columns designated for full-text indexing.
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature. Use the
sys.fulltext_index_columns catalog view instead.
sp_help_fulltext_system_components
Returns information for the registered word-breakers, filter, and protocol handlers, as well as a list of identifiers of
databases and full-text catalogs that have used a specified component.
sp_help_fulltext_tables
Returns a list of tables that are registered for full-text indexing.
sp_help_fulltext_tables_cursor
Returns a list of tables that are registered for full-text indexing.
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use this feature. Use the sys.fulltext_indexes
catalog view instead.

Semantic Search Stored Procedures


sp_fulltext_semantic_register_language_statistics_db (Transact-SQL)
Registers a pre-populated Semantic Language Statistics database in the current instance of SQL Server.
sp_fulltext_semantic_unregister_language_statistics_db (Transact-SQL)
Unregisters an existing Semantic Language Statistics database from the current instance of SQL Server and deletes
any associated metadata.

See Also
Full-Text Search and Semantic Search Catalog Views (Transact-SQL)
Full-Text Search and Semantic Search Dynamic Management Views and Functions (Transact-SQL)
System Stored Procedures (Transact-SQL)
Full-Text Search
sp_fulltext_catalog (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates and drops a full-text catalog, and starts and stops the indexing action for a catalog. Multiple full-text
catalogs can be created for each database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use CREATE FULLTEXT CATALOG, ALTER FULLTEXT
CATALOG, and DROP FULLTEXT CATALOG instead.

Transact-SQL Syntax Conventions

Syntax
sp_fulltext_catalog [ @ftcat= ] 'fulltext_catalog_name' ,
[ @action= ] 'action'
[ , [ @path= ] 'root_directory' ]

Arguments
[ @ftcat=] 'fulltext_catalog_name'
Is the name of the full-text catalog. Catalog names must be unique for each database. fulltext_catalog_name is
sysname.
[ @action=] 'action'
Is the action to be performed. action is varchar(20), and can be one of these values.

NOTE
Full-text catalogs can be created, dropped, and modified as needed. However, avoid making schema changes on multiple
catalogs at the same time. These actions can be performed using the sp_fulltext_table stored procedure, which is the
recommended way.

VALUE DESCRIPTION

Create Creates an empty, new full-text catalog in the file system and
adds an associated row in sysfulltextcatalogs with the
fulltext_catalog_name and root_directory, if present, values.
fulltext_catalog_name must be unique within the database.
VALUE DESCRIPTION

Drop Drops fulltext_catalog_name by removing it from the file


system and deleting the associated row in
sysfulltextcatalogs. This action fails if this catalog contains
indexes for one or more tables. sp_fulltext_table
'table_name', 'drop' should be executed to drop the tables
from the catalog.

An error is displayed if the catalog does not exist.

start_incremental Starts an incremental population for fulltext_catalog_name.


An error is displayed if the catalog does not exist. If a full-text
index population is already active, a warning is displayed but
no population action occurs. With incremental population only
changed rows are retrieved for full-text indexing, provided
there is a timestamp column present in the table being full-
text indexed.

start_full Starts a full population for fulltext_catalog_name. Every row


of every table associated with this full-text catalog is retrieved
for full-text indexing even if they have already been indexed.

Stop Stops an index population for fulltext_catalog_name. An error


is displayed if the catalog does not exist. No warning is
displayed if population is already stopped.

Rebuild Rebuilds fulltext_catalog_name. When a catalog is rebuilt, the


existing catalog is deleted and a new catalog is created in its
place. All the tables that have full-text indexing references are
associated with the new catalog. Rebuilding resets the full-text
metadata in the database system tables.

If change tracking is OFF, rebuilding does not cause a


repopulation of the newly created full-text catalog. In this
case, to repopulate, execute sp_fulltext_catalog with the
start_full or start_incremental action.

[ @path=] 'root_directory'
Is the root directory (not the complete physical path) for a create action. root_directory is nvarchar(100) and has
a default value of NULL, which indicates the use of the default location specified at setup. This is the Ftdata
subdirectory in the Mssql directory; for example, C:\Program Files\Microsoft SQL
Server\MSSQL13.MSSQLSERVER\MSSQL\FTData. The specified root directory must reside on a drive on the same
computer, consist of more than just the drive letter, and cannot be a relative path. Network drives, removable
drives, floppy disks, and UNC paths are not supported. Full-text catalogs must be created on a local hard drive
associated with an instance of SQL Server.
@path is valid only when action is create. For actions other than create (stop, rebuild, and so on), @path must
be NULL or omitted.
If the instance of SQL Server is a virtual server in a cluster, the catalog directory specified needs to be on a shared
disk drive on which the SQL Server resource depends. If @path is not specified, the location of default catalog
directory is on the shared disk drive, in the directory that was specified when the virtual server was installed.

Return Code Values


0 (success) or 1 (failure)
Result Sets
None

Remarks
The start_full action is used to create a complete snapshot of the full-text data in fulltext_catalog_name. The
start_incremental action is used to re-index only the changed rows in the database. Incremental population can
be applied only if the table has a column of the type timestamp. If a table in the full-text catalog does not contain
a column of the type timestamp, the table undergoes a full population.
Full-text catalog and index data is stored in files created in a full-text catalog directory. The full-text catalog
directory is created as a sub-directory of the directory specified in @path or in the server default full-text catalog
directory if @path is not specified. The name of the full-text catalog directory is built in a way that guarantees it
will be unique on the server. Therefore, all full-text catalog directories on a server can share the same path.

Permissions
The caller is required to be member of the db_owner role. Depending on the action requested, the caller should
not be denied ALTER or CONTROL permissions (which db_owner has) on the target full-text catalog.

Examples
A. Create a full-text catalog
This example creates an empty full-text catalog, Cat_Desc, in the AdventureWorks2012 database.

USE AdventureWorks2012;
GO
EXEC sp_fulltext_catalog 'Cat_Desc', 'create';
GO

B. To rebuild a full-text catalog


This example rebuilds an existing full-text catalog, Cat_Desc, in the AdventureWorks2012 database.

USE AdventureWorks2012;
GO
EXEC sp_fulltext_catalog 'Cat_Desc', 'rebuild';
GO

C. Start the population of a full-text catalog


This example begins a full population of the Cat_Desc catalog.

USE AdventureWorks2012;
GO
EXEC sp_fulltext_catalog 'Cat_Desc', 'start_full';
GO

D. Stop the population of a full-text catalog


This example stops the population of the Cat_Desc catalog.
USE AdventureWorks2012;
GO
EXEC sp_fulltext_catalog 'Cat_Desc', 'stop';
GO

E. To remove a full-text catalog


This example removes the Cat_Desc catalog.

USE AdventureWorks2012;
GO
EXEC sp_fulltext_catalog 'Cat_Desc', 'drop';
GO

See Also
FULLTEXTCATALOGPROPERTY (Transact-SQL)
sp_fulltext_database (Transact-SQL)
sp_help_fulltext_catalogs (Transact-SQL)
sp_help_fulltext_catalogs_cursor (Transact-SQL)
System Stored Procedures (Transact-SQL)
Full-Text Search
sp_fulltext_column (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Specifies whether or not a particular column of a table participates in full-text indexing.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER FULLTEXT INDEX instead.

Transact-SQL Syntax Conventions

Syntax
sp_fulltext_column [ @tabname= ] 'qualified_table_name' ,
[ @colname= ] 'column_name' ,
[ @action= ] 'action'
[ , [ @language= ] 'language_term' ]
[ , [ @type_colname= ] 'type_column_name' ]

Arguments
[ @tabname= ] 'qualified_table_name'
Is a one- or two-part table name. The table must exist in the current database. The table must have a full-text index.
qualified_table_name is nvarchar(517), with no default value.
[ @colname= ] 'column_name'
Is the name of a column in qualified_table_name. The column must be either a character, varbinary(max) or
image column and cannot be a computed column. column_name is sysname, with no default.

NOTE
SQL Server can create full-text indexes of text data stored in columns that are of varbinary(max) or image data type.
Images and pictures are not indexed.

[ @action= ] 'action'
Is the action to be performed. action is varchar(20), with no default value, and can be one of the following values.

VALUE DESCRIPTION

add Adds column_name of qualified_table_name to the table's


inactive full-text index. This action enables the column for full-
text indexing.

drop Removes column_name of qualified_table_name from the


table's inactive full-text index.
[ @language= ] 'language_term'
Is the language of the data stored in the column. For a list of languages included in SQL Server, see
sys.fulltext_languages (Transact-SQL).

NOTE
Use 'Neutral' when a column contains data in multiple languages or in an unsupported language. The default is specified by
the configuration option 'default full-text language'.

[ @type_colname = ] 'type_column_name'
Is the name of a column in qualified_table_name that holds the document type of column_name. This column
must be char, nchar, varchar, or nvarchar. It is only used when the data type of column_name is of type
varbinary(max) or image. type_column_name is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
If the full-text index is active, any ongoing population is stopped. Furthermore, if a table with an active full-text
index has change tracking enabled, SQL Server ensures that the index is current. For example, SQL Server stops
any current population on the table, drops the existing index, and starts a new population.
If change tracking is on and columns need to be added or dropped from the full-text index while preserving the
index, the table should be deactivated, and the required columns should be added or dropped. These actions freeze
the index. The table can be activated later when starting a population is practical.

Permissions
User must be a member of the db_ddladmin fixed database role, or a member of the db_owner fixed database
role, or the owner of the table.

Examples
The following example adds the DocumentSummary column from the Document table to the full-text index of the
table.

USE AdventureWorks2012;
GO
EXEC sp_fulltext_column 'Production.Document', DocumentSummary, 'add';
GO

The following example assumes you created a full-text index on a table named spanishTbl . To add the spanishCol
column to the full-text index, execute the following stored procedure:

EXEC sp_fulltext_column 'spanishTbl', 'spanishCol', 'add', 0xC0A;


GO
When you run this query:

SELECT *
FROM spanishTbl
WHERE CONTAINS(spanishCol, 'formsof(inflectional, trabajar)')

The result set would include rows with different forms of trabajar (to work), such as trabajo , trabajamos , and
trabajan .

NOTE
All columns listed in a single full-text query function clause must use the same language.

See Also
OBJECTPROPERTY (Transact-SQL)
sp_help_fulltext_columns (Transact-SQL)
sp_help_fulltext_columns_cursor (Transact-SQL)
sp_help_fulltext_tables (Transact-SQL)
sp_help_fulltext_tables_cursor (Transact-SQL)
System Stored Procedures (Transact-SQL)
Full-Text Search and Semantic Search Stored Procedures (Transact-SQL)
sp_fulltext_database (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Has no effect on full-text catalogs in SQL Server 2008 and later versions and is supported for backward
compatibility only. sp_fulltext_database does not disable the Full-Text Engine for a given database. All user-
created databases in SQL Server 2017 are always enabled for full-text indexing.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Do not use this feature in new development work,
and modify applications that currently use this feature as soon as possible. Use Management Studio instead.

Transact-SQL Syntax Conventions

Syntax
sp_fulltext_database [@action=] 'action'

Arguments
[ @action=] 'action'
Is the action to be performed. action is varchar(20), and can be one of these values.

VALUE DESCRIPTION

enable Supported for backward compatibility only. Has no effect on


full-text catalogs in SQL Server 2008 and later versions.

disable Supported for backward compatibility only. Has no effect on


full-text catalogs in SQL Server 2008 and later versions.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
In SQL Server 2008 and later versions, full-text indexing cannot be turned off. Disabling full-text indexing does not
remove rows from sysfulltextcatalogs and does not indicate that full-text enabled tables are no longer marked
for full-text indexing. All the full-text metadata definitions are still in the system tables.
Permissions
Only members of the sysadmin fixed server role and db_owner fixed database role can execute
sp_fulltext_database.

See Also
DATABASEPROPERTYEX (Transact-SQL)
FULLTEXTSERVICEPROPERTY (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_fulltext_keymappings (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns mappings between document identifiers (DocIds) and full-text key values. The DocId column contains
values for a bigint integer that maps to a particular full-text key value in a full-text indexed table. DocId values that
satisfy a search condition are passed from the Full-Text Engine to the Database Engine, where they are mapped to
full-text key values from the base table being queried. The full-text key column is a unique index that is required on
one column of the table.
Transact-SQL Syntax Conventions

Syntax
sp_fulltext_keymappings { table_id | table_id, docid | table_id, NULL, key }

Parameters
table_id
Is the object ID of the full-text indexed table. If you specify an invalid table_id, an error is returned. For information
about obtaining the object ID of a table, see OBJECT_ID (Transact-SQL).
docid
Is an internal document identifier (DocId) that corresponds to the key value. An invalid docid value returns no
results.
key
Is the full-text key value from the specified table. An invalid key value returns no results. For information about full-
text key values, see Manage Full-Text Indexes.

IMPORTANT
For information about using one, two, or three parameters, see "Remarks," later in this topic.

Return Code Values


None.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

DocId bigint Is an internal document identifier


(DocId) column that corresponds to the
key value.
COLUMN NAME DATA TYPE DESCRIPTION

Key * Is the full-text key value from the


specified table.

If no full-text keys exist in the mapping


table, an empty rowset is returned.

* The data type for Key is same as the data type of the full-text key column in the base table.

Permissions
This function is public and does not require any special permissions.

Remarks
The following table describes the effect of using one, two, or three parameters.

THIS PARAMETER LIST… HAS THIS RESULT…

table_id When invoked with only the table_id parameter,


sp_fulltext_keymappings returns all full-text key (Key) values
from the specified base table, along with the DocId that
corresponds to each key. This includes keys that are pending
delete.

This function is useful for troubleshooting a variety of issues. It


is particularly useful for seeing the full-text index content
when the selected full-text key is not of an integer data type.
This involves joining the results of sp_fulltext_keymappings
with the results of
sys.dm_fts_index_keywords_by_document. For more
information, see sys.dm_fts_index_keywords_by_document
(Transact-SQL).

In general, however, we recommend that, if possible, you


execute sp_fulltext_keymappings with parameters that specify
a specific full-text key or DocId. This is much more efficient
than returning an entire key map, especially for a very large
table for which the performance cost of returning the entire
key map might be substantial.

table_id, docid If only the table_id and docid are specified, docid must be
nonNULL and specify a valid DocId in the specified table. This
function is useful to isolate the custom full-text key from the
base table that corresponds to the DocId of a particular full-
text index.

table_id, NULL, key If three parameters are present, the second parameter must
be NULL, and key must be nonNULL and specify a valid full-
text key value from the specified table. This function is useful
in isolating the DocId that corresponds to a particular full-text
key from the base table.

An error is returned under any of the following conditions:


You specify an invalid table_id.
The table is not full-text indexed.
NULL is encountered for a parameter that may be nonNULL

Examples
NOTE
The examples in this section use the Production.ProductReview table of the AdventureWorks2012 sample database. You
can create this index by executing the example provided for the ProductReview table in CREATE FULLTEXT INDEX (Transact-
SQL).

A. Obtaining all the Key and DocId values


The following example uses a DECLARE statement to create a local variable, @table_id and to assign the ID of the
ProductReview table as its value. The example executes sp_fulltext_keymappings specifying @table_id for the
table_id parameter.

NOTE
Using sp_fulltext_keymappings with only the table_id parameter is suitable for small tables.

USE AdventureWorks2012;
GO
DECLARE @table_id int = OBJECT_ID(N'Production.ProductReview');
EXEC sp_fulltext_keymappings @table_id;
GO

This example returns all the DocIds and full-text keys from the table, as follows:

docid key

1 1 1

2 2 2

3 3 3

4 4 4

B. Obtaining the DocId value for a specific Key value


The following example uses a DECLARE statement to create a local variable, @table_id , and to assign the ID of the
ProductReview table as its value. The example executes sp_fulltext_keymappings specifying @table_id for the
table_id parameter, NULL for the docid parameter, and 4 for the key parameter.

NOTE
Using sp_fulltext_keymappings with only the table_id parameteris suitable for small tables.
USE AdventureWorks2012;
GO
DECLARE @table_id int = OBJECT_ID(N'Production.ProductReview');
EXEC sp_fulltext_keymappings @table_id, NULL, 4;
GO

This example returns the following results.

docid key

4 4 4

See Also
Full-Text Search and Semantic Search Stored Procedures (Transact-SQL)
sp_fulltext_load_thesaurus_file (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Causes the server instance to parse and load the data from the thesaurus file that corresponds to the language
whose LCID is specified. This stored procedure is useful after updating a thesaurus file. Executing
sp_fulltext_load_thesaurus_file causes recompilation of full-text queries that use the thesaurus of the specified
LCID.
Transact-SQL Syntax Conventions

Syntax
sys.sp_fulltext_load_thesaurus_file lcid [ , @loadOnlyIfNotLoaded = action ]

Arguments
lcid
Integer mapping the locale identifier (LCID) of the language for which you want to lade the thesaurus XML
definition. To obtain the LCIDs of languages that are available on a server instance, use the sys.fulltext_languages
(Transact-SQL) catalog view.
@loadOnlyIfNotLoaded = action
Specifies whether the thesaurus file is loaded into the internal thesaurus tables even if it has already been loaded.
action is one of:

VALUE DEFINITION

0 Load the thesaurus file regardless of whether it is already


loaded. This is the default behavior of
sp_fulltext_load_thesaurus_file.

1 Load the thesaurus file only if it is not yet loaded.

Return Code Values


None

Result Sets
None

Remarks
Thesaurus files are automatically loaded by full-text queries that use the thesaurus. To avoid this first-time
performance impact on full-text queries, we recommend that you execute sp_fulltext_load_thesaurus_file.
Use sp_fulltext_service'update_languages' to update the list of languages registered with full-text search.
Permissions
Only members of the sysadmin fixed server role or the system administrator can execute the
sp_fulltext_load_thesaurus_file stored procedure.
Only system administrators can update, modify, or delete thesaurus files.

Examples
A. Load a thesaurus file even if it is already loaded
The following example parses and loads the English thesaurus file.

EXEC sys.sp_fulltext_load_thesaurus_file 1033;


GO

B. Load a thesaurus file only if it is not yet loaded


The following example parses and loads the Arabic thesaurus file, unless it is already loaded.

EXEC sys.sp_fulltext_load_thesaurus_file 1025, @loadOnlyIfNotLoaded = 1;


GO

See Also
FULLTEXTSERVICEPROPERTY (Transact-SQL)
System Stored Procedures (Transact-SQL)
Configure and Manage Thesaurus Files for Full-Text Search
Configure and Manage Thesaurus Files for Full-Text Search
sp_fulltext_pendingchanges (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns unprocessed changes, such as pending inserts, updates, and deletes, for a specified table that is using
change tracking.
Transact-SQL Syntax Conventions

Syntax
sp_fulltext_pendingchanges table_id

Arguments
table_id
ID of the table. If the table is not full-text indexed, or change tracking is not enabled on the table, an error is
returned.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

Key * Is the full-text key value from the


specified table.

DocId bigint Is an internal document identifier


(DocId) column that corresponds to the
key value.

Status int 0 = Row will be removed from the full-


text index.

1 = Row will be full-text indexed.

2 = Row is up-to-date.

-1 = Row is in a transitional (batched,


but not committed) state or an error
state.

DocState tinyint Is a raw dump of the internal document


identifier (DocId) map status column.

* The data type for Key is same as the data type of the full-text key column in the base table.

Permissions
Requires membership in the sysadmin fixed server role.
Remarks
If there are no changes to process, an empty rowset is returned.
Full-Text Search queries do not return rows with a Status value of 0. This is because the row has been deleted from
base table and is waiting to be deleted from the full-text index.
To find out how many changes are pending for a particular table, use the TableFullTextPendingChanges
property of the OBJECTPROPERTYEX function.

See Also
Full-Text Search and Semantic Search Stored Procedures (Transact-SQL)
OBJECTPROPERTYEX (Transact-SQL)
sp_fulltext_semantic_register_language_statistics_db
(Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Registers a pre-populated Semantic Language Statistics database in the current instance of SQL Server.
You can initiate semantic extraction only after you have attached this language statistics database and registered it
by using this stored procedure. You only need to perform this task once for each instance of SQL Server.
Transact-SQL Syntax Conventions

Syntax
EXEC sp_fulltext_semantic_register_language_statistics_db
[ @dbname = ] ‘database_name’;
GO

Arguments
[ @dbname = ] ‘database_name’
Is the name of the Semantic Language Statistics database to be registered for the current instance of SQL Server.
The database must already be attached. database_name is sysname, and may not be NULL.

Return Code Value


0 (success) or 1 (failure)

Result Set
None.

General Remarks
The Semantic Language Statistics database contains language-related statistics that are required for semantic
processing of textual content.
sp_fulltext_semantic_register_language_statistics_db performs the following steps:
1. Checks that the instance of SQL Server is a version that supports semantic processing.
2. Checks that the instance of SQL Server does not already have a Semantic Language Statistics database
defined.
3. Checks that the database is a valid Semantic Language Statistics database.
4. Sets permissions on the Semantic Language Statistics database to restrict access to the database by users.
5. Inserts the metadata that defines the name of the Semantic Language Statistics database for the instance of
SQL Server.
6. Inserts the metadata that defines the mappings between the installed Semantic Language Statistics database
and the internal Language Model tables.
7. Checks to ensure that the database is ready to be used.
For more information, see Install and Configure Semantic Search.

Metadata

For information about the Semantic Language Statistics database installed on an instance of SQL Server, query the
catalog view sys.fulltext_semantic_language_statistics_database (Transact-SQL).

Security
Permissions
Requires CONTROL SERVER permissions.

Examples
The following example shows how to register the Semantic Language Statistics database by calling
sp_fulltext_semantic_register_language_statistics_db.

EXEC sp_fulltext_semantic_register_language_statistics_db @dbname = 'semanticsDb';


GO

See Also
Install and Configure Semantic Search
sp_fulltext_semantic_unregister_language_statistics_db
(Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Unregisters an existing Semantic Language Statistics database from the current instance of SQL Server and deletes
any associated metadata.
This statement does not detach the database or remove the physical database file from the file system. After you
unregister the database, you can detach it and delete the physical database file.
Transact-SQL Syntax Conventions

Syntax
EXEC sp_fulltext_semantic_unregister_language_statistics_db;
GO

Arguments
This procedure does not require any arguments. Since an instance of SQL Server only has one semantic language
statistics database, it is not necessary to identify the database.

Return Code Value


0 (success) or 1 (failure)

Result Set
None.

General Remarks
When a Semantic Language Statistics database is unregistered, all the metadata associated with it is also removed.
sp_fulltext_semantic_unregister_language_statistics_db performs the following steps:
1. Checks that there are no semantic populations in progress for the current instance of SQL Server.
2. Removes all metadata associated with the specified Semantic Language Statistics database.
For more information, see Install and Configure Semantic Search.

Metadata

For information about the Semantic Language Statistics database installed on an instance of SQL Server, query the
catalog view sys.fulltext_semantic_language_statistics_database (Transact-SQL).
Security
Permissions
Requires CONTROL SERVER permissions.

Examples
The following example shows how to unregister the Semantic Language Statistics database by calling
sp_fulltext_semantic_unregister_language_statistics_db.

EXEC sp_fulltext_semantic_unregister_language_statistics_db;
GO

See Also
Install and Configure Semantic Search
sp_fulltext_service (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the server properties of full-text search for SQL Server.
Transact-SQL Syntax Conventions

Syntax
sp_fulltext_service [ [@action=] 'action'
[ , [ @value= ] value ] ]

Arguments
[ @action=] 'action'
Is the property to be changed or reset. action is nvarchar(100), with no default. For a list of action properties, their
descriptions, and the values that can be set, see the table under the value argument. This argument returns the
following properties: data type, current running value, minimum or maximum value, and deprecation status, if
applicable.
[ @value=] value
Is the value of the specified property. value is sql_variant, with a default value of NULL. If @value is null,
sp_fulltext_service returns the current setting. This table lists action properties, their descriptions, and the values
that can be set.

NOTE
The following actions will be removed in a future release of SQL Server: clean_up, connect_timeout, data_timeout, and
resource_usage. Avoid using these actions in new development work, and plan to modify applications that currently use
any of them.

ACTION DATA TYPE DESCRIPTION

clean_up int Supported for backward compatibility


only. The value is always 0.

connect_timeout int Supported for backward compatibility


only. The value is always 0.

data_timeout int Supported for backward compatibility


only. The value is always 0.
ACTION DATA TYPE DESCRIPTION

load_os_resources int Indicates whether operating system


word breakers, stemmers, and filters are
registered and used with this instance
of SQL Server. One of:

0 = Use only filters and word breakers


specific to this instance of SQL Server.

1 = Load operating system filters and


word breakers.

By default, this property is disabled to


prevent inadvertent behavior changes
by updates made to the operating
system. Enabling use of operating
system resources provides access to
resources for languages and document
types registered with Microsoft
Indexing Service that do not have an
instance-specific resource installed. If
you enable the loading of operating
system resources, ensure that the
operating system resources are trusted
signed binaries; otherwise, they cannot
be loaded when verify_signature (see
below) is set to 1.

master_merge_dop int Specifies the number of threads to be


used by the master merge process. This
value should not exceed the number of
available CPUs or CPU cores.

When this argument is not specified,


the service uses the lesser of 4, or the
number of available CPUs or CPU cores.

pause_indexing int Specifies whether full-text indexing


should be paused, if it is currently
running, or resumed, if it is currently
paused.

0 = Resumes full-text indexing activities


for the server instance.

1 = Pauses full-text indexing activities


for the server instance.

resource_usage int Has no function in SQL Server 2008


and later versions, and is ignored.
ACTION DATA TYPE DESCRIPTION

update_languages NULL Updates the list of languages and filters


that are registered with full-text search.
The languages are specified when
configuring indexing and in full-text
queries. Filters are used by the filter
daemon host to extract textual
information from corresponding file
formats such as .docx stored in data
types, such as varbinary,
varbinary(max), image, or xml, for
full-text indexing.

For more information, see View or


Change Registered Filters and Word
Breakers.
ACTION DATA TYPE DESCRIPTION

upgrade_option int Controls how full-text indexes are


migrated when upgrading a database
from SQL Server 2005 to a later
version. This property applies to
upgrading by attaching a database,
restoring a database backup, restoring
a file backup, or copying the database
by using the Copy Database Wizard.

One of:

0 = Full-text catalogs are rebuilt using


the new and enhanced word breakers.
Rebuilding indexes can take awhile, and
a significant amount of CPU and
memory might be required after the
upgrade.

1 = Full-text catalogs are reset. SQL


Server 2005 full-text catalog files are
removed, but the metadata for full-text
catalogs and full-text indexes is
retained. After being upgraded, all full-
text indexes are disabled for change
tracking and crawls are not started
automatically. The catalog will remain
empty until you manually issue a full
population, after the upgrade
completes.

2 = Full-text catalogs are imported.


Typically, import is significantly faster
than rebuild. For example, when using
only one CPU, import runs about 10
times faster than rebuild. However, an
imported full-text catalog does not use
the new and enhanced word breakers,
so you might want to rebuild your full-
text catalogs eventually.

Note: Rebuild can run in multi-threaded


mode, and if more than 10 CPUs are
available, rebuild might run faster than
import if you allow rebuild to use all of
the CPUs.

If a full-text catalog is not available, the


associated full-text indexes are rebuilt.
This option is available for only SQL
Server 2005 databases.

For information about choosing a full-


text upgrade option, see full-Upgrade
Full-Text Search.

Note: To set this property in SQL Server


Management Studio, use the Full-Text
Upgrade Option property. For more
information, see Manage and Monitor
Full-Text Search for a Server Instance.
ACTION DATA TYPE DESCRIPTION

verify_signature int Indicates whether only signed binaries


are loaded by the Full-Text Engine. By
default, only trusted, signed binaries are
loaded.

1 = Verify that only trusted, signed


binaries are loaded (default).

0 = Do not verify whether binaries are


signed.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Permissions
Only members of the serveradmin fixed server role or the system administrator can execute sp_fulltext_service.

Examples
A. Updating the list of registered languages
The following example updates the list of languages registered with full-text search.

EXEC sp_fulltext_service 'update_languages';


GO

B. Changing the full-text upgrade option to reset full-text catalogs


The following example changes the full-text upgrade option to reset full-text catalogs. This removes them
completely. This example specifies the optional @action and @value keywords.

EXEC sp_fulltext_service @action='upgrade_option', @value=1;


GO

See Also
Full-Text Search
FULLTEXTSERVICEPROPERTY (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_fulltext_table (Transact-SQL)
11/27/2017 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Marks or unmarks a table for full-text indexing.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use CREATE FULLTEXT INDEX, ALTER FULLTEXT INDEX, and
DROP FULLTEXT INDEX instead.

Transact-SQL Syntax Conventions

Syntax
sp_fulltext_table
[ @tabname= ] 'qualified_table_name'
, [ @action= ] 'action'
[
, [ @ftcat= ] 'fulltext_catalog_name'
, [ @keyname= ] 'unique_index_name'
]

Arguments
[ @tabname=] 'qualified_table_name'
Is a one- or two-part table name. The table must exist in the current database. qualified_table_name is
nvarchar(517), with no default.
[ @action=] 'action'
Is the action to be performed. action is nvarchar(50), with no default, and can be one of these values.

VALUE DESCRIPTION

Create Creates the metadata for a full-text index for the table
referenced by qualified_table_name and specifies that the
full-text index data for this table should reside in
fulltext_catalog_name. This action also designates the use of
unique_index_name as the full-text key column. This unique
index must already be present and must be defined on one
column of the table.

A full-text search cannot be performed against this table until


the full-text catalog is populated.
VALUE DESCRIPTION

Drop Drops the metadata on the full-text index for


qualified_table_name. If the full-text index is active, it is
automatically deactivated before being dropped. It is not
necessary to remove columns before dropping the full-text
index.

Activate Activates the ability for full-text index data to be gathered for
qualified_table_name, after it has been deactivated. There
must be at least one column participating in the full-text index
before it can be activated.

A full-text index is automatically made active (for population)


as soon as the first column is added for indexing. If the last
column is dropped from the index, the index becomes inactive.
If change tracking is on, activating an inactive index starts a
new population.

Note that this does not actually populate the full-text index,
but simply registers the table in the full-text catalog in the file
system so that rows from qualified_table_name can be
retrieved during the next full-text index population.

Deactivate Deactivates the full-text index for qualified_table_name so


that full-text index data can no longer be gathered for the
qualified_table_name. The full-text index metadata remains
and the table can be reactivated.

If change tracking is on, deactivating an active index freezes


the state of the index: any ongoing population is stopped, and
no more changes are propagated to the index.

start_change_tracking Start an incremental population of the full-text index. If the


table does not have a timestamp, start a full population of the
full-text index. Start tracking changes to the table.

Full-text change tracking does not track any WRITETEXT or


UPDATETEXT operations performed on full-text indexed
columns that are of type image, text, or ntext.

stop_change_tracking Stop tracking changes to the table.

update_index Propagate the current set of tracked changes to the full-text


index.

start_background_updateindex Start propagating tracked changes to the full-text index as


they occur.

stop_background_updateindex Stop propagating tracked changes to the full-text index as


they occur.

start_full Start a full population of the full-text index for the table.

start_incremental Start an incremental population of the full-text index for the


table.

Stop Stop a full or incremental population.


[ @ftcat=] 'fulltext_catalog_name'
Is a valid, existing full-text catalog name for a create action. For all other actions, this parameter must be NULL.
fulltext_catalog_name is sysname, with a default of NULL.
[ @keyname=] 'unique_index_name'
Is a valid single-key-column, unique nonnullable index on qualified_table_name for a create action. For all other
actions, this parameter must be NULL. unique_index_name is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
After a full-text index is deactivated for a particular table, the existing full-text index remains in place until the next
full population; however, this index is not used because Microsoft SQL Server blocks queries on deactivated tables.
If the table is reactivated and the index is not repopulated, the old index is still available for queries against any
remaining, but not new, full-text enabled columns. Data from deleted columns are matched in queries that specify
an all-full-text column search.
After a table has been defined for full-text indexing, switching the full-text unique key column from one data type
to another, either by changing the data type of that column or changing the full-text unique key from one column
to another, without a full repopulation may cause a failure to occur during a subsequent query and returning the
error message: "Conversion to type data_type failed for full-text search key value key_value." To prevent this, drop
the full-text definition for this table using the drop action of sp_fulltext_table and redefine it using
sp_fulltext_table and sp_fulltext_column.
The full-text key column must be defined to be 900 bytes or less. It is recommended that the size of the key column
be as small as possible for performance reasons.

Permissions
Only members of the sysadmin fixed server role, db_owner and db_ddladmin fixed database roles, or a user
with reference permissions on the full-text catalog can execute sp_fulltext_table.

Examples
A. Enabling a table for full-text indexing
The following example creates full-text index metadata for the Document table of the AdventureWorks database.
Cat_Desc is a full-text catalog. PK_Document_DocumentID is a unique, single-column index on Document .

USE AdventureWorks2012;
GO
EXEC sp_fulltext_table 'Production.Document', 'create', 'Cat_Desc', 'PK_Document_DocumentID';
--Add some columns
EXEC sp_fulltext_column 'Production.Document','DocumentSummary','add';
-- Activate the full-text index
EXEC sp_fulltext_table 'Production.Document','activate';
GO

B. Activating and propagating track changes


The following example activates and starts propagating tracked changes to the full-text index as they occur.

USE AdventureWorks2012;
GO
EXEC sp_fulltext_table 'Production.Document', 'Start_change_tracking';
EXEC sp_fulltext_table 'Production.Document', 'Start_background_updateindex';
GO

C. Removing a full-text index


This example removes the full-text index metadata for the Document table of the AdventureWorks database.

USE AdventureWorks2012;
GO
EXEC sp_fulltext_table 'Production.Document', 'drop';
GO

See Also
INDEXPROPERTY (Transact-SQL)
OBJECTPROPERTY (Transact-SQL)
sp_help_fulltext_tables (Transact-SQL)
sp_help_fulltext_tables_cursor (Transact-SQL)
sp_helpindex (Transact-SQL)
System Stored Procedures (Transact-SQL)
Full-Text Search and Semantic Search Stored Procedures (Transact-SQL)
sp_help_fulltext_catalogs (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the ID, name, root directory, status, and number of full-text indexed tables for the specified full-text
catalog.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use the sys.fulltext_catalogs catalog view instead.

Transact-SQL Syntax Conventions

Syntax
sp_help_fulltext_catalogs [ @fulltext_catalog_name = ] 'fulltext_catalog_name'

Arguments
[ @fulltext_catalog_name=] 'fulltext_catalog_name'
Is the name of the full-text catalog. fulltext_catalog_name is sysname. If this parameter is omitted or has the value
NULL, information about all full-text catalogs associated with the current database is returned.

Return Code Values


0 (success) or (1) failure

Result Sets
This table shows the result set, which is ordered by ftcatid.

COLUMN NAME DATA TYPE DESCRIPTION

fulltext_catalog_id smallint Full-text catalog identifier.

NAME sysname Name of the full-text catalog.

PATH nvarchar(260) Beginning with SQL Server 2008, this


clause has no effect.
COLUMN NAME DATA TYPE DESCRIPTION

STATUS int Full-text index population status of the


catalog:

0 = Idle

1 = Full population in progress

2 = Paused

3 = Throttled

4 = Recovering

5 = Shutdown

6 = Incremental population in progress

7 = Building index

8 = Disk is full. Paused

9 = Change tracking

NULL = User does not have VIEW


permission on the full-text catalog, or
database is not full-text enabled, or full-
text component not installed.

NUMBER_FULLTEXT_TABLES int Number of full-text indexed tables


associated with the catalog.

Permissions
Execute permissions default to members of the public role.

Examples
The following example returns information about the Cat_Desc full-text catalog.

USE AdventureWorks2012;
GO
EXEC sp_help_fulltext_catalogs 'Cat_Desc' ;
GO

See Also
FULLTEXTCATALOGPROPERTY (Transact-SQL)
sp_fulltext_catalog (Transact-SQL)
sp_help_fulltext_catalogs_cursor (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_fulltext_catalog_components (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a list of all components (filters, word-breakers, and protocol handlers), used for all full-text catalogs in the
current database.

NOTE
This feature will be removed in a future version of Microsoft SQL Server. Do not use this feature in new development work,
and modify applications that currently use this feature as soon as possible.

Transact-SQL Syntax Conventions

Syntax
sp_help_fulltext_catalog_components

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

full-text catalog name int Name of the full-text catalog.

full-text catalog id sysname ID of the full-text catalog.

componenttype sysname Type of component. One of the


following:

Filter

Protocol handler

Wordbreaker

componentname sysname Name of the component.

clsid uniqueidentifier Class identifier of the component.

fullpath nvarchar(256) Path to the location of the component.

NULL = Caller not a member of


serveradmin fixed server role.

version nvarchar(30) Version of the component.


COLUMN NAME DATA TYPE DESCRIPTION

manufacturer sysname Name of the manufacturer of the


component.

Permissions
Requires membership in the public role.

See Also
Full-Text Search and Semantic Search Stored Procedures (Transact-SQL)
sys.fulltext_catalogs (Transact-SQL)
sp_help_fulltext_system_components (Transact-SQL)
Full-Text Search
sp_help_fulltext_catalogs_cursor (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Uses a cursor to return the ID, name, root directory, status, and number of full-text indexed tables for the specified
full-text catalog.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use the sys.fulltext_catalogs catalog view instead.

Transact-SQL Syntax Conventions

Syntax
sp_help_fulltext_catalogs_cursor [ @cursor_return= ] @cursor_variable OUTPUT ,
[ @fulltext_catalog_name = ] 'fulltext_catalog_name'

Arguments
[ @cursor_return=] @cursor_variable OUTPUT
Is the output variable of type cursor. The cursor is a read-only, scrollable, dynamic cursor.
[ @fulltext_catalog_name=] 'fulltext_catalog_name'
Is the name of the full-text catalog. fulltext_catalog_name is sysname. If this parameter is omitted or is NULL,
information about all full-text catalogs associated with the current database is returned.

Return Code Values


0 (success) or (1) failure

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

fulltext_catalog_id smallint Full-text catalog identifier.

NAME sysname Name of the full-text catalog.

PATH nvarchar(260) Beginning with SQL Server 2008, this


clause has no effect.
COLUMN NAME DATA TYPE DESCRIPTION

STATUS int Full-text index population status of the


catalog:

0 = Idle

1 = Full population in progress

2 = Paused

3 = Throttled

4 = Recovering

5 = Shutdown

6 = Incremental population in progress

7 = Building index

8 = Disk is full. Paused

9 = Change tracking

NUMBER_FULLTEXT_TABLES int Number of full-text indexed tables


associated with the catalog.

Permissions
Execute permissions default to the public role.

Examples
The following example returns information about the Cat_Desc full-text catalog.

USE AdventureWorks2012;
GO
DECLARE @mycursor CURSOR;
EXEC sp_help_fulltext_catalogs_cursor @mycursor OUTPUT, 'Cat_Desc';
FETCH NEXT FROM @mycursor;
WHILE (@@FETCH_STATUS <> -1)
BEGIN
FETCH NEXT FROM @mycursor;
END
CLOSE @mycursor;
DEALLOCATE @mycursor;
GO

See Also
FULLTEXTCATALOGPROPERTY (Transact-SQL)
sp_fulltext_catalog (Transact-SQL)
sp_help_fulltext_catalogs (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_fulltext_columns (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the columns designated for full-text indexing.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use the sys.fulltext_index_columns catalog view instead.

Transact-SQL Syntax Conventions

Syntax
sp_help_fulltext_columns [ [ @table_name = ] 'table_name' ] ]
[ , [ @column_name = ] 'column_name' ]

Arguments
[ @table_name=] 'table_name'
Is the one- or two-part table name for which full-text index information is requested. table_name is
nvarchar(517), with a default value of NULL. If table_name is omitted, full-text index column information is
retrieved for every full-text indexed table.
[ @column_name=] 'column_name'
Is the name of the column for which full-text index metadata is requested. column_name is sysname, with a
default value of NULL. If column_name is omitted or is NULL, full-text column information is returned for every
full-text indexed column for table_name. If table_name is also omitted or is NULL, full-text index column
information is returned for every full-text indexed column for all tables in the database.

Return Code Values


0 (success) or (1) failure

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_OWNER sysname Table owner. This is the name of the


database user that created the table.

TABLE_ID int ID of the table.

TABLE_NAME sysname Name of the table.


COLUMN NAME DATA TYPE DESCRIPTION

FULLTEXT_COLUMN_NAME sysname Column in a full-text indexed table that


is designated for indexing.

FULLTEXT_COLID int Column ID of the full-text indexed


column.

FULLTEXT_BLOBTP_COLNAME sysname Column in a full-text indexed table that


specifies the document type of the full-
text indexed column. This value is only
applicable when the full-text indexed
column is a varbinary(max) or image
column.

FULLTEXT_BLOBTP_COLID int Column ID of the document type


column. This value is only applicable
when the full-text indexed column is a
varbinary(max) or image column.

FULLTEXT_LANGUAGE sysname Language used for the full-text search


of the column.

Permissions
Execute permissions default to members of the public role.

Examples
The following example returns information about the columns that have been designated for full-text indexing in
the Document table.

USE AdventureWorks2012;
GO
EXEC sp_help_fulltext_columns 'Production.Document';
GO

See Also
COLUMNPROPERTY (Transact-SQL)
sp_fulltext_column (Transact-SQL)
sp_help_fulltext_columns_cursor (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_fulltext_columns_cursor (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Uses a cursor to return the columns designated for full-text indexing.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use the sys.fulltext_index_columns catalog view instead.

Transact-SQL Syntax Conventions

Syntax
sp_help_fulltext_columns_cursor [ @cursor_return = ] @cursor_variable OUTPUT
[ , [ @table_name = ] 'table_name' ]
[ , [ @column_name = ] 'column_name' ]

Arguments
[ @cursor_return =] @cursor_variable OUTPUT
Is the output variable of type cursor. The resulting cursor is a read-only, scrollable, dynamic cursor.
[ @table_name =] 'table_name'
Is the one- or two-part table name for which full-text index information is requested. table_name is
nvarchar(517), with a default value of NULL. If table_name is omitted, full-text index column information is
retrieved for every full-text indexed table.
[ @column_name =] 'column_name'
Is the name of the column for which full-text index metadata is desired. column_name is sysname with a default
value of NULL. If column_name is omitted or is NULL, full-text column information is returned for every full-text
indexed column for table_name. If table_name is also omitted or is NULL, full-text index column information is
returned for every full-text indexed column for all tables in the database.

Return Code Values


0 (success) or (1) failure

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_OWNER sysname Table owner. This is the name of the


database user that created the table.

TABLE_ID int ID of the table.


COLUMN NAME DATA TYPE DESCRIPTION

TABLE_NAME sysname Table name.

FULLTEXT_COLUMN_NAME sysname Column in a full-text indexed table that


is designated for indexing.

FULLTEXT_COLID int Column ID of the full-text indexed


column.

FULLTEXT_BLOBTP_COLNAME sysname Column in a full-text indexed table that


specifies the document type of the full-
text indexed column. This value is only
applicable when the full-text indexed
column is a varbinary(max) or image
column.

FULLTEXT_BLOBTP_COLID int Column ID of the document type


column. This value is only applicable
when the full-text indexed column is a
varbinary(max) or image column.

FULLTEXT_LANGUAGE sysname Language used for the full-text search


of the column.

Permissions
Execute permissions default to members of the public role.

Examples
The following example returns information about the columns that have been designated for full-text indexing in
all of the tables in the database.

USE AdventureWorks2012;
GO
DECLARE @mycursor CURSOR;
EXEC sp_help_fulltext_columns_cursor @mycursor OUTPUT
FETCH NEXT FROM @mycursor;
WHILE (@@FETCH_STATUS <> -1)
BEGIN
FETCH NEXT FROM @mycursor;
END;
CLOSE @mycursor;
DEALLOCATE @mycursor;
GO

See Also
COLUMNPROPERTY (Transact-SQL)
sp_fulltext_column (Transact-SQL)
sp_help_fulltext_columns (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_fulltext_system_components (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information for the registered word-breakers, filter, and protocol handlers.
sp_help_fulltext_system_components also returns a list of identifiers of databases and full-text catalogs that
have used the specified component.
Transact-SQL Syntax Conventions

Syntax
sp_help_fulltext_system_components
{ 'all'| [ @component_type = ] 'component_type' }
, [ @param = ] 'param'

Arguments
'all'
Returns information for all full-text components.
[ @component_type= ] component_type
Specifies the type of component. component_type can be one of the following:
wordbreaker
filter
protocol handler
fullpath
If a full path is specified, param must also be specified with the full path to the component DLL, or an error
message is returned.
[ @param= ] param
Depending on component type, this is one of the following: a locale identifier (LCID), the file extension with
"." prefix, the full component name of the protocol handler, or the full path to the component DLL.

Return Code Values


0 (success) or (1) failure

Result Sets
The following result set is returned for the system components.

COLUMN NAME DATA TYPE DESCRIPTION


COLUMN NAME DATA TYPE DESCRIPTION

componenttype sysname Type of component. One of the


following:

filter

protocol handler

wordbreaker

componentname sysname Name of the component.

clsid uniqueidentifier Class identifier of the component.

fullpath nvarchar(256) Path to the location of the component.

NULL = Caller not a member of


serveradmin fixed server role.

version nvarchar(30) Version of the component.

manufacturer sysname Name of the manufacturer of the


component.

The following result set is returned only if one or more than one full-text catalog exists that uses component_type.

COLUMN NAME DATA TYPE DESCRIPTION

dbid int ID of the database.

ftcatid int ID of the full-text catalog.

Permissions
Requires membership in the public role; however, users can only see information about the full-text catalogs for
which they have VIEW DEFINITION permission. Only members of the serveradmin fixed server role can see values
in the fullpath column.

Remarks
This method is of particular importance when preparing for an upgrade. Execute the stored procedure within a
particular database, and use the output to determine whether a particular catalog will be impacted by the upgrade.

Examples
A. Listing all full-text system components
The following example lists all of the full-text system components that have been registered on the server instance.

EXEC sp_help_fulltext_system_components 'all';


GO

B. Listing word breakers


The following example lists all the word breakers registered on the service instance.
EXEC sp_help_fulltext_system_components 'wordbreaker';
GO

C. Determining whether a specific word breaker is registered


The following example will list the word breaker for the Turkish language (LCID = 1055) if it has been installed on
the system and registered on the service instance. This example specifies the parameter names,
@component_type and @param.

EXEC sp_help_fulltext_system_components @component_type = 'wordbreaker', @param = 1055;


GO

By default, this word breaker is not installed, so the result set is empty.
D. Determining whether a specific filter has been registered
The following example lists the filter for the .xdoc component if it has been manually installed on the system and
registered on the server instance.

EXEC sp_help_fulltext_system_components 'filter', '.xdoc';


GO

By default, this filter is not installed, so the result set is empty.


E. Listing a specific .dll file
The following example lists a specific .ddl file, nlhtml.dll , which is installed by default.

EXEC sp_help_fulltext_system_components 'fullpath',


'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Binn\nlhtml.dll';
GO

See Also
View or Change Registered Filters and Word Breakers
Configure and Manage Word Breakers and Stemmers for Search
Configure and Manage Filters for Search
Full-Text Search and Semantic Search Stored Procedures (Transact-SQL)
sp_help_fulltext_tables (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns a list of tables that are registered for full-text indexing.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use sys.fulltext_indexes catalog view instead. For more
information, see sys.fulltext_indexes (Transact-SQL).

Transact-SQL Syntax Conventions

Syntax
sp_help_fulltext_tables [ [ @fulltext_catalog_name = ] 'fulltext_catalog_name' ]
[ , [ @table_name = ] 'table_name' ]

Arguments
[ @fulltext_catalog_name=] 'fulltext_catalog_name'
Is the name of the full-text catalog. fulltext_catalog_name is sysname, with a default of NULL. If
fulltext_catalog_name is omitted or is NULL, all full-text indexed tables associated with the database are returned.
If fulltext_catalog_name is specified, but table_name is omitted or is NULL, the full-text index information is
retrieved for every full-text indexed table associated with this catalog. If both fulltext_catalog_name and
table_name are specified, a row is returned if table_name is associated with fulltext_catalog_name; otherwise, an
error is raised.
[ @table_name=] 'table_name'
Is the one- or two-part table name for which the full-text metadata is requested. table_name is nvarchar(517),
with a default value of NULL. If only table_name is specified, only the row relevant to table_name is returned.

Return Code Values


0 (success) or (1) failure

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_OWNER sysname Table owner. This is the name of the


database user that created the table.

TABLE_NAME sysname Table name.


COLUMN NAME DATA TYPE DESCRIPTION

FULLTEXT_KEY_INDEX_NAME sysname Index imposing the UNIQUE constraint


on the column designated as the
unique key column.

FULLTEXT_KEY_COLID int Column ID of the unique index


identified by FULLTEXT_KEY_NAME.

FULLTEXT_INDEX_ACTIVE int Specifies whether columns marked for


full-text indexing in this table are
eligible for queries:

0 = Inactive

1 = Active

FULLTEXT_CATALOG_NAME sysname Full-text catalog in which the full-text


index data resides.

Permissions
Execute permissions default to members of the public role.

Examples
The following example returns the names of the full-text indexed tables associated with the Cat_Desc full-text
catalog.

USE AdventureWorks2012;
GO
EXEC sp_help_fulltext_tables 'Cat_Desc';
GO

See Also
INDEXPROPERTY (Transact-SQL)
OBJECTPROPERTY (Transact-SQL)
sp_fulltext_table (Transact-SQL)
sp_help_fulltext_tables_cursor (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_fulltext_tables_cursor (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Uses a cursor to return a list of tables that are registered for full-text indexing.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use the new sys.fulltext_indexes catalog view instead. For
more information, see sys.fulltext_indexes (Transact-SQL).

Transact-SQL Syntax Conventions

Syntax
sp_help_fulltext_tables_cursor [ @cursor_return = ] @cursor_variable OUTPUT
[ , [ @fulltext_catalog_name = ] 'fulltext_catalog_name' ]
[ , [ @table_name = ] 'table_name' ]

Arguments
[ @cursor_return= ] @cursor_variable OUTPUT
Is the output variable of type cursor. The cursor is a read-only, scrollable, dynamic cursor.
[ @fulltext_catalog_name= ] 'fulltext_catalog_name'
Is the name of the full-text catalog. fulltext_catalog_name is sysname, with a default of NULL. If
fulltext_catalog_name is omitted or is NULL, all full-text indexed tables associated with the database are returned.
If fulltext_catalog_name is specified, but table_name is omitted or is NULL, the full-text index information is
retrieved for every full-text indexed table associated with this catalog. If both fulltext_catalog_name and
table_name are specified, a row is returned if table_name is associated with fulltext_catalog_name; otherwise, an
error is raised.
[ @table_name=] 'table_name'
Is the one- or two-part table name for which the full-text metadata is requested. table_name is nvarchar(517),
with a default value of NULL. If only table_name is specified, only the row relevant to table_name is returned.

Return Code Values


0 (success) or (1) failure

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_OWNER sysname Table owner. This is the name of the


database user that created the table.
COLUMN NAME DATA TYPE DESCRIPTION

TABLE_NAME sysname Table name.

FULLTEXT_KEY_INDEX_NAME sysname Index imposing the UNIQUE constraint


on the column designated as the
unique key column.

FULLTEXT_KEY_COLID int Column ID of the unique index


identified by FULLTEXT_KEY_NAME.

FULLTEXT_INDEX_ACTIVE int Specifies whether columns marked for


full-text indexing in this table are
eligible for queries:

0 = Inactive

1 = Active

FULLTEXT_CATALOG_NAME sysname Full-text catalog in which the full-text


index data resides.

Permissions
Execute permissions default to members of the public role.

Examples
The following example returns the names of the full-text indexed tables associated with the Cat_Desc full-text
catalog.

USE AdventureWorks2012;
GO
DECLARE @mycursor CURSOR;
EXEC sp_help_fulltext_tables_cursor @mycursor OUTPUT, 'Cat_Desc';
FETCH NEXT FROM @mycursor;
WHILE (@@FETCH_STATUS <> -1)
BEGIN
FETCH NEXT FROM @mycursor;
END;
CLOSE @mycursor;
DEALLOCATE @mycursor;
GO

See Also
INDEXPROPERTY (Transact-SQL)
OBJECTPROPERTY (Transact-SQL)
sp_fulltext_table (Transact-SQL)
sp_help_fulltext_tables (Transact-SQL)
System Stored Procedures (Transact-SQL)
General Extended Stored Procedures (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
SQL Server supports the following system stored procedures that provide an interface from an instance of SQL
Server to external programs for various maintenance activities.

xp_cmdshell xp_logininfo

xp_enumgroups xp_msver

xp_grantlogin xp_revokelogin

xp_logevent xp_sprintf

xp_loginconfig xp_sqlmaint

xp_sscanf

See Also
System Stored Procedures (Transact-SQL)
xp_cmdshell (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Spawns a Windows command shell and passes in a string for execution. Any output is returned as rows of text.
Transact-SQL Syntax Conventions

Syntax
xp_cmdshell { 'command_string' } [ , no_output ]

Arguments
' command_string '
Is the string that contains a command to be passed to the operating system. command_string is varchar(8000) or
nvarchar(4000), with no default. command_string cannot contain more than one set of double quotation marks. A
single pair of quotation marks is required if any spaces are present in the file paths or program names referenced
in command_string. If you have trouble with embedded spaces, consider using FAT 8.3 file names as a
workaround.
no_output
Is an optional parameter, specifying that no output should be returned to the client.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Executing the following xp_cmdshell statement returns a directory listing of the current directory.

EXEC xp_cmdshell 'dir *.exe';


GO

The rows are returned in an nvarchar(255) column. If the no_output option is used, only the following will be
returned:

The command(s) completed successfully.

Remarks
The Windows process spawned by xp_cmdshell has the same security rights as the SQL Server service account.
xp_cmdshell operates synchronously. Control is not returned to the caller until the command-shell command is
completed.
xp_cmdshell can be enabled and disabled by using the Policy-Based Management or by executing sp_configure.
For more information, see Surface Area Configuration and xp_cmdshell Server Configuration Option.

IMPORTANT
If xp_cmdshell is executed within a batch and returns an error, the batch will fail. This is a change of behavior. In earlier
versions of Microsoft SQL Server the batch would continue to execute.

xp_cmdshell Proxy Account


When it is called by a user that is not a member of the sysadmin fixed server role, xp_cmdshell connects to
Windows by using the account name and password stored in the credential named
##xp_cmdshell_proxy_account##. If this proxy credential does not exist, xp_cmdshell will fail.
The proxy account credential can be created by executing sp_xp_cmdshell_proxy_account. As arguments, this
stored procedure takes a Windows user name and password. For example, the following command creates a proxy
credential for Windows domain user SHIPPING\KobeR that has the Windows password sdfh%dkc93vcMt0 .

EXEC sp_xp_cmdshell_proxy_account 'SHIPPING\KobeR','sdfh%dkc93vcMt0';

For more information, see sp_xp_cmdshell_proxy_account (Transact-SQL).

Permissions
Because malicious users sometimes attempt to elevate their privileges by using xp_cmdshell, xp_cmdshell is
disabled by default. Use sp_configure or Policy Based Management to enable it. For more information, see
xp_cmdshell Server Configuration Option.
When first enabled, xp_cmdshell requires CONTROL SERVER permission to execute and the Windows process
created by xp_cmdshell has the same security context as the SQL Server service account. The SQL Server service
account often has more permissions than are necessary for the work performed by the process created by
xp_cmdshell. To enhance security, access to xp_cmdshell should be restricted to highly privileged users.
To allow non-administrators to use xp_cmdshell, and allow SQL Server to create child processes with the security
token of a less-privileged account, follow these steps:
1. Create and customize a Windows local user account or a domain account with the least privileges that your
processes require.
2. Use the sp_xp_cmdshell_proxy_account system procedure to configure xp_cmdshell to use that least-
privileged account.

NOTE
You can also configure this proxy account using SQL Server Management Studio by right-clicking Properties on
your server name in Object Explorer, and looking on the Security tab for the Server proxy account section.

3. In Management Studio, using the master database, execute the GRANT exec ON xp_cmdshell TO '<somelogin>'
statement to give specific non-sysadmin users the ability to execute xp_cmdshell. The specified login must
be mapped to a user in the master database.
Now non-administrators can launch operating system processes with xp_cmdshell and those processes
run with the permissions of the proxy account that you have configured. Users with CONTROL SERVER
permission (members of the sysadmin fixed server role) will continue to receive the permissions of the SQL
Server service account for child processes that are launched by xp_cmdshell.
To determine the Windows account being used by xp_cmdshell when launching operating system
processes, execute the following statement:

xp_cmdshell 'whoami.exe'

To determine the security context for another login, execute the following:

EXECUTE AS LOGIN = '<other_login>' ;


GO
xp_cmdshell 'whoami.exe' ;
REVERT ;

Examples
A. Returning a list of executable files
The following example shows the xp_cmdshell extended stored procedure executing a directory command.

EXEC master..xp_cmdshell 'dir *.exe''

B. Returning no output
The following example uses xp_cmdshell to execute a command string without returning the output to the client.

USE master;

EXEC xp_cmdshell 'copy c:\SQLbcks\AdvWorks.bck


\\server2\backups\SQLbcks, NO_OUTPUT';
GO

C. Using return status


In the following example, the xp_cmdshell extended stored procedure also suggests return status. The return code
value is stored in the variable @result .

DECLARE @result int;


EXEC @result = xp_cmdshell 'dir *.exe';
IF (@result = 0)
PRINT 'Success'
ELSE
PRINT 'Failure';

D. Writing variable contents to a file


The following example writes the contents of the @var variable to a file named var_out.txt in the current server
directory.

DECLARE @cmd sysname, @var sysname;


SET @var = 'Hello world';
SET @cmd = 'echo ' + @var + ' > var_out.txt';
EXEC master..xp_cmdshell @cmd;

E. Capturing the result of a command to a file


The following example writes the contents of the current directory to a file named dir_out.txt in the current
server directory.

DECLARE @cmd sysname, @var sysname;


SET @var = 'dir/p';
SET @cmd = @var + ' > dir_out.txt';
EXEC master..xp_cmdshell @cmd;

See Also
General Extended Stored Procedures (Transact-SQL)
xp_cmdshell Server Configuration Option
Surface Area Configuration
sp_xp_cmdshell_proxy_account (Transact-SQL)
xp_enumgroups (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Provides a list of local Microsoft Windows groups or a list of global groups that are defined in a specified Windows
domain.
Transact-SQL Syntax Conventions

Syntax
xp_enumgroups [ 'domain_name' ]

Arguments
' domain_name '
Is the name of the Windows domain for which to enumerate a list of global groups. domain_name is sysname,
with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

group sysname Name of the Windows group

comment sysname Description of the Windows group


provided by Windows

Remarks
If domain_name is the name of the Windows-based computer that an instance of SQL Server is running on, or no
domain name is specified, xp_enumgroups enumerates the local groups from the computer that is running SQL
Server.
xp_enumgroups cannot be used when an instance of SQL Server is running on Windows 98.

Permissions
Requires membership in the db_owner fixed database role in the master database, or membership in the
sysadmin fixed server role.

Examples
The following example lists the groups in the sales domain.

EXEC xp_enumgroups 'sales';

See Also
sp_grantlogin (Transact-SQL)
sp_revokelogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
General Extended Stored Procedures (Transact-SQL)
xp_loginconfig (Transact-SQL)
xp_logininfo (Transact-SQL)
xp_grantlogin (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Grants a Windows group or user access to SQL Server.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use CREATE LOGIN instead.

Transact-SQL Syntax Conventions

Syntax
xp_grantlogin {[@loginame = ] 'login'} [,[@logintype = ] 'logintype']

Arguments
[ @loginame = ] 'login'
Is the name of the Windows user or group to be added. The Windows user or group must be qualified with a
Windows domain name in the form Domain\User. login is sysname, with no default.
[ @logintype = ] 'logintype'
Is the security level of the login being granted access. logintype is varchar(5), with a default of NULL. Only admin
can be specified. If admin is specified, login is granted access to SQL Server, and added as a member of the
sysadmin fixed server role.

Return Code Values


0 (success) or 1 (failure)

Remarks
xp_grantlogin is now a system stored procedure instead of an extended stored procedure. xp_grantlogin calls
sp_grantlogin and sp_addsrvrolemember.

Permissions
Requires membership in the securityadmin fixed server role. When changing the logintype, requires membership
in the sysadmin fixed server role.

See Also
sp_denylogin (Transact-SQL)
sp_grantlogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
General Extended Stored Procedures (Transact-SQL)
xp_enumgroups (Transact-SQL)
xp_loginconfig (Transact-SQL)
xp_logininfo (Transact-SQL)
sp_revokelogin (Transact-SQL)
xp_logevent (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Logs a user-defined message in the SQL Server log file and in the Windows Event Viewer. xp_logevent can be used
to send an alert without sending a message to the client.
Transact-SQL Syntax Conventions

Syntax
xp_logevent { error_number , 'message' } [ , 'severity' ]

Arguments
error_number
Is a user-defined error number larger than 50,000. The maximum value is 2147483647 (2^31 - 1).
' message '
Is a character string with a maximum of 2048 characters.
' severity '
Is one of three character strings: INFORMATIONAL, WARNING, or ERROR. severity is optional, with a default of
INFORMATIONAL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
xp_logevent returns the following error message for the included code example:
The command(s) completed successfully.

Remarks
When you send messages from Transact-SQL procedures, triggers, batches, and so on, use the RAISERROR
statement instead of xp_logevent. xp_logevent does not call a message handler of a client or set @@ERROR. To
write messages to the Windows Event Viewer and to the SQL Server error log file within an instance of SQL Server,
execute the RAISERROR statement.

Permissions
Requires membership in the db_owner fixed database role in the master database, or membership in the sysadmin
fixed server role.

Examples
The following example logs the message, with variables passed to the message in the Windows Event Viewer.

DECLARE @@TABNAME varchar(30, @@USERNAME varchar(30),DECLARE @@MESSAGE varchar(255);


SET @@TABNAME = 'customers';
SET @@USERNAME = USER_NAME();
SELECT @@MESSAGE = 'The table ' + @@TABNAME + ' is not owned by the user
' + @@USERNAME + '.';

USE master;
EXEC xp_logevent 60000, @@MESSAGE, informational;

See Also
PRINT (Transact-SQL)
RAISERROR (Transact-SQL)
System Stored Procedures (Transact-SQL)
General Extended Stored Procedures (Transact-SQL)
xp_loginconfig (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports the login security configuration of an instance of SQL Server.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature.

Transact-SQL Syntax Conventions

Syntax
xp_loginconfig ['config_name']

Arguments
' config_name '
Is the configuration value to be displayed. If config_name is not specified, all configuration values are reported.
config_name is sysname, with a default of NULL, and can be one of these values.

VALUE DESCRIPTION

login mode Login security mode. Possible values are Mixed and
Windows Authentication.

Replaced by:

SELECT SERVERPROPERTY('IsIntegratedSecurityOnly');
GO

default login Name of the default SQL Server login ID for authorized users
of trusted connections (for users without matching login
name). The default login is guest. This value is provided for
backward compatibility.

Default domain Name of the default Windows domain for network users of
trusted connections. The default domain is the domain of the
computer running Windows and SQL Server. This value is
provided for backward compatibility.

audit level Audit level. Possible values are none, success, failure, and all.
Audits are written to the error log and to the Windows Event
Viewer.
VALUE DESCRIPTION

set hostname Indicates whether the host name from the client login record
is replaced with the Windows network user name. Possible
values are true or false. If this is set, the network user name
appears in output from sp_who.

map _ Reports what special Windows characters are mapped to the


valid SQL Server underscore character (_). Possible values are
domain separator (default), space, null, or any single
character. This value is provided for backward compatibility.

map $ Reports what special Windows characters are mapped to the


valid SQL Server dollar sign character ($). Possible values are
domain separator, space, null, or any single character. The
default is space. This value is provided for backward
compatibility.

map # Reports what special Windows characters are mapped to the


valid SQL Server number sign character (#). Possible values
are domain separator, space, null, or any single character.
Default is the hyphen. This value is provided for backward
compatibility.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

name sysname Configuration value

config value sysname Configuration value setting

Remarks
xp_loginconfig cannot be used to set configuration values.
To set the login mode and audit level, use SQL Server Management Studio.

Permissions
Requires CONTROL permission on the master database.

Examples
A. How to report all configuration values
The following example shows all the currently configured settings.

EXEC xp_loginconfig;
GO
B. How to report a specific configuration value
The following example shows the setting for only the login mode.

EXEC xp_loginconfig 'login mode';


GO

See Also
sp_denylogin (Transact-SQL)
sp_grantlogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_revokelogin (Transact-SQL)
xp_logininfo (Transact-SQL)
xp_logininfo (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about Windows users and Windows groups.
Transact-SQL Syntax Conventions

Syntax
xp_logininfo [ [ @acctname = ] 'account_name' ]
[ , [ @option = ] 'all' | 'members' ]
[ , [ @privilege = ] variable_name OUTPUT]

Arguments
[ @acctname = ] 'account_name'
Is the name of a Windows user or group granted access to SQL Server. account_name is sysname, with a default
of NULL. If account_name is not specified, all Windows groups and Windows users that have been explicitly
granted login permission are reported. account_name must be fully qualified. For example, 'ADVWKS4\macraes',
or 'BUILTIN\Administrators'.
'all' | 'members'
Specifies whether to report information about all permission paths for the account, or to report information about
the members of the Windows group. @option is varchar(10), with a default of NULL. Unless all is specified, only
the first permission path is displayed.
[ @privilege = ] variable_name
Is an output parameter that returns the privilege level of the specified Windows account. variable_name is
varchar(10), with a default of 'Not wanted'. The privilege level returned is user, admin, or null.
OUTPUT
When specified, puts variable_name in the output parameter.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

account name sysname Fully qualified Windows account name.

type char(8) Type of Windows account. Valid values


are user or group.
COLUMN NAME DATA TYPE DESCRIPTION

privilege char(9) Access privilege for SQL Server. Valid


values are admin, user, or null.

mapped login name sysname For user accounts that have user
privilege, mapped login name shows
the mapped login name that SQL
Server tries to use when logging in with
this account by using the mapped rules
with the domain name added before it.

permission path sysname Group membership that allowed the


account access.

Remarks
If account_name is specified, xp_logininfo reports the highest privilege level of the specified Windows user or
group. If a Windows user has access as both a system administrator and as a domain user, it will be reported as a
system administrator. If the user is a member of multiple Windows groups of equal privilege level, only the group
that was first granted access to SQL Server is reported.
If account_name is a valid Windows user or group that is not associated with a SQL Server login, an empty result
set is returned. If account_name cannot be identified as a valid Windows user or group, an error message is
returned.
If account_name and all are specified, all permission paths for the Windows user or group are returned. If
account_name is a member of multiple groups, all of which have been granted access to SQL Server, multiple
rows are returned. The admin privilege rows are returned before the user privilege rows, and within a privilege
level rows are returned in the order in which the corresponding SQL Server logins were created.
If account_name and members are specified, a list of the next-level members of the group is returned. If
account_name is a local group, the listing can include local users, domain users, and groups. If account_name is a
domain account, the list is made up of domain users. SQL Server must connect to the domain controller to
retrieve group membership information. If the server cannot contact the domain controller, no information will be
returned.
xp_logininfo only returns information from Active Director global groups, not universal groups.

Permissions
Requires membership in the sysadmin fixed server role or membership in the public fixed database role in the
master database with EXECUTE permission granted.

Examples
The following example displays information about the BUILTIN\Administrators Windows group.

EXEC xp_logininfo 'BUILTIN\Administrators';

See Also
sp_denylogin (Transact-SQL)
sp_grantlogin (Transact-SQL)
sp_revokelogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
General Extended Stored Procedures (Transact-SQL)
xp_msver (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns version information about Microsoft SQL Server. xp_msver also returns information about the actual
build number of the server and information about the server environment. The information that xp_msver returns
can be used within Transact-SQL statements, batches, stored procedures, and so on, to enhance logic for platform-
independent code.
Transact-SQL Syntax Conventions

Syntax
xp_msver [ optname ]

Arguments
optname
Is the name of an option, and can be one of the following values.

OPTION/COLUMN NAME DESCRIPTION

ProductName Product name; for example, Microsoft SQL Server.

ProductVersion Product version.

Language The language version of SQL Server.

Platform Operating-system name, manufacturer name, and chip family


name for the computer that is running SQL Server.

Comments Miscellaneous information about SQL Server.

CompanyName Company name that produces SQL Server; for example,


Microsoft Corporation.

FileDescription The operating system.

FileVersion Version of the SQL Server executable.

InternalName Microsoft internal name for SQL Server; for example,


SQLSERVR.

LegalCopyright Legal copyright information required for SQL Server; for


example, Copyright© Microsoft Corp. 1988-2005.
OPTION/COLUMN NAME DESCRIPTION

LegalTrademarks Legal trademark information required for SQL Server. For


example, Microsoft is a registered trademark of Microsoft
Corporation.

OriginalFilename File name executed at SQL Server startup; for example,


Sqlservr.exe.

PrivateBuild Identified for informational purposes only. Not supported.


Future compatibility is not guaranteed.

SpecialBuild Identified for informational purposes only. Not supported.


Future compatibility is not guaranteed.

WindowsVersion Version of Microsoft Windows that is installed on the


computer that is running SQL Server.

ProcessorCount The number of processors in the computer that is running


SQL Server.

ProcessorActiveMask Indicates the processors installed in the computer that is


running SQL Server that are started and usable by Microsoft
Windows.

ProcessorType Processor type. Similar to Platform.

PhysicalMemory Amount in megabytes (MB) of RAM installed on the computer


that is running SQL Server.

Product ID Product ID (PID) number. This is specified during installation.


This number is located on a sticker on the original SQL Server
CD case.

Return Code Values


1 (success)

Result Sets
xp_msver, without any parameters, returns a four-column result set that lists all the option values. xp_msver, for
any parameter, returns the four-column result set with values for that option.

Permissions
Requires membership in the public role.

See Also
System Functions (Transact-SQL)
System Stored Procedures (Transact-SQL)
General Extended Stored Procedures (Transact-SQL)
@@VERSION (Transact-SQL)
xp_revokelogin (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Revokes access from a Windows group or user to SQL Server.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use DROP LOGIN instead.

Transact-SQL Syntax Conventions

Syntax
xp_revokelogin {[@loginame=] 'login'}

Arguments
[ @loginame = ] 'login'
Is the name of the Windows user or group from which to revoke access. login must include the domain name, for
example [ADVWKS\sylvester1]. login is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
Use DROP LOGIN instead.

Permissions
Requires ALTER ANY LOGIN permission on the server.

See Also
sp_denylogin (Transact-SQL)
sp_grantlogin (Transact-SQL)
sp_revokelogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
General Extended Stored Procedures (Transact-SQL)
xp_loginconfig (Transact-SQL)
xp_logininfo (Transact-SQL)
xp_sprintf (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Formats and stores a series of characters and values in the string output parameter. Each format argument is
replaced with the corresponding argument.
Transact-SQL Syntax Conventions

Syntax
xp_sprintf { string OUTPUT , format }
[ , argument [ ,...n ] ]

Arguments
string
Is a varchar variable that receives the output.
OUTPUT
When specified, puts the value of the variable in the output parameter.
format
Is a format character string with placeholders for argument values, similar to that supported by the C-language
sprintf function. Currently, only the %s format argument is supported.
argument
Is a character string that represents the value of the corresponding format argument.
n
Is a placeholder that indicates that a maximum of 50 arguments can be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
xp_sprintf returns the following message:
The command(s) completed successfully.

Permissions
Requires membership in the public role.

See Also
System Stored Procedures (Transact-SQL)
General Extended Stored Procedures (Transact-SQL)
xp_sscanf (Transact-SQL)
xp_sqlmaint (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Calls the sqlmaint utility with a string that contains sqlmaintswitches. The sqlmaint utility performs a set of
maintenance operations on one or more databases.

NOTE
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature.

Transact-SQL Syntax Conventions

Syntax
xp_sqlmaint 'switch_string'

Arguments
' switch_string '
Is a string containing the sqlmaint utility switches. The switches and their values must be separated by a space.
The -? switch is not valid for xp_sqlmaint.

Return Code Values


None. Returns an error if the sqlmaint utility fails.

Remarks
If this procedure is called by a user logged on with SQL Server Authentication, the -U "login_id" and -P
"password" switches are prepended to switch_string before execution. If the user is logged on with Windows
Authentication, switch_string is passed without change to sqlmaint.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
In the following example, xp_sqlmaint calls sqlmaint to perform integrity checks, create a report file, and update
msdb.dbo.sysdbmaintplan_history .

EXEC xp_sqlmaint '-D AdventureWorks2012 -PlanID 02A52657-D546-11D1-9D8A-00A0C9054212


-Rpt "C:\Program Files\Microsoft SQL Server\MSSQL\LOG\DBMaintPlan2.txt" -WriteHistory -CkDB -CkAl';
Here is the result set.

The command(s) executed successfully.

See Also
sqlmaint Utility
System Stored Procedures (Transact-SQL)
xp_sscanf (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reads data from the string into the argument locations specified by each format argument.
Transact-SQL Syntax Conventions

Syntax
xp_sscanf { string OUTPUT , format } [ ,argument [ ,...n ] ]

Arguments
string
Is the character string to read the argument values from.
OUTPUT
When specified, puts the value of argument in the output parameter.
format
Is a formatted character string similar to what is supported by the C-language sscanf function. Currently, only the
%s format argument is supported.
argument
Is a varchar variable set to the value of the corresponding format argument.
n
Is a placeholder that indicates that a maximum of 50 arguments can be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
xp_sscanf returns the following message:
Command(s) completed successfully.

Permissions
Requires membership in the public role.

Examples
The following example uses xp_sscanf to extract two values from a source string based on their positions in the
format of the source string.
DECLARE @filename varchar (20), @message varchar (20);
EXEC xp_sscanf 'sync -b -fproducts10.tmp -rrandom', 'sync -b -f%s -r%s',
@filename OUTPUT, @message OUTPUT;
SELECT @filename, @message;

Here is the result set.

-------------------- --------------------
products10.tmp random

See Also
System Stored Procedures (Transact-SQL)
General Extended Stored Procedures (Transact-SQL)
xp_sprintf (Transact-SQL)
Log Shipping Stored Procedures (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Microsoft SQL Server and later versions support the following system stored procedures that are used to configure,
modify, and monitor log shipping configurations.

sp_add_log_shipping_alert_job sp_delete_log_shipping_secondary_database

sp_add_log_shipping_primary_database sp_delete_log_shipping_secondary_primary

sp_add_log_shipping_primary_secondary sp_help_log_shipping_alert_job

sp_add_log_shipping_secondary_database sp_help_log_shipping_monitor

sp_add_log_shipping_secondary_primary sp_help_log_shipping_monitor_primary

sp_change_log_shipping_primary_database sp_help_log_shipping_monitor_secondary

sp_change_log_shipping_secondary_database sp_help_log_shipping_primary_database

sp_change_log_shipping_secondary_primary sp_help_log_shipping_primary_secondary

sp_cleanup_log_shipping_history sp_help_log_shipping_secondary_database

sp_delete_log_shipping_alert_job sp_help_log_shipping_secondary_primary

sp_delete_log_shipping_primary_database sp_refresh_log_shipping_monitor

sp_delete_log_shipping_primary_secondary

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_add_log_shipping_primary_database (Transact-
SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sets up the primary database for a log shipping configuration, including the backup job, local monitor record, and
remote monitor record.
Transact-SQL Syntax Conventions

Syntax
sp_add_log_shipping_primary_database [ @database = ] 'database',
[ @backup_directory = ] 'backup_directory',
[ @backup_share = ] 'backup_share',
[ @backup_job_name = ] 'backup_job_name',
[, [ @backup_retention_period = ] backup_retention_period]
[, [ @monitor_server = ] 'monitor_server']
[, [ @monitor_server_security_mode = ] monitor_server_security_mode]
[, [ @monitor_server_login = ] 'monitor_server_login']
[, [ @monitor_server_password = ] 'monitor_server_password']
[, [ @backup_threshold = ] backup_threshold ]
[, [ @threshold_alert = ] threshold_alert ]
[, [ @threshold_alert_enabled = ] threshold_alert_enabled ]
[, [ @history_retention_period = ] history_retention_period ]
[, [ @backup_job_id = ] backup_job_id OUTPUT ]
[, [ @primary_id = ] primary_id OUTPUT]
[, [ @backup_compression = ] backup_compression_option ]

Arguments
[ @database= ] 'database'
Is the name of the log shipping primary database. database is sysname, with no default, and cannot be NULL.
[ @backup_directory= ] 'backup_directory'
Is the path to the backup folder on the primary server. backup_directory is nvarchar(500), with no default, and
cannot be NULL.
[ @backup_share= ] 'backup_share'
Is the network path to the backup directory on the primary server. backup_share is nvarchar(500), with no default,
and cannot be NULL.
[ @backup_job_name= ] 'backup_job_name'
Is the name of the SQL Server Agent job on the primary server that copies the backup into the backup folder.
backup_job_name is sysname and cannot be NULL.
[ @backup_retention_period= ] backup_retention_period
Is the length of time, in minutes, to retain the log backup file in the backup directory on the primary server.
backup_retention_period is int, with no default, and cannot be NULL.
[ @monitor_server= ] 'monitor_server'
Is the name of the monitor server. Monitor_server is sysname, with no default, and cannot be NULL.
[ @monitor_server_security_mode= ] monitor_server_security_mode
The security mode used to connect to the monitor server.
1 = Windows Authentication.
0 = SQL Server Authentication. monitor_server_security_mode is bit and cannot be NULL.
[ @monitor_server_login= ] 'monitor_server_login'
Is the username of the account used to access the monitor server.
[ @monitor_server_password= ] 'monitor_server_password'
Is the password of the account used to access the monitor server.
[ @backup_threshold= ] backup_threshold
Is the length of time, in minutes, after the last backup before a threshold_alert error is raised. backup_threshold is
int, with a default of 60 minutes.
[ @threshold_alert= ] threshold_alert
Is the alert to be raised when the backup threshold is exceeded. threshold_alert is int, with a default of 14,420.
[ @threshold_alert_enabled= ] threshold_alert_enabled
Specifies whether an alert will be raised when backup_threshold is exceeded. The value of zero (0), the default,
means that the alert is disabled and will not be raised. threshold_alert_enabled is bit.
[ @history_retention_period= ] history_retention_period
Is the length of time in minutes in which the history will be retained. history_retention_period is int, with a default
of NULL. A value of 14420 will be used if none is specified.
[ @backup_job_id= ] backup_job_id OUTPUT
The SQL Server Agent job ID associated with the backup job on the primary server. backup_job_id is
uniqueidentifier and cannot be NULL.
[ @primary_id= ] primary_id OUTPUT
The ID of the primary database for the log shipping configuration. primary_id is uniqueidentifier and cannot be
NULL.
[ @backup_compression= ] backup_compression_option
Specifies whether a log shipping configuration uses backup compression. This parameter is supported only in SQL
Server 2008 Enterprise (or a later version).
0 = Disabled. Never compress log backups.
1 = Enabled. Always compress log backups.
2 = Use the setting of the View or Configure the backup compression default Server Configuration Option. This is
the default value.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_add_log_shipping_primary_database must be run from the master database on the primary server. This
stored procedure performs the following functions:
1. Generates a primary ID and adds an entry for the primary database in the table
log_shipping_primary_databases using the supplied arguments.
2. Creates a backup job for the primary database that is disabled.
3. Sets the backup job ID in the log_shipping_primary_databases entry to the job ID of the backup job.
4. Adds a local monitor record in the table log_shipping_monitor_primary on the primary server using
supplied arguments.
5. If the monitor server is different from the primary server, adds a monitor record in
log_shipping_monitor_primary on the monitor server using supplied arguments.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

Examples
This example adds the database AdventureWorks2012 as the primary database in a log shipping configuration.

DECLARE @LS_BackupJobId AS uniqueidentifier ;


DECLARE @LS_PrimaryId AS uniqueidentifier ;

EXEC master.dbo.sp_add_log_shipping_primary_database
@database = N'AdventureWorks'
,@backup_directory = N'c:\lsbackup'
,@backup_share = N'\\tribeca\lsbackup'
,@backup_job_name = N'LSBackup_AdventureWorks'
,@backup_retention_period = 1440
,@monitor_server = N'rockaway'
,@monitor_server_security_mode = 1
,@backup_threshold = 60
,@threshold_alert = 0
,@threshold_alert_enabled = 0
,@history_retention_period = 1440
,@backup_job_id = @LS_BackupJobId OUTPUT
,@primary_id = @LS_PrimaryId OUTPUT
,@overwrite = 1
,@backup_compression = 0;
GO

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_add_log_shipping_primary_secondary (Transact-
SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This stored procedure adds an entry for a secondary database on the primary server.
Transact-SQL Syntax Conventions

Syntax
sp_add_log_shipping_primary_secondary
[ @primary_database = ] 'primary_database',
[ @secondary_server = ] 'secondary_server',
[ @secondary_database = ] 'secondary_database'

Arguments
[ @primary_database = ] 'primary_database'
Is the name of the database on the primary server. primary_database is sysname, with no default.
[ @secondary_server = ] 'secondary_server',
Is the name of the secondary server. secondary_server is sysname, with no default.
[ @secondary_database = ] 'secondary_database'
Is the name of the secondary database. secondary_database is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_add_log_shipping_primary_secondary must be run from the master database on the primary server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

Examples
This example illustrates using sp_add_log_shipping_primary_secondary to add an entry for the secondary
database LogShipAdventureWorks to the secondary server FLATIRON.
EXEC master.dbo.sp_add_log_shipping_primary_secondary
@primary_database = N'AdventureWorks'
, @secondary_server = N'flatiron'
, @secondary_database = N'LogShipAdventureWorks' ;
GO

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_add_log_shipping_secondary_database (Transact-
SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Sets up a secondary databases for log shipping.
Transact-SQL Syntax Conventions

Syntax
sp_add_log_shipping_secondary_database
[ @secondary_database = ] 'secondary_database',
[ @primary_server = ] 'primary_server',
[ @primary_database = ] 'primary_database',
[, [ @restore_delay = ] 'restore_delay']
[, [ @restore_all = ] 'restore_all']
[, [ @restore_mode = ] 'restore_mode']
[, [ @disconnect_users = ] 'disconnect_users']
[, [ @block_size = ] 'block_size']
[, [ @buffer_count = ] 'buffer_count']
[, [ @max_transfer_size = ] 'max_transfer_size']
[, [ @restore_threshold = ] 'restore_threshold']
[, [ @threshold_alert = ] 'threshold_alert']
[, [ @threshold_alert_enabled = ] 'threshold_alert_enabled']
[, [ @history_retention_period = ] 'history_retention_period']

Arguments
[ @secondary_database = ] 'secondary_database'
Is the name of the secondary database. secondary_database is sysname, with no default.
[ @primary_server = ] 'primary_server'
The name of the primary instance of the Microsoft SQL Server Database Engine in the log shipping configuration.
primary_server is sysname and cannot be NULL.
[ @primary_database = ] 'primary_database'
Is the name of the database on the primary server. primary_database is sysname, with no default.
[ @restore_delay = ] 'restore_delay'
The amount of time, in minutes, that the secondary server waits before restoring a given backup file. restore_delay
is int and cannot be NULL. The default value is 0.
[ @restore_all = ] 'restore_all'
If set to 1, the secondary server restores all available transaction log backups when the restore job runs. Otherwise,
it stops after one file is restored. restore_all is bit and cannot be NULL.
[ @restore_mode = ] 'restore_mode'
The restore mode for the secondary database.
0 = Restore log with NORECOVERY.
1 = restore log with STANDBY.
restore is bit and cannot be NULL.
[ @disconnect_users = ] 'disconnect_users'
If set to 1, users are disconnected from the secondary database when a restore operation is performed. Default = 0.
disconnect users is bit and cannot be NULL.
[ @block_size = ] 'block_size'
The size, in bytes, that is used as the block size for the backup device. block_size is int with a default value of -1.
[ @buffer_count = ] 'buffer_count'
The total number of buffers used by the backup or restore operation. buffer_count is int with a default value of -1.
[ @max_transfer_size = ] 'max_transfer_size'
The size, in bytes, of the maximum input or output request which is issued by SQL Server to the backup device.
max_transfersize is int and can be NULL.
[ @restore_threshold = ] 'restore_threshold'
The number of minutes allowed to elapse between restore operations before an alert is generated.
restore_threshold is int and cannot be NULL.
[ @threshold_alert = ] 'threshold_alert'
Is the alert to be raised when the backup threshold is exceeded. threshold_alert is int, with a default of 14,420.
[ @threshold_alert_enabled = ] 'threshold_alert_enabled'
Specifies whether an alert is raised when backup_threshold is exceeded. The value of one (1), the default, means
that the alert is raised. threshold_alert_enabled is bit.
[ @history_retention_period = ] 'history_retention_period'
Is the length of time in minutes in which the history is retained. history_retention_period is int, with a default of
NULL. A value of 14420 is used if none is specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_add_log_shipping_secondary_database must be run from the master database on the secondary server.
This stored procedure does the following:
1. sp_add_log_shipping_secondary_primary should be called prior to this stored procedure to initialize the
primary log shipping database information on the secondary server.
2. Adds an entry for the secondary database in log_shipping_secondary_databases using the supplied
arguments.
3. Adds a local monitor record in log_shipping_monitor_secondary on the secondary server using supplied
arguments.
4. If the monitor server is different from the secondary server, adds a monitor record in
log_shipping_monitor_secondary on the monitor server using supplied arguments.
Permissions
Only members of the sysadmin fixed server role can run this procedure.

Examples
This example illustrates using the sp_add_log_shipping_secondary_database stored procedure to add the
database LogShipAdventureWorks as a secondary database in a log shipping configuration with the primary
database AdventureWorks2012 residing on the primary server TRIBECA.

EXEC master.dbo.sp_add_log_shipping_secondary_database
@secondary_database = N'LogShipAdventureWorks'
,@primary_server = N'TRIBECA'
,@primary_database = N'AdventureWorks2012'
,@restore_delay = 0
,@restore_mode = 1
,@disconnect_users = 0
,@restore_threshold = 45
,@threshold_alert_enabled = 0
,@history_retention_period = 1440 ;
GO

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_add_log_shipping_secondary_primary (Transact-
SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Sets up the primary information, adds local and remote monitor links, and creates copy and restore jobs on the
secondary server for the specified primary database.
Transact-SQL Syntax Conventions

Syntax
sp_add_log_shipping_secondary_primary
[ @primary_server = ] 'primary_server',
[ @primary_database = ] 'primary_database',
[ @backup_source_directory = ] 'backup_source_directory' ,
[ @backup_destination_directory = ] 'backup_destination_directory'
[ @copy_job_name = ] 'copy_job_name'
[ @restore_job_name = ] 'restore_job_name'
[, [ @file_retention_period = ] 'file_retention_period']
[, [ @monitor_server = ] 'monitor_server']
[, [ @monitor_server_security_mode = ] 'monitor_server_security_mode']
[, [ @monitor_server_login = ] 'monitor_server_login']
[, [ @monitor_server_password = ] 'monitor_server_password']
[, [ @copy_job_id = ] 'copy_job_id' OUTPUT ]
[, [ @restore_job_id = ] 'restore_job_id' OUTPUT ]
[, [ @secondary_id = ] 'secondary_id' OUTPUT]

Arguments
[ @primary_server = ] 'primary_server'
The name of the primary instance of the Microsoft SQL Server Database Engine in the log shipping configuration.
primary_server is sysname and cannot be NULL.
[ @primary_database = ] 'primary_database'
Is the name of the database on the primary server. primary_database is sysname, with no default.
[ @backup_source_directory = ] 'backup_source_directory'
The directory where transaction log backup files from the primary server are stored. backup_source_directory is
nvarchar(500) and cannot be NULL.
[ @backup_destination_directory = ] 'backup_destination_directory'
The directory on the secondary server where backup files are copied to. backup_destination_directory is
nvarchar(500) and cannot be NULL.
[ @copy_job_name = ] 'copy_job_name'
The name to use for the SQL Server Agent job being created to copy transaction log backups to the secondary
server. copy_job_name is sysname and cannot be NULL.
[ @restore_job_name = ] 'restore_job_name'
Is the name of the SQL Server Agent job on the secondary server that restores the backups to the secondary
database. restore_job_name is sysname and cannot be NULL.
[ @file_retention_period = ] 'file_retention_period'
The length of time, in minutes, that a backup file is retained on the secondary server in the path specified by the
@backup_destination_directory parameter before being deleted. history_retention_period is int, with a default of
NULL. A value of 14420 will be used if none is specified.
[ @monitor_server = ] 'monitor_server'
Is the name of the monitor server. Monitor_server is sysname, with no default, and cannot be NULL.
[ @monitor_server_security_mode = ] 'monitor_server_security_mode'
The security mode used to connect to the monitor server.
1 = Windows Authentication.
0 = SQL Server authentication.
monitor_server_security_mode is bit and cannot be NULL.
[ @monitor_server_login = ] 'monitor_server_login'
Is the username of the account used to access the monitor server.
[ @monitor_server_password = ] 'monitor_server_password'
Is the password of the account used to access the monitor server.
[ @copy_job_id = ] 'copy_job_id' OUTPUT
The ID associated with the copy job on the secondary server. copy_job_id is uniqueidentifier and cannot be NULL.
[ @restore_job_id = ] 'restore_job_id' OUTPUT
The ID associated with the restore job on the secondary server. restore_job_id is uniqueidentifier and cannot be
NULL.
[ @secondary_id = ] 'secondary_id' OUTPUT
The ID for the secondary server in the log shipping configuration. secondary_id is uniqueidentifier and cannot be
NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_add_log_shipping_secondary_primary must be run from the master database on the secondary server. This
stored procedure does the following:
1. Generates a secondary ID for the specified primary server and primary database.
2. Does the following:
a. Adds an entry for the secondary ID in log_shipping_secondary using the supplied arguments.
b. Creates a copy job for the secondary ID that is disabled.
c. Sets the copy job ID in the log_shipping_secondary entry to the job ID of the copy job.
d. Creates a restore job for the secondary ID that is disabled.
e. Set the restore job ID in the log_shipping_secondary entry to the job ID of the restore job.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

Examples
This example illustrates using the sp_add_log_shipping_secondary_primary stored procedure to set up
information for the primary database AdventureWorks2012 on the secondary server.

EXEC master.dbo.sp_add_log_shipping_secondary_primary
@primary_server = N'TRIBECA'
,@primary_database = N'AdventureWorks'
,@backup_source_directory = N'\\tribeca\LogShipping'
,@backup_destination_directory = N''
,@copy_job_name = N''
,@restore_job_name = N''
,@file_retention_period = 1440
,@monitor_server = N'ROCKAWAY'
,@monitor_server_security_mode = 1
,@copy_job_id = @LS_Secondary__CopyJobId OUTPUT
,@restore_job_id = @LS_Secondary__RestoreJobId OUTPUT
,@secondary_id = @LS_Secondary__SecondaryId OUTPUT ;
GO

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_add_log_shipping_alert_job (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This stored procedure checks to see if an alert job has been created on this server. If an alert job does not exist, this
stored procedure creates the alert job and adds its job ID to the log_shipping_monitor_alert table. The alert job is
enabled by default and runs on a schedule of once every two minutes.
Transact-SQL Syntax Conventions

Syntax
sp_add_log_shipping_alert_job
[, [ @alert_job_id = ] alert_job_id OUTPUT ]

Arguments
[ @alert_job_id = ] alert_job_id OUTPUT
The Microsoft SQL Server Agent job ID of the log shipping alert job.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_add_log_shipping_alert_job must be run from the master database on the monitor server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

Examples
This example shows the execution of sp_add_log_shipping_alert_job to create an alert job ID.

USE master
GO
EXEC sp_add_log_shipping_alert_job;

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_can_tlog_be_applied (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Verifies whether a transaction log backup can be applied to a SQL Server database. sp_can_tlog_be_applied
requires that the database be in the Restoring state.
Transact-SQL Syntax Conventions

Syntax
sp_can_tlog_be_applied [ @backup_file_name = ] 'backup_file_name'
, [ @database_name = ] 'database_name'
, [ @result = ] result OUTPUT

Arguments
[ @backup_file_name= ] 'backup_file_name'
Is the name of a backup file. backup_file_name is nvarchar(128).
[ @database_name= ] 'database_name'
Is the name of the database. database_name is sysname.
[ @result= ] result OUTPUT
Indicates whether the transaction log can be applied to the database. result is bit.
1 = The log can be applies
0= The log cannot be applied.

Return Code Values


0 (success) or 1 (failure)

Permissions
Only members of the sysadmin fixed server role can execute sp_can_tlog_be_applied.

Examples
The following example declares a local variable, @MyBitVar , to store the result.
USE master;
GO
DECLARE @MyBitVar BIT;
EXEC sp_can_tlog_be_applied
@backup_file_name =
N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\AdventureWorks2012.bak',
@database_name = N'AdventureWorks2012',
@result = @MyBitVar OUTPUT;
GO

See Also
System Stored Procedures (Transact-SQL)
sp_change_log_shipping_primary_database (Transact-
SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the primary database settings.
Transact-SQL Syntax Conventions

Syntax
sp_change_log_shipping_primary_database [ @database = ] 'database'
[, [ @backup_directory = ] 'backup_directory']
[, [ @backup_share = ] 'backup_share']
[, [ @backup_retention_period = ] 'backup_retention_period']
[, [ @monitor_server_security_mode = ] 'monitor_server_security_mode']
[, [ @monitor_server_login = ] 'monitor_server_login']
[, [ @monitor_server_password = ] 'monitor_server_password']
[, [ @backup_threshold = ] 'backup_threshold']
[, [ @threshold_alert = ] 'threshold_alert']
[, [ @threshold_alert_enabled = ] 'threshold_alert_enabled']
[, [ @history_retention_period = ] 'history_retention_period']
[, [ @backup_compression = ] backup_compression_option ]

Arguments
[ @database = ] 'database'
Is the name of the database on the primary server. primary_database is sysname, with no default.
[ @backup_directory = ] 'backup_directory'
Is the path to the backup folder on the primary server. backup_directory is nvarchar(500), with no default, and
cannot be NULL.
[ @backup_share = ] 'backup_share'
Is the network path to the backup directory on the primary server. backup_share is nvarchar(500), with no default,
and cannot be NULL.
[ @backup_retention_period = ] 'backup_retention_period'
Is the length of time, in minutes, to retain the log backup file in the backup directory on the primary server.
backup_retention_period is int, with no default, and cannot be NULL.
[ @monitor_server_security_mode = ] 'monitor_server_security_mode'
The security mode used to connect to the monitor server.
1 = Windows Authentication.
0 = SQL Server Authentication.
monitor_server_security_mode is bit and cannot be NULL.
[ @monitor_server_login = ] 'monitor_server_login'
Is the username of the account used to access the monitor server.
[ @monitor_server_password = ] 'monitor_server_password'
Is the password of the account used to access the monitor server.
[ @backup_threshold = ] 'backup_threshold'
Is the length of time, in minutes, after the last backup before a threshold_alert error is raised. backup_threshold is
int, with a default of 60 minutes.
[ @threshold_alert = ] 'threshold_alert'
The alert to be raised when the backup threshold is exceeded. threshold_alert is int and cannot be NULL.
[ @threshold_alert_enabled = ] 'threshold_alert_enabled'
Specifies whether an alert is raised when backup_threshold is exceeded.
1 = enabled.
0 = disabled.
threshold_alert_enabled is bit and cannot be NULL.
[ @history_retention_period = ] 'history_retention_period'
Is the length of time in minutes in which the history is retained. history_retention_period is int. A value of 14420 is
used if none is specified.
[ @backup_compression= ] backup_compression_option
Specifies whether a log shipping configuration uses backup compression. This parameter is supported only in SQL
Server 2008 Enterprise (or a later version).
0 = Disabled. Never compress log backups.
1 = Enabled. Always compress log backups.
2 = Use the setting of the View or Configure the backup compression default Server Configuration Option. This is
the default value.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_change_log_shipping_primary_database must be run from the master database on the primary server. This
stored procedure does the following:
1. Changes the settings in the log_shipping_primary_database record, if necessary.
2. Changes the local record in log_shipping_monitor_primary on the primary server using supplied
arguments, if necessary.
3. If the monitor server is different from the primary server, changes record in
log_shipping_monitor_primary on the monitor server using supplied arguments, if necessary.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

Examples
This example illustrates the use of sp_change_log_shipping_primary_database to update the settings
associated with the primary database AdventureWorks2012.

EXEC master.dbo.sp_change_log_shipping_primary_database
@database = N'AdventureWorks'
, @backup_directory = N'c:\LogShipping'
, @backup_share = N'\\tribeca\LogShipping'
, @backup_retention_period = 1440
, @backup_threshold = 60
, @threshold_alert = 0
, @threshold_alert_enabled = 1
, @history_retention_period = 1440
,@monitor_server_security_mode = 1
,@backup_compression = 1;

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
log_shipping_primary_databases (Transact-SQL)
sp_change_log_shipping_secondary_database
(Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes secondary database settings.
Transact-SQL Syntax Conventions

Syntax
sp_change_log_shipping_secondary_database
[ @secondary_database = ] 'secondary_database',
[, [ @restore_delay = ] 'restore_delay']
[, [ @restore_all = ] 'restore_all']
[, [ @restore_mode = ] 'restore_mode']
[, [ @disconnect_users = ] 'disconnect_users']
[, [ @block_size = ] 'block_size']
[, [ @buffer_count = ] 'buffer_count']
[, [ @max_transfer_size = ] 'max_transfer_size']
[, [ @restore_threshold = ] 'restore_threshold']
[, [ @threshold_alert = ] 'threshold_alert']
[, [ @threshold_alert_enabled = ] 'threshold_alert_enabled']
[, [ @history_retention_period = ] 'history_retention_period']

Arguments
[ @restore_delay = ] 'restore_delay'
The amount of time, in minutes, that the secondary server waits before restoring a given backup file. restore_delay
is int and cannot be NULL. The default value is 0.
[ @restore_all = ] 'restore_all'
If set to 1, the secondary server restores all available transaction log backups when the restore job runs. Otherwise,
it stops after one file has been restored. restore_all is bit and cannot be NULL.
[ @restore_mode = ] 'restore_mode'
The restore mode for the secondary database.
0 = restore log with NORECOVERY.
1 = restore log with STANDBY.
restore is bit and cannot be NULL.
[ @disconnect_users = ] 'disconnect_users'
If set to 1, users is disconnected from the secondary database when a restore operation is performed. Default = 0.
disconnect_users is bit and cannot be NULL.
[ @block_size = ] 'block_size'
The size, in bytes, that is used as the block size for the backup device. block_size is int with a default value of -1.
[ @buffer_count = ] 'buffer_count'
The total number of buffers used by the backup or restore operation. buffer_count is int with a default value of -1.
[ @max_transfer_size = ] 'max_transfer_size'
The size, in bytes, of the maximum input or output request which is issued by SQL Server to the backup device.
max_transfersize is int and can be NULL.
[ @restore_threshold = ] 'restore_threshold'
The number of minutes allowed to elapse between restore operations before an alert is generated.
restore_threshold is int and cannot be NULL.
[ @threshold_alert = ] 'threshold_alert'
Is the alert to be raised when the restore threshold is exceeded. threshold_alert is int, with a default of 14420.
[ @threshold_alert_enabled = ] 'threshold_alert_enabled'
Specifies whether an alert will be raised when restore_thresholdis exceeded. 1 = enabled; 0 = disabled.
threshold_alert_enabled is bit and cannot be NULL.
[ @history_retention_period = ] 'history_retention_period'
Is the length of time in minutes in which the history will be retained. history_retention_period is int. A value of
1440 will be used if none is specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_change_log_shipping_secondary_database must be run from the master database on the secondary server.
This stored procedure does the following:
1. Changes the settings in the log_shipping_secondary_database records as necessary.
2. Changes the local monitor record in log_shipping_monitor_secondary on the secondary server using
supplied arguments, if necessary.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

Examples
This example illustrates using sp_change_log_shipping_secondary_database to update secondary database
parameters for the database LogShipAdventureWorks.

EXEC master.dbo.sp_change_log_shipping_secondary_database
@secondary_database = 'LogShipAdventureWorks'
, @restore_delay = 0
, @restore_all = 1
, @restore_mode = 0
, @disconnect_users = 0
, @threshold_alert = 14420
, @threshold_alert_enabled = 1
, @history_retention_period = 14420;
See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_change_log_shipping_secondary_primary
(Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes secondary database settings.
Transact-SQL Syntax Conventions

Syntax
sp_change_log_shipping_secondary_primary
[ @primary_server = ] 'primary_server',
[ @primary_database = ] 'primary_database',
[, [ @backup_source_directory = ] 'backup_source_directory']
[, [ @backup_destination_directory = ] 'backup_destination_directory']
[, [ @file_retention_period = ] file_retention_period]
[, [ @monitor_server_security_mode = ] monitor_server_security_mode]
[, [ @monitor_server_login = ] 'monitor_server_login']
[, [ @monitor_server_password = ] 'monitor_server_password']

Arguments
[ @primary_server = ] 'primary_server'
The name of the primary instance of the Microsoft SQL Server Database Engine in the log shipping configuration.
primary_server is sysname and cannot be NULL.
[ @primary_database = ] 'primary_database'
Is the name of the database on the primary server. primary_database is sysname, with no default.
[ @backup_source_directory = ] 'backup_source_directory'
The directory where transaction log backup files from the primary server are stored. backup_source_directory is
nvarchar(500) and cannot be NULL.
[ @backup_destination_directory = ] 'backup_destination_directory'
The directory on the secondary server where backup files are copied to. backup_destination_directory is
nvarchar(500) and cannot be NULL.
[ @file_retention_period = ] 'file_retention_period'
Is the length of time in minutes in which the history will be retained. history_retention_period is int, with a default
of NULL. A value of 14420 will be used if none is specified.
[ @monitor_server_security_mode = ] 'monitor_server_security_mode'
The security mode used to connect to the monitor server.
1 = Windows Authentication;
0 = SQL Server Authentication. monitor_server_security_mode is bit and cannot be NULL.
[ @monitor_server_login = ] 'monitor_server_login'
Is the username of the account used to access the monitor server.
[ @monitor_server_password = ] 'monitor_server_password'
Is the password of the account used to access the monitor server.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_change_log_shipping_secondary_primary must be run from the master database on the secondary server.
This stored procedure does the following:
1. Changes settings in the log_shipping_secondary records as necessary.
2. If the monitor server is different from the secondary server, changes monitor record in
log_shipping_monitor_secondary on the monitor server using supplied arguments, if necessary.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_cleanup_log_shipping_history (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This stored procedure cleans up history locally and on the monitor server based on retention period.
Transact-SQL Syntax Conventions

Syntax
sp_cleanup_log_shipping_history
[ @agent_id = ] 'agent_id',
[ @agent_type = ] 'agent_type'

Arguments
[ @agent_id = ] 'agent_id',
The primary ID for backup or the secondary ID for copy or restore. agent_id is uniqueidentifier and cannot be
NULL.
[ @agent_type = ] 'agent_type'
The type of log shipping job. 0 = Backup, 1 = Copy, 2 = Restore. agent_type is tinyint and cannot be NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Remarks
sp_cleanup_log_shipping_history must be run from the master database on any log shipping server. This
stored procedure cleans up local and remote copies of log_shipping_monitor_history_detail and
log_shipping_monitor_error_detail based on history retention period.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_delete_log_shipping_secondary_primary (Transact-
SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This stored procedure removes the information about the specified primary server from the secondary server, and
removes the copy job and restore job from the secondary.
Transact-SQL Syntax Conventions

Syntax
sp_delete_log_shipping_secondary_primary
[ @primary_server = ] 'primary_server'
[ @primary_database = ] 'primary_database'

Arguments
[ @primary_server = ] 'primary_server'
The name of the primary instance of the Microsoft SQL Server Database Engine in the log shipping configuration.
primary_server is sysname and cannot be NULL.
[ @primary_database = ] 'primary_database'
Is the name of the database on the primary server. primary_database is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Remarks
sp_delete_log_shipping_secondary_primary must be run from the master database on the secondary server.
This stored procedure does the following:
1. Deletes the copy and restore jobs for the secondary ID.
2. Deletes the entry in log_shipping_secondary.
3. Calls sp_delete_log_shipping_alert_job on the monitor server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.
See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_delete_log_shipping_secondary_database
(Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This stored procedure removes a secondary database and removes the local history and remote history.
Transact-SQL Syntax Conventions

Syntax
sp_delete_log_shipping_secondary_database
[ @secondary_database = ] 'secondary_database'

Arguments
[ @secondary_database = ] 'secondary_database'
Is the name of the secondary database. secondary_database is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Remarks
sp_delete_log_shipping_secondary_database must be run from the master database on the secondary server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_delete_log_shipping_primary_secondary (Transact-
SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes the entry for a secondary database on the primary server.
Transact-SQL Syntax Conventions

Syntax
sp_delete_log_shipping_primary_secondary
[ @primary_database = ] 'primary_database',
[ @secondary_server = ] 'secondary_server',
[ @secondary_database = ] 'secondary_database'

Arguments
[ @primary_database = ] 'primary_database'
Is the name of the database on the primary server. primary_database is sysname, with no default.
[ @secondary_server = ] 'secondary_server'
Is the name of the secondary server. secondary_server is sysname, with no default.
[ @secondary_database = ] 'secondary_database'
Is the name of the secondary database. secondary_database is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Remarks
sp_delete_log_shipping_primary_secondary must be run from the master database on the primary server. This
stored procedure removes the entry for a secondary database from log_shipping_primary_secondaries on the
primary server.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
In the following example, sp_delete_log_shipping_primary_secondary is used to delete the secondary database
LogShipAdventureWorks from the secondary server FLATIRON .

EXEC master.dbo.sp_delete_log_shipping_primary_secondary
@primary_database = N'AdventureWorks'
,@secondary_server = N'FLATIRON'
,@secondary_database = N'LogShipAdventureWorks';
GO

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_delete_log_shipping_primary_database (Transact-
SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
This stored procedure removes log shipping of primary database including backup job as well as local and remote
history. Only use this stored procedure after you have removed the secondary databases using
sp_delete_log_shipping_primary_secondary.
Transact-SQL Syntax Conventions

Syntax
sp_delete_log_shipping_primary_database
[ @database = ] 'database'

Arguments
[ @database = ] 'database'
Is the name of the log shipping primary database. database is sysname, with no default, and cannot be NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Remarks
sp_delete_log_shipping_primary_database must be run from the master database on the primary server. This
stored procedure does the following:
1. Deletes the backup job for the specified primary database.
2. Removes the local monitor record in log_shipping_monitor_primary on the primary server.
3. Removes corresponding entries in log_shipping_monitor_history_detail and
log_shipping_monitor_error_detail.
4. If the monitor server is different from the primary server, removes the monitor record in
log_shipping_monitor_primary on the monitor server.
5. Removes corresponding entries in log_shipping_monitor_history_detail and
log_shipping_monitor_error_detail on the monitor server.
6. Removes the entry in log_shipping_primary_databases for this primary database.
7. Calls sp_delete_log_shipping_alert_job on the monitor server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

Examples
This example illustrates using sp_delete_log_shipping_primary_database to delete the primary database
AdventureWorks2012.

EXEC master.dbo.sp_delete_log_shipping_primary_database @database = N'AdventureWorks2012';


GO

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_delete_log_shipping_alert_job (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes an alert job from the log shipping monitor server if the job exists and there are no more primary or
secondary databases to be monitored.
Transact-SQL Syntax Conventions

Syntax
sp_delete_log_shipping_alert_job

Arguments
None.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Remarks
sp_delete_log_shipping_alert_job must be run from the master database on the monitor server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

Examples
This example shows the execution of sp_delete_log_shipping_alert_job to delete an alert job.

USE master;
GO
EXEC sp_delete_log_shipping_alert_job;

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_help_log_shipping_alert_job (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This stored procedure returns the job ID of the alert job from the log shipping monitor.
Transact-SQL Syntax Conventions

Syntax
sp_help_log_shipping_alert_job

Arguments
None

Return Code Values


0 (success) or 1 (failure)

Result Sets
This stored procedure returns the Microsoft SQL Server Agent job ID of the log shipping alert job. If no log
shipping alert job exists, it returns an empty result set.

Remarks
sp_help_log_shipping_alert_job must be run from the master database on the monitor server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_help_log_shipping_monitor (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a result set containing status and other information for registered primary and secondary databases on a
primary, secondary, or monitor server.
Transact-SQL Syntax Conventions

Syntax
sp_help_log_shipping_monitor

Arguments
None.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

status bit Collective status of agents for the log


shipping database:

0 = healthy and no-agent failures.

1 = otherwise.

is_primary bit Indicates whether this row is for a


primary database:

1 = The row is for a primary database.

0 = The row is for a secondary


database.

server sysname The name of the primary or secondary


server where this database resides.

database_name sysname The database name.


COLUMN NAME DATA TYPE DESCRIPTION

time_since_last_backup int The length of time, in minutes, since the


last log backup.

NULL = The information is not available


or is not relevant.

last_backup_file nvarchar(500) The name of the last successful log


backup file.

NULL = The information is not available


or is not relevant.

backup_threshold int The length of time, in minutes, after the


last backup before a threshold_alert
error is raised. backup_threshold is int,
with a default of 60 minutes.

NULL = The information is not available


or is not relevant.

This value can be changed using


sp_add_log_shipping_primary_database
(Transact-SQL).

is_backup_alert_enabled bit Specifies whether an alert will be raised


when backup_threshold is exceeded.
The value of one (1), the default, means
that the alert will be raised.

NULL = The information is not available


or is not relevant.

This value can be changed using


sp_add_log_shipping_primary_database
(Transact-SQL).

time_since_last_copy int The length of time, in minutes, since the


last log backup was copied.

NULL = The information is not available


or is not relevant.

last_copied_file nvarchar(500) The name of the last successfully copied


log backup file.

NULL = The information is not available


or is not relevant.

time_since_last_restore int The length of time, in minutes, since the


last log backup was restored.

NULL = The information is not available


or is not relevant.
COLUMN NAME DATA TYPE DESCRIPTION

last_restored_file nvarchar(500). The name of the last successfully


restored log backup file.

NULL = The information is not available


or is not relevant.

last_restored_latency int Duration of time, in minutes, from the


creation of the last backup to restore of
the backup.

NULL = The information is not available


or is not relevant.

restore_threshold int The number of minutes allowed to


elapse between restore operations
before an alert is generated.
restore_threshold cannot be NULL.

is_restore_alert_enabled bit Specifies whether an alert is raised when


restore_threshold is exceeded. The
value of one (1), the default, means that
the alert is raised.

NULL = The information is not available


or is not relevant.

To set restore threshold, use


sp_add_log_shipping_secondary_databa
se.

Remarks
sp_help_log_shipping_monitor must be run from the master database on the monitor server.

Permissions
Requires membership in the sysadmin fixed server role.

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_help_log_shipping_monitor_primary (Transact-
SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns information regarding a primary database from the monitor tables.
Transact-SQL Syntax Conventions

Syntax
sp_help_log_shipping_monitor_primary
[ @primary_server = ] 'primary_server',
[ @primary_database = ] 'primary_database'

Arguments
[ @primary_server = ] 'primary_server'
The name of the primary instance of the Microsoft SQL Server Database Engine in the log shipping configuration.
primary_server is sysname and cannot be NULL.
[ @primary_database = ] 'primary_database'
Is the name of the database on the primary server. primary_database is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DESCRIPTION

primary_id The ID of the primary database for the log shipping


configuration.

primary_server The name of the primary instance of the SQL Server Database
Engine in the log shipping configuration.

primary_database The name of the primary database in the log shipping


configuration.

backup_threshold The number of minutes allowed to elapse between backup


operations before an alert is generated.

threshold_alert The alert to be raised when the backup threshold is exceeded.


COLUMN NAME DESCRIPTION

threshold_alert_enabled Determines if backup threshold alerts are enabled. 1 =


enabled; 0 = disabled.

last_backup_file The absolute path of the most recent transaction log backup.

last_backup_date The time and date of the last transaction log backup operation
on the primary database.

last_backup_date_utc The time and date of the last transaction log backup operation
on the primary database, expressed in Coordinated Universal
Time.

history_retention_period The amount of time, in minutes, that log shipping history


records are retained for a given primary database before being
deleted.

Remarks
sp_help_log_shipping_monitor_primary must be run from the master database on the monitor server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_help_log_shipping_monitor_secondary (Transact-
SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns information regarding a secondary database from the monitor tables.
Transact-SQL Syntax Conventions

Syntax
sp_help_log_shipping_monitor_secondary
[ @secondary_server = ] 'secondary_server',
[ @secondary_database = ] 'secondary_database'

Arguments
[ @secondary_server = ] 'secondary_server'
Is the name of the secondary server. secondary_server is sysname, with no default.
[ @secondary_database = ] 'secondary_database'
Is the name of the secondary database. secondary_database is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN DESCRIPTION

secondary_server The name of the secondary instance of the Microsoft SQL


Server Database Engine in the log shipping configuration.

secondary_database The name of the secondary database in the log shipping


configuration.

secondary_id The ID for the secondary server in the log shipping


configuration.

primary_server The name of the primary instance of the SQL Server Database
Engine in the log shipping configuration.

primary_database The name of the primary database in the log shipping


configuration.
COLUMN DESCRIPTION

restore_threshold The number of minutes allowed to elapse between restore


operations before an alert is generated.

threshold_alert The alert to be raised when the restore threshold is exceeded.

threshold_alert_enabled Determines if restore threshold alerts are enabled.

1 = Enabled.

0 = Disabled.

last_copied_file The filename of the last backup file copied to the secondary
server.

last_copied_date The time and date of the last copy operation to the secondary
server.

last_copied_date_utc The time and date of the last copy operation to the secondary
server, expressed in Coordinated Universal Time.

last_restored_file The filename of the last backup file restored to the secondary
database.

last_restored_date The time and date of the last restore operation on the
secondary database.

last_restored_date_utc The time and date of the last restore operation on the
secondary database, expressed in Coordinated Universal Time.

history_retention_period The amount of time, in minutes, that log shipping history


records are retained for a given secondary database before
being deleted.

Remarks
sp_help_log_shipping_monitor_secondary must be run from the master database on the monitor server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

See also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_help_log_shipping_primary_database (Transact-
SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Retrieves primary database settings.
Transact-SQL Syntax Conventions

Syntax
sp_help_log_shipping_primary_database
[ @database = ] 'database' OR
[ @primary_id = ] 'primary_id'

Arguments
[ @database = ] 'database'
Is the name of the log shipping primary database. database is sysname, with no default, and cannot be NULL.
[ @primary_id = ] 'primary_id'
The ID of the primary database for the log shipping configuration. primary_id is uniqueidentifier and cannot be
NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DESCRIPTION

primary_id The ID of the primary database for the log shipping


configuration.

primary_database The name of the primary database in the log shipping


configuration.

backup_directory The directory where transaction log backup files from the
primary server are stored.

backup_share The network or UNC path to the backup directory.

backup_retention_period The length of time, in minutes, that a log backup file is


retained in the backup directory before being deleted.
COLUMN NAME DESCRIPTION

backup_compression Indicates whether the log shipping configuration uses backup


compression.

0 = Disabled. Never compress log backups.

1 = Enabled. Always compress log backups.

2 = Use the setting of the View or Configure the backup


compression default Server Configuration Option. This is the
default value.

Backup compression is supported only in SQL Server 2008


Enterprise (or a later version). In other editions, the value is
always 2.

backup_job_id The Microsoft SQL Server Agent job ID associated with the
backup job on the primary server.

monitor_server The name of the instance of the SQL Server Database Engine
being used as a monitor server in the log shipping
configuration.

monitor_server_security_mode The security mode used to connect to the monitor server.

1 = Microsoft Windows Authentication.

0 = SQL Server Authentication.

backup_threshold The number of minutes allowed to elapse between backup


operations before an alert is generated.

threshold_alert The alert to be raised when the backup threshold is exceeded.

threshold_alert_enabled Determines if backup threshold alerts are enabled.

1 = Enabled.

0 = Disabled.

last_backup_file The absolute path of the most recent transaction log backup.

last_backup_date The time and date of the last log backup operation.

last_backup_date_utc The time and date of the last transaction log backup operation
on the primary database, expressed in Coordinated Universal
Time.

history_retention_period The amount of time, in minutes, that log shipping history


records are retained for a given primary database before being
deleted.

Remarks
sp_help_log_shipping_primary_database must be run from the master database on the primary server.
Permissions
Only members of the sysadmin fixed server role can run this procedure.

Examples
This example illustrates using sp_help_log_shipping_primary_database to retrieve primary database settings
for the database AdventureWorks2012.

EXEC master.dbo.sp_help_log_shipping_primary_database @database=N'AdventureWorks2012';


GO

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_help_log_shipping_primary_secondary (Transact-
SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This stored procedure returns information regarding all the secondary databases for a given primary database.
Transact-SQL Syntax Conventions

Syntax
sp_help_log_shipping_primary_secondary
[ @primary_database = ] 'primary_database'

Arguments
[ @primary_database = ] 'primary_database'
Is the name of the database on the primary server. primary_database is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DESCRIPTION

secondary_server The name of the secondary instance of the Microsoft SQL


Server Database Engine in the log shipping configuration.

secondary_database The name of the secondary database in the log shipping


configuration.

Remarks
sp_help_log_shipping_primary_secondary must be run from the master database on the primary server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

Examples
This example illustrates using sp_help_log_shipping_primary_secondary to retrieve a list of secondary
databases associate with the primary database AdventureWorks2012.
EXECUTE master.dbo.sp_help_log_shipping_primary_secondary @primary_database=N'AdventureWorks';
GO

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_help_log_shipping_secondary_database (Transact-
SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This stored procedure retrieves the settings for one or more secondary databases.
Transact-SQL Syntax Conventions

Syntax
sp_help_log_shipping_secondary_database
[ @secondary_database = ] 'secondary_database' OR
[ @secondary_id = ] 'secondary_id'

Arguments
[ @secondary_database = ] 'secondary_database'
Is the name of the secondary database. secondary_database is sysname, with no default.
[ @secondary_id = ] 'secondary_id'
The ID for the secondary server in the log shipping configuration. secondary_id is uniqueidentifier and cannot be
NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DESCRIPTION

secondary_id The ID for the secondary server in the log shipping


configuration.

primary_server The name of the primary instance of the Microsoft SQL Server
Database Engine in the log shipping configuration.

primary_database The name of the primary database in the log shipping


configuration.

backup_source_directory The directory where transaction log backup files from the
primary server are stored.

backup_destination_directory The directory on the secondary server where backup files are
copied to.
COLUMN NAME DESCRIPTION

file_retention_period The length of time, in minutes, that a backup file is retained on


the secondary server before being deleted.

copy_job_id The ID associated with the copy job on the secondary server.

restore_job_id The ID associated with the restore job on the secondary


server.

monitor_server The name of the instance of the SQL Server Database Engine
being used as a monitor server in the log shipping
configuration.

monitor_server_security_mode The security mode used to connect to the monitor server.

1 = Microsoft Windows Authentication.

0 = SQL Server Authentication.

secondary_database The name of the secondary database in the log shipping


configuration.

restore_delay The amount of time, in minutes, that the secondary server


waits before restoring a given backup file. The default is 0
minutes.

restore_all If set to 1, the secondary server restores all available


transaction log backups when the restore job runs. Otherwise,
it stops after one file has been restored.

restore_mode The restore mode for the secondary database.

0 = Restore log with NORECOVERY.

1 = Restore log with STANDBY.

disconnect_users If set to 1, users are disconnected from the secondary


database when a restore operation is performed. Default = 0.

block_size The size, in bytes, that is used as the block size for the backup
device.

buffer_count The total number of buffers used by the backup or restore


operation.

max_transfer_size The size, in bytes, of the maximum input or output request


which is issued by SQL Server to the backup device.

restore_threshold The number of minutes allowed to elapse between restore


operations before an alert is generated.

threshold_alert The alert to be raised when the restore threshold is exceeded.


COLUMN NAME DESCRIPTION

threshold_alert_enabled Determines if restore threshold alerts are enabled.

1 = Enabled.

0 = Disabled.

last_copied_file The filename of the last backup file copied to the secondary
server.

last_copied_date The time and date of the last copy operation to the secondary
server.

last_copied_date_utc The time and date of the last copy operation to the secondary
server, expressed in Coordinated Universal Time.

last_restored_file The filename of the last backup file restored to the secondary
database.

last_restored_date The time and date of the last restore operation on the
secondary database.

last_restored_date_utc The time and date of the last restore operation on the
secondary database, expressed in Coordinated Universal Time.

history_retention_period The amount of time, in minutes, that log shipping history


records are retained for a given secondary database before
being deleted.

last_restored_latency The amount of time, in minutes, that elapsed between when


the log backup was created on the primary and when it was
restored on the secondary.

The initial value is NULL.

Remarks
If you include the secondary_database parameter, the result set will contain information about that secondary
database; if you include the secondary_id parameter, the result set will contain information about all secondary
databases associated with that secondary ID.
sp_help_log_shipping_secondary_database must be run from the master database on the secondary server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

See Also
sp_help_log_shipping_secondary_primary (Transact-SQL)
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_help_log_shipping_secondary_primary (Transact-
SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
This stored procedure retrieves the settings for a given primary database on the secondary server.
Transact-SQL Syntax Conventions

Syntax
sp_help_log_shipping_secondary_primary
[ @primary_server = ] 'primary_server' OR
[ @primary_database = ] 'primary_database'

Arguments
[ @primary_server = ] 'primary_server'
The name of the primary instance of the Microsoft SQL Server Database Engine in the log shipping configuration.
primary_server is sysname and cannot be NULL.
[ @primary_database = ] 'primary_database'
Is the name of the database on the primary server. primary_database is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
The result set contains the columns secondary_id, primary_server, primary_database,
backup_source_directory, backup_destination_directory, file_retention_period, copy_job_id,
restore_job_id, monitor_server, monitor_server_security_mode from log_shipping_secondary.

Remarks
sp_help_log_shipping_secondary_primary must be run from the master database on the secondary server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_refresh_log_shipping_monitor (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This stored procedure refreshes the remote monitor tables with the latest information from a given primary or
secondary server for the specified log shipping agent. The procedure is invoked on the primary or secondary
server.
Transact-SQL Syntax Conventions

Syntax
sp_refresh_log_shipping_monitor
[ @agent_id = ] 'agent_id',
[ @agent_type = ] 'agent_type'
[ @database = ] 'database'
[ @mode ] n

Arguments
[ @agent_id= ] 'agent_id'
The primary ID for backup or the secondary ID for copy or restore. agent_id is uniqueidentifier and cannot be
NULL.
[ @agent_type= ] 'agent_type'
The type of log shipping job.
0 = Backup.
1 = Copy.
2 = Restore.
agent_type is tinyint and cannot be NULL.
[ @database= ] 'database'
The primary or secondary database used by logging by backup or restore agents.
[ @mode ] n
Specifies whether to refresh the monitor data or clean it. The data type of m is tinyint, and the supported values are:
1 = refresh (This is the default value.)
2 = delete

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Remarks
sp_refresh_log_shipping_monitor refreshes the log_shipping_monitor_primary,
log_shipping_monitor_secondary, log_shipping_monitor_history_detail, and
log_shipping_monitor_error_detail tables with any session information that has not already been transferred.
This allows you to synchronize the monitor server with primary or a secondary server when the monitor has been
out of sync for awhile. Additionally, it allows you to clean up the monitor information on monitor server if
necessary.
sp_refresh_log_shipping_monitor must be run from the master database on the primary or secondary server.

Permissions
Only members of the sysadmin fixed server role can run this procedure.

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
sp_upgrade_log_shipping (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
The sp_upgrade_log_shipping stored procedure is invoked automatically for upgrading metadata that is specific to
log shipping.
Transact-SQL Syntax Conventions

Syntax
sp_upgrade_log_shipping

Arguments
None.

Return Code Values


0 (success) or 1 (otherwise)

Result Sets
None.

Remarks
This stored procedure is invoked automatically during SQL Server upgrade for upgrading metadata for log
shipping. You do not need to execute this procedure explicitly, unless a problem occurs with the metadata during
upgrade.
sp_upgrade_log_shipping must be run from the master database on the primary, secondary, or monitor server.

Permissions
Requires membership in the sysadmin fixed server role.

See Also
About Log Shipping (SQL Server)
System Stored Procedures (Transact-SQL)
Managed Backup Stored Procedures (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
The following stored procedures can be used to configure SQL Server Managed Backup to Microsoft Azure.

In this section
managed_backup.sp_backup_config_basic (Transact-SQL)
managed_backup.sp_backup_config_advanced (Transact-SQL)
managed_backup.sp_backup_config_schedule (Transact-SQL)
managed_backup.sp_ backup_master_switch (Transact-SQL)
managed_backup.sp_set_parameter (Transact-SQL)
managed_backup.sp_get_backup_diagnostics (Transact-SQL)
managed_backup.sp_backup_on_demand (Transact-SQL)

See Also
SQL Server Managed Backup to Microsoft Azure
managed_backup.sp_backup_config_basic (Transact-
SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Configures the SQL Server Managed Backup to Microsoft Azure basic settings for a specific database or for an
instance of SQL Server.

NOTE
This procedure can be called on its own to create a basic managed backup configuration. However, if you plan to add
advanced features or a custom schedule, first configure those settings using managed_backup.sp_backup_config_advanced
(Transact-SQL) and managed_backup.sp_backup_config_schedule (Transact-SQL) before enabling managed backup with this
procedure.

Transact-SQL Syntax Conventions

Syntax
EXEC managed_backup.sp_backup_config_basic
[@enable_backup = ] { 0 | 1} ,[@database_name = ] 'database_name' ,[@container_url = ]
'Azure_Storage_blob_container
,[@retention_days = ] 'retention_period_in_days' ,[@credential_name = ] 'sql_credential_name'

Arguments
@enable_backup
Enable or disable SQL Server Managed Backup to Microsoft Azure for the specified database. The @enable_backup
is BIT. Required parameter when configuring SQL Server Managed Backup to Microsoft Azure for the first instance
of SQL Server. If you are changing an existing SQL Server Managed Backup to Microsoft Azure configuration, this
parameter is optional. In that case, any configuration values not specified retain their existing values.
@database_name
The database name for enabling managed backup on a specific database.
@container_url
A URL that indicates the location of the backup. When @credential_name is NULL, this URL is a shared access
signature (SAS) URL to a blob container in Azure Storage, and the backups use the new backup to block blob
functionality. For more information, please review Understanding SAS. When @credential_name is specified, then
this is a storage account URL, and the backups use the deprecated backup to page blob functionality.

NOTE
Only a SAS URL is supported for this parameter at this time.

@retention_days
The retention period for the backup files in days. The @storage_url is INT. This is a required parameter when
configuring SQL Server Managed Backup to Microsoft Azure for the first time on the instance of SQL Server. While
changing the SQL Server Managed Backup to Microsoft Azure configuration, this parameter is optional. If not
specified then the existing configuration values are retained.
@credential_name
The name of the SQL Credential used to authenticate to the Windows Azure storage account. @credentail_name is
SYSNAME. When specified, the backup is stored to a page blob. If this parameter is NULL, the backup will be
stored as a block blob. Backup to page blob is deprecated, so it is preferred to use the new block blob backup
functionality. When used to change the SQL Server Managed Backup to Microsoft Azure configuration, this
parameter is optional. If not specified, then the existing configuration values are retained.

WARNING
The @credential_name parameter is not supported at this time. Only backup to block blob is supported, which requires this
parameter to be NULL.

Return Code Value


0 (success) or 1 (failure)

Security
Permissions
Requires membership in db_backupoperator database role, with ALTER ANY CREDENTIAL permissions, and
EXECUTE permissions on sp_delete_backuphistory stored procedure.

Examples
You can create both the storage account container and the SAS URL by using the latest Azure PowerShell
commands. The following example creates a new container, mycontainer, in the mystorageaccount storage account
and then obtains a SAS URL for it with full permissions.

$context = New-AzureStorageContext -StorageAccountName mystorageaccount -StorageAccountKey (Get-


AzureStorageKey -StorageAccountName mystorageaccount).Primary
New-AzureStorageContainer -Name mycontainer -Context $context
New-AzureStorageContainerSASToken -Name mycontainer -Permission rwdl -FullUri -Context $context

The following example enables SQL Server Managed Backup to Microsoft Azure for the instance of SQL Server it is
executed on, sets the retention policy to 30 days, sets the destination to a container named 'mycontainer' in a
storage account named 'mystorageaccount'.

Use msdb;
Go
EXEC managed_backup.sp_backup_config_basic
@enable_backup=1
,@container_url = 'https://mystorageaccount.blob.core.windows.net/mycontainer'
,@retention_days=30;
GO

The following example disables SQL Server Managed Backup to Microsoft Azure for the instance of SQL Server it is
executed on.
Use msdb;
Go
EXEC managed_backup.sp_backup_config_basic
@enable_backup=0;
GO

See Also
managed_backup.sp_backup_config_advanced (Transact-SQL)
managed_backup.sp_backup_config_schedule (Transact-SQL)
managed_backup.sp_backup_config_advanced
(Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Configures advanced settings for SQL Server Managed Backup to Microsoft Azure.
Transact-SQL Syntax Conventions

Syntax
EXEC managed_backup.sp_backup_config_advanced
[@database_name = ] 'database_name'
,[@encryption_algorithm = ] 'name of the encryption algorithm'
,[@encryptor_type = ] {'CERTIFICATE' | 'ASYMMETRIC_KEY'}
,[@encryptor_name = ] 'name of the certificate or asymmetric key'
,[@local_cache_path = ] 'NOT AVAILABLE'

Arguments
@database_name
The database name for enabling managed backup on a specific database. If NULL or *, then this managed backup
applies to all databases on the server.
@encryption_algorithm
The name of the encryption algorithm used during the backup to encrypt the backup file. The
@encryption_algorithm is SYSNAME. It is a required parameter when configuring SQL Server Managed Backup to
Microsoft Azure for the first time for the database. Specify NO_ENCRYPTION if you do not wish to encrypt the
backup file. When changing the SQL Server Managed Backup to Microsoft Azure configuration settings, this
parameter is optional – if the parameter is not specified then the existing configuration values are retained. The
allowed values for this parameter are:
AES_128
AES_192
AES_256
TRIPLE_DES_3KEY
NO_ENCRYPTION
For more information on encryption algorithms, see Choose an Encryption Algorithm.
@encryptor_type
The type of encryptor, which can be either 'CERTIFICATE' or 'ASYMMETRIC_KEY". The @encryptor_type is
nvarchar(32). This parameter is optional if you specify NO_ENCRYPTION for the @encryption_algorithm
parameter.
@encryptor_name
The name of an existing certificate or asymmetric key to use to encrypt the backup. The @encryptor_name
is SYSNAME. If using an asymmetric key, it must be configured with Extended Key Management (EKM). This
parameter is optional if you specify NO_ENCRYPTION for the @encryption_algorithm parameter.
For more information, see Extensible Key Management (EKM).
@local_cache_path
This parameter is not yet supported.

Return Code Value


0 (success) or 1 (failure)

Security
Permissions
Requires membership in db_backupoperator database role, with ALTER ANY CREDENTIAL permissions, and
EXECUTE permissions on sp_delete_backuphistory stored procedure.

Examples
The following example sets advanced configuration options for SQL Server Managed Backup to Microsoft Azure
for the instance of SQL Server.

Use msdb;
Go
EXEC managed_backup.sp_backup_config_advanced
@encryption_algorithm ='AES_128'
,@encryptor_type = 'CERTIFICATE'
,@encryptor_name = 'MyTestDBBackupEncryptCert'
GO

See Also
managed_backup.sp_backup_config_basic (Transact-SQL)
managed_backup.sp_backup_config_schedule (Transact-SQL)
managed_backup.sp_backup_config_schedule
(Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Configures automated or custom scheduling options for SQL Server Managed Backup to Microsoft Azure.
Transact-SQL Syntax Conventions

Syntax
EXEC managed_backup.sp_backup_config_schedule
[@database_name = ] 'database_name' ,[@scheduling_option = ] {'Custom' | 'System'}
,[@full_backup_freq_type = ] {'Daily' | 'Weekly'}
,[@days_of_week = ] 'days_of_the_week'
,[@backup_begin_time = ] 'begin time of the backup window'
,[@backup_duration = ] 'backup window length'
,[@log_backup_freq = ] 'frequency of log backup'

Arguments
@database_name
The database name for enabling managed backup on a specific database. If NULL or *, then this managed backup
applies to all databases on the server.
@scheduling_option
Specify 'System' for system-controlled backup scheduling. Specify 'Custom' for a custom schedule defined by the
other paratmeters.
@full_backup_freq_type
The frequency type for the managed backup operation, which can be set to 'Daily' or 'Weekly'.
@days_of_week
The days of the week for the backups when @full_backup_freq_type is set to Weekly. Specify full string names like
'Monday'. You can also specify more than one day name, separated by commas. For example 'Monday,
Wednesday, Friday'.
@backup_begin_time
The start time of the backup window. Backups will not be started outside of the time window, which is defined by a
combination of @backup_begin_time and @backup_duration.
@backup_duration
The duration of the backup time window. Note that there is no guarantee that backups will be completed during
the time window defined by @backup_begin_time and @backup_duration. Backup operations that are started in
this time window but exceed the duration of the window will not be cancelled.
@log_backup_freq
This determines the frequency of transaction log backups. These backups happen at regular intervals rather than
on the schedule specified for the database backups. @log_backup_freq can be in minutes or hours and 0 is valid,
which indicates no log backups. Disabling log backups would only be appropriate for databases with a simple
recovery model.

NOTE
If the recovery model changes from simple to full, you need to reconfigure the log_backup_freq from 0 to a non-zero value.

Return Code Value


0 (success) or 1 (failure)

Security
Permissions
Requires membership in db_backupoperator database role, with ALTER ANY CREDENTIAL permissions, and
EXECUTE permissions on sp_delete_backuphistory stored procedure.

See Also
managed_backup.sp_backup_config_basic (Transact-SQL)
managed_backup.sp_backup_config_advanced (Transact-SQL)
managed_backup.sp_ backup_master_switch
(Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Pauses or resumes the SQL Server Managed Backup to Microsoft Azure.
Use this stored procedure to temporarily pause and them resume SQL Server Managed Backup to Microsoft Azure.
This makes sure that all the configurations settings remain and is retained when the operations resume. When SQL
Server Managed Backup to Microsoft Azure is paused the retention period is not enforced. This means that there is
no check to determine whether files should be deleted from storage or if there are backup file corrupted, or break
in log chain.
Transact-SQL Syntax Conventions

Syntax
EXEC managed_backup.sp_backup_master_switch
[@state = ] { 0 | 1}

Arguments
@state
Set the state of SQL Server Managed Backup to Microsoft Azure. The @state parameter is BIT. When set to a value
of 0 the operations are paused, and when set to a value of 1 the operation resume.

Return Code Value


0 (success) or 1 (failure)

Security
Describes security issues related to the statement.Include Permissions as a subsection (H3 heading). Consider
including other subsections for Ownership Chaining and Auditing if appropriate.
Permissions
Requires membership in db_backupoperator database role, with ALTER ANY CREDENTIAL permissions, and
EXECUTE permissions on sp_delete_backuphistorystored procedure.

Examples
The following example can be used to pause SQL Server Managed Backup to Microsoft Azure on the instance it is
executed on:
Use msdb;
GO
EXEC managed_backup.sp_master_switch @state=0;
Go

The following example can be used to resume SQL Server Managed Backup to Microsoft Azure.

Use msdb;
GO
EXEC managed_backup.sp_master_switch @state=1;
Go

See Also
SQL Server Managed Backup to Microsoft Azure
managed_backup.sp_set_parameter (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sets the value of the specified Smart Admin system parameter.
The available parameters are related to SQL Server Managed Backup to Microsoft Azure . These parameters are
used to set the email notifications, enable specific extended events, and enable user set policy based management
policies. You must specify the parameter name and the parameter value pairs..
Transact-SQL Syntax Conventions

Syntax
EXEC managed_backup.sp_set_parameter
[@parameter_name = ] {'SSMBackup2WANotificationEmailIds' | 'SSMBackup2WAEnableUserDefinedPolicy' |
'SSMBackup2WADebugXevent' | 'FileRetentionDebugXevent' | 'StorageOperationDebugXevent'}
,[@parameter_value = ] 'parameter_value'

Arguments
@parameter_name
The name of the parameter you want to set the value for. @parameter_name is NVARCHAR(128). The available
parameter names are SSMBackup2WANotificationEmailIds, SSMBackup2WADebugXevent,
SSMBackup2WAEnableUserDefinedPolicy, FileRetentionDebugXevent, and
StorageOperationDebugXevent.
@parameter_value
The value for the parameter you want to set. @parameter value is NVARCHAR(128). Following are the allowed
parameter name and value pairs:
@parameter_name = 'SSMBackup2WANotificationEmailIds' : @parameter_value = 'email'
@parameter_name = 'SSMBackup2WAEnableUserDefinedPolicy' : @parameter_value = { 'true' | 'false' }
@parameter_name = 'SSMBackup2WADebugXevent': @parameter_value = { 'true' | 'false' }
@parameter_name = 'FileRetentionDebugXevent' : @parameter_value = { 'true' | 'false' }
@parameter_name = 'StorageOperationDebugXevent' = { 'true' | 'false' }

Return Code Value


0 (success) or 1 (failure)

Best Practices
Optional section that describes best practices the user should know when executing the statement or routine.

Security
Permissions
Requires EXECUTE permissions on managed_backup.sp_set_parameter stored procedure.

Examples
The following examples enable operational and debug extended events.

-- to enable operational events


Use msdb;
Go
EXEC managed_backup.sp_set_parameter 'FileRetentionOperationalXevent', 'True'
-- to enable debug events
Use msdb;
Go
EXEC managed_backup.sp_set_parameter 'FileRetentionDebugXevent', 'True'

The following example enables email notifications of errors and warnings and sets the emailID to use to send the
notifications to:

Use msdb
Go
EXEC managed_backup.sp_set_parameter @parameter_name = 'SSMBackup2WANotificationEmailIds', @parameter_value =
'<email address>'
managed_backup.sp_get_backup_diagnostics
(Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the Extended Events logged by Smart Admin.
Use this stored procedure to monitor Extended Events logged by Smart Admin. SQL Server Managed Backup to
Microsoft Azure events are logged in this system and can be reviewed and monitored using this stored procedure.
Transact-SQL Syntax Conventions

Syntax
managed_backup.sp_get_backup_diagnostics [@xevent_channel = ] 'event type' [, [@begin_time = ] 'time1' ] [,
[@end_time = ] 'time2'VARCHAR(255) = 'Xevent',@begin_time DATETIME = NULL,@end_time DATETIME = NULL

Arguments
@xevent_channel
The type of Extended Event. The default value is set to return all events logged for the previous 30 minutes. The
events logged depend on the type of Extended Events enabled. You can use this parameter to filter the stored
procedure to show only events of a certain type. You can either specify the full event name or specify a substring
such as: ‘Admin’, ‘Analytic’, ‘Operational’, and ‘Debug’. The @event_channel is VARCHAR (255).
To get a list of event types currently enabled use the managed_backup.fn_get_current_xevent_settings
function.
[@begin_time
The start of the time period from which the events should be displayed. The @begin_time parameter is DATETIME
with a default value of NULL. If this is not specified then the events from the past 30 minutes is displayed.
@end_time
The end of the time period up to which the events should be displayed. The @end_time parameter is DATATIME
with a default value of NULL. If this is not specified then the events up to the current time is displayed.

Table Returned
This stored procedure returns a table with the following information:

Column Name Data Type Description

event_type NVARCHAR(512) Type of Extended Event.

Event NVARCHAR(512) Summary of the event logs.


Timestamp TIMESTAMP Timestamp of the event that shows
when the event was raised.

Security
Permissions
Requires EXECUTE permissions on the stored procedure. It also requires VIEW SERVER STATE permissions since
it internally calls other system objects that require this permission.

Examples
The following example returns all the events logged for the past 30 minutes

Use msdb
Go
EXEC managed_backup.sp_get_backup_diagnostics

The following example returns all the events logged for a specific time range.

Use msdb
Go
EXEC managed_backup.sp_get_backup_diagnostics @xevent_channel = 'Admin',
@begin_time = '2013-06-01', @end_time = '2013-06-10'

The following example returns all the analytical events logged for the past 30 minutes

Use msdb
Go
EXEC managed_backup.sp_get_backup_diagnostics @xevent_channel = 'Analytic'
managed_backup.sp_backup_on_demand (Transact-
SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Requests SQL Server Managed Backup to Microsoft Azure to perform a backup of the specified database.
Use this stored procedure to perform ad hoc backups for a database configured with SQL Server Managed Backup
to Microsoft Azure. This prevents any break in the backup chain and SQL Server Managed Backup to Microsoft
Azure processes are aware and the backup is stored in the same Windows Azure Blob storage container.
Upon successful completion of the backup the full backup file path is returned. This includes the name and location
of the new backup file resulting from the backup operation.
An error is returned if SQL Server Managed Backup to Microsoft Azure is in the process of executing a backup of
given type for the specified database. In this case, the error message returned includes the full backup file path
where the current backup is being uploaded to.
Transact-SQL Syntax Conventions

Syntax
EXEC managed_backup.sp_backup_on_demand
[@database_name =] 'database name',[@type = ] { 'Database' | 'Log' }

Arguments
@database_name
The name of the database on which the backup is to be performed. The @database_name is SYSNAME.
@type
The type of backup to be performed: Database or Log. The @type parameter is NVARCHAR(32).

Return Code Value


0 (success) or 1 (failure)

Security
Permissions
Requires membership in db_backupoperator database role, with ALTER ANY CREDENTIAL permissions, and
EXECUTE permissions on sp_delete_backuphistorystored procedure.

Examples
The following example makes a database backup request for the database ‘TestDB’. This database has SQL Server
Managed Backup to Microsoft Azure enabled.
Use MSDB
Go
EXEC managed_backup.sp_backup_on_demand
@database_name = 'TestDB'
,@type = 'Database'

For each code snippet, select 'tsql' in the language attribute field.
Management Data Warehouse Stored Procedures
(Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
The data collector stores data and data collector type information in the management data warehouse. The
following stored procedures are used to update data and change the tables in the management data warehouse.

core.sp_create_snapshot (Transact-SQL) core.sp_update_data_source (Transact-SQL)

core.sp_add_collector_type (Transact-SQL) core.sp_remove_collector_type (Transact-SQL)

core.sp_purge_data (Transact-SQL)

See Also
Data Collector Stored Procedures (Transact-SQL)
core.sp_create_snapshot (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Inserts a row in the management data warehouse core.snapshots view. This procedure is called every time an
upload package starts uploading data to the management data warehouse.
Transact-SQL Syntax Conventions

Syntax
core.sp_create_snapshot [ @collection_set_uid = ] 'collection_set_uid'
, [ @collector_type_uid = ] 'collector_type_uid'
,[ @machine_name = ] 'machine_name'
, [ @named_instance = ] 'named_instance'
, [ @log_id = ] log_id
, [ @snapshot_id = ] snapshot_id OUTPUT

Arguments
[ @collection_set_uid = ] 'collection_set_uid'
The GUID for the collection set. collection_set_uid is uniqueidentifier with no default value. To obtain the GUID,
query the dbo.syscollector_collection_sets view in the msdb database.
[ @collector_type_uid = ] 'collector_type_uid'
The GUID for a collector type. collector_type_uid is uniqueidentifier with no default value. To obtain the GUID,
query the dbo.syscollector_collector_types view in the msdb database.
[ @machine_name= ] 'machine_name'
The name of the server that the collection set resides on. machine_name is sysname, with no default value.
[ @named_instance= ] 'named_instance'
The name of the instance for the collection set. named_instance is sysname, with no default value.
[ @log_id = ] log_id
The unique identifier that maps to the collection set event log on the server that collected the data. log_id is bigint
with no default value. To obtain the value for log_id, query the dbo.syscollector_execution_log view in the msdb
database.
[ @snapshot_id = ] snapshot_id
The unique identifier for a row that is inserted into the core.snapshots view. snapshot_id is int and is returned as
OUTPUT.

Return Code Values


0 (success) or 1 (failure)

Remarks
Every time an upload package starts uploading data to the management data warehouse, the data collector run-
time component calls core.sp_create_snapshot.
This procedure checks to see if:
The collection_set_uid matches an existing entry in the core.source_info_internal table.
The collector_type_uid matches an existing entry in the core.supported_collector_types view.
If either of the preceding checks fails, the procedure fails and returns an error.

Permissions
Requires membership in the mdw_writer (with EXECUTE permission) fixed database role.

Examples
The following example creates a snapshot for the Disk Usage collection set, adds it to the management data
warehouse, and returns the snapshot identifier. In the example, the default instance is used.

USE <management_data_warehouse>;
DECLARE @snapshot_id int;
EXEC core.sp_create_snapshot
@collection_set_uid = '7B191952-8ECF-4E12-AEB2-EF646EF79FEF',
@collector_type_uid = '302E93D1-3424-4BE7-AA8E-84813ECF2419',
@machine_name = '<computername>',
@named_instance = 'MSSQLSERVER',
@log_id = 11, -- ID of the log for the collection set
@snapshot_id = @snapshot_id OUTPUT;

See Also
System Stored Procedures (Transact-SQL)
Data Collector Stored Procedures (Transact-SQL)
Management Data Warehouse
core.sp_update_data_source (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Updates an existing row or inserts a new row in the management data warehouse core.source_info_internal table.
This procedure is called by the data collector run-time component every time an upload package starts uploading
data to the management data warehouse.
Transact-SQL Syntax Conventions

Syntax
core.sp_update_data_source [ @collection_set_uid = ] 'collection_set_uid'
,[ @machine_name = ] 'machine_name'
, [ @named_instance = ] 'named_instance'
, [ @days_until_expiration = ] days_until_expiration
, [ @source_id = ] source_id OUTPUT

Arguments
[ @collection_set_uid = ] 'collection_set_uid'
The GUID for the collection set. collection_set_uid is uniqueidentifier, with no default value. To obtain the GUID,
query the dbo.syscollector_collection_sets view in the msdb database.
[ @machine_name = ] 'machine_name'
The name of the server that the collection set resides on. machine_name is sysname with no default value.
[ @named_instance = ] 'named_instance'
The name of the instance for the collection set. named_instance is sysname, with no default value.

NOTE
named_instance must be the fully qualified instance name, which consists of the computer name and the instance name in
the form computername\instancename.

[ @days_until_expiration = ] days_until_expiration
The number of days remaining in the snapshot data retention period. days_until_expiration is smallint.
[ @source_id = ] source_id
The unique identifier for the source of the update. source_id is int and is returned as OUTPUT.

Return Code Values


0 (success) or 1 (failure)

Remarks
Every time an upload package starts uploading data to the management data warehouse, the data collector run-
time component calls core.sp_update_data_source. The core.source_info_internal table is updated if one of the
following changes has happened since the last upload:
A new collection set was added.
The value for days_until_expiration has changed.

Permissions
Requires membership in the mdw_writer (with EXECUTE permission) fixed database role.

Examples
The following example updates the data source (in this case the Disk Usage collection set), sets the number of days
until expiration, and returns the identifier for the source. In the example, the default instance is used.

USE <management_data_warehouse>;
GO
DECLARE @source_id int;
EXEC core.sp_update_data_source
@collection_set_uid = '7B191952-8ECF-4E12-AEB2-EF646EF79FEF',
@machine_name = '<computername>',
@named_instance = 'MSSQLSERVER',
@days_until_expiration = 10,
@source_id = @source_id OUTPUT;

See Also
System Stored Procedures (Transact-SQL)
Data Collector Stored Procedures (Transact-SQL)
Management Data Warehouse
core.sp_add_collector_type (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adds a new entry to the core.supported_collector_types view in the management data warehouse database. The
procedure must be executed in the context of the management data warehouse database.
Transact-SQL Syntax Conventions

Syntax
core.sp_add_collector_type [ @collector_type_uid = ] 'collector_type_uid'

Arguments
[ @collector_type_uid = ] 'collector_type_uid'
The GUID for the collector type. collector_type_uid is uniqueidentifier, with no default value.

Return Code Values


0 (success) or 1 (failure)

Permissions
Requires membership in the mdw_admin (with EXECUTE permission) fixed database role.

Examples
The following example adds the Generic T-SQL Query collector type to the core.supported_collector_types view. By
default, the Generic T-SQL Query collector type already exists. Therefore, if you run this code on a default
installation, you will receive a message that the collector type already exists.
This code would run successfully if you had removed the Generic T-SQL Query collector type by using the
core.sp_remove_collector_type stored procedure, and then wanted to re-add it as a registered collector type that
can upload data to the management data warehouse.

USE <management_data_warehouse>;
GO
DECLARE @RC int;
DECLARE @collector_type_uid uniqueidentifier;
SELECT @collector_type_uid = (SELECT collector_type_uid FROM msdb.dbo.syscollector_collector_types WHERE name
= N'Generic T-SQL Query Collector Type');
EXECUTE @RC = core.sp_add_collector_type @collector_type_uid;

See Also
System Stored Procedures (Transact-SQL)
Data Collector Stored Procedures (Transact-SQL)
Management Data Warehouse
core.sp_remove_collector_type (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes an entry from the core.supported_collector_types view in the management data warehouse database. The
procedure must be executed in the context of the management data warehouse database.
The core.supported_collector_types view shows the registered collector types that can upload data to the
management data warehouse.
Transact-SQL Syntax Conventions

Syntax
core.sp_remove_collector_type [ @collector_type_uid = ] 'collector_type_uid'

Arguments
[ @collector_type_uid = ] 'collector_type_uid'
The GUID for the collector type. collector_type_uid is uniqueidentifier, with no default value.

Return Code Values


0 (success) or 1 (failure)

Permissions
Requires membership in the mdw_admin (with EXECUTE permission) fixed database role.

Examples
The following example removes the Generic T-SQL Query collector type from the core.supported_collector_types
view.

USE <management_data_warehouse>;
GO
DECLARE @RC int;
DECLARE @collector_type_uid uniqueidentifier;
SELECT @collector_type_uid = (SELECT collector_type_uid FROM msdb.dbo.syscollector_collector_types WHERE name
= N'Generic T-SQL Query Collector Type');
EXECUTE @RC = core.sp_remove_collector_type @collector_type_uid;

See Also
System Stored Procedures (Transact-SQL)
Data Collector Stored Procedures (Transact-SQL)
Management Data Warehouse
core.sp_purge_data (Transact-SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes data from the management data warehouse based on a retention policy. This procedure is executed daily
by the mdw_purge_data SQL Server Agent job against the management data warehouse associated with the
specified instance. You can use this stored procedure to perform an on-demand removal of data from the
management data warehouse.
Transact-SQL Syntax Conventions

Syntax
core.sp_purge_data
[ [ @retention_days = ] retention_days ]
[ , [ @instance_name = ] 'instance_name' ]
[ , [ @collection_set_uid = ] 'collection_set_uid' ]
[ , [ @duration = ] duration ]

Arguments
[@retention_days =] retention_days
The number of days to retain data in the management data warehouse tables. Data with a time stamp older than
retention_days is removed. retention_days is smallint, with a default of NULL. If specified, the value must be
positive. When NULL, the value in the valid_through column in the core.snapshots view determines the rows that
are eligible for removal.
[@instance_name = ] 'instance_name'
The name of the instance for the collection set. instance_name is sysname, with a default of NULL.
instance_name must be the fully qualified instance name, which consists of the computer name and the instance
name in the form computername\instancename. When NULL, the default instance on the local server is used.
[@collection_set_uid = ] 'collection_set_uid'
The GUID for the collection set. collection_set_uid is uniqueidentifier, with a default of NULL. When NULL,
qualifying rows from all collection sets are removed. To obtain this value, query the syscollector_collection_sets
catalog view.
[@duration = ] duration
The maximum number of minutes the purge operation should run. duration is smallint, with a default of NULL. If
specified, the value must be zero or a positive integer. When NULL, the operation runs until all qualified rows are
removed or the operation is manually stopped.

Return Code Values


0 (success) or 1 (failure)

Remarks
This procedure selects rows in the core.snapshots view that qualify for removal based on a retention period. All
rows that qualify for removal are deleted from the core.snapshots_internal table. Deleting the preceding rows
triggers a cascading delete action in all of the management data warehouse tables. This is done by using the ON
DELETE CASCADE clause, which is defined for all the tables that store collected data.
Each snapshot and its associated data are deleted within an explicit transaction and then committed. Therefore, if
the purge operation is manually stopped, or the value specified for @duration is exceeded, only the uncommitted
data remains. This data can be removed the next time the job runs.
The procedure must be executed in the context of the management data warehouse database.

Permissions
Requires membership in the mdw_admin (with EXECUTE permission) fixed database role.

Examples
A. Running sp_purge_data with no parameters
The following example executes core.sp_purge_data without specifying any parameters. Therefore, the default
value of NULL is used for all parameters, with the associated behavior.

USE <management_data_warehouse>;
EXECUTE core.sp_purge_data;
GO

B. Specifying retention and duration values


The following example removes data from the management data warehouse that is older than 7 days. In addition,
the @duration parameter is specified so that the operation will run no longer than 5 minutes.

USE <management_data_warehouse>;
EXECUTE core.sp_purge_data @retention_days = 7, @duration = 5;
GO

C. Specifying an instance name and collection set


The following example removes data from the management data warehouse for a given collection set on the
specified instance of SQL Server. Because @retention_days is not specified, the value in the valid_through column
in the core.snapshots view is used to determine the rows for the collection set that are eligible for removal.

USE <management_data_warehouse>;
GO
-- Get the collection set unique identifier for the Disk Usage system collection set.
DECLARE @disk_usage_collection_set_uid uniqueidentifier = (SELECT collection_set_uid
FROM msdb.dbo.syscollector_collection_sets WHERE name = N'Disk Usage');

EXECUTE core.sp_purge_data @instance_name = @@SERVERNAME, @collection_set_uid =


@disk_usage_collection_set_uid;
GO

See Also
System Stored Procedures (Transact-SQL)
Data Collector Stored Procedures (Transact-SQL)
OLE Automation Stored Procedures (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
SQL Server supports the following system stored procedures that allow OLE Automation objects to be used within
a Transact-SQL batch. By default, SQL Server blocks access to OLE Automation stored procedures because this
component is turned off as part of the security configuration for this server. A system administrator can enable
access to OLE Automation procedures by using sp_configure. For more information, see Surface Area
Configuration.

sp_OACreate sp_OAMethod

sp_OADestroy sp_OASetProperty

sp_OAGetErrorInfo sp_OAStop

sp_OAGetProperty Object Hierarchy Syntax (Transact-SQL)

See Also
System Stored Procedures (Transact-SQL)
Ole Automation Procedures Server Configuration Option
Object Hierarchy Syntax (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
The propertyname parameter of sp_OAGetProperty and sp_OASetProperty and the methodname parameter of
sp_OAMethod support an object hierarchy syntax that is similar to that of Microsoft Visual Basic. When this special
syntax is used, these parameters have the following general form.

Syntax
'TraversedObject.PropertyOrMethod'

Arguments
TraversedObject
Is an OLE object in the hierarchy under the objecttoken specified in the stored procedure. Use Visual Basic syntax to
specify a series of collections, object properties, and methods that return objects. Each object specifier in the series
must be separated by a period (.).
An item in the series can be the name of a collection. Use this syntax to specify a collection:
Collection("item")
The double quotation marks (") are required. The Visual Basic exclamation point (!) syntax for collections is not
supported.
PropertyOrMethod
Is the name of a property or method of the TraversedObject.
To specify all index or method parameters by using sp_OAGetProperty, sp_OASetProperty, or sp_OAMethod
parameters (including support for sp_OAMethod output parameters), use the following syntax:
PropertyOrMethod
To specify all index or method parameters inside the parentheses (causing all index or method parameters of
sp_OAGetProperty, sp_OASetProperty, or sp_OAMethod to be ignored) use the following syntax:
PropertyOrMethod( [ ParameterName:= ] "parameter" [ , ... ] )
The double quotation marks (") are required. All named parameters must be specified after all positional
parameters are specified.

Remarks
If TraversedObject is not specified, PropertyOrMethod is required.
If PropertyOrMethod is not specified, the TraversedObject is returned as an object token output parameter from the
OLE Automation stored procedure. If PropertyOrMethod is specified, the property or method of the
TraversedObject is called, and the property value or method return value is returned as an output parameter from
the OLE Automation stored procedure.
If any item in the TraversedObject list does not return an OLE object, an error is raised.
For more information about Visual Basic OLE object syntax, see the Visual Basic documentation.
For more information about HRESULT Return Codes, see sp_OACreate (Transact-SQL).

Examples
The following are examples of object hierarchy syntax that use a SQL-DMO SQLServer object.

-- Get the AdventureWorks2012 Person.Address Table object.


EXEC @hr = sp_OAGetProperty @object,
'Databases("AdventureWorks2012").Tables("Person.Address")',
@table OUT

-- Get the Rows property of the AdventureWorks2012 Person.Address table.


EXEC @hr = sp_OAGetProperty @object,
'Databases("AdventureWorks2012").Tables("Person.Address").Rows',
@rows OUT

-- Call the CheckTable method to validate the


-- AdventureWorks2012 Person.Address table.
EXEC @hr = sp_OAMethod @object,
'Databases("AdventureWorks2012").Tables("Person.Address").CheckTable',
@checkoutput OUT

See Also
OLE Automation Sample Script
OLE Automation Stored Procedures (Transact-SQL)
sp_OACreate (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates an instance of an OLE object.
Transact-SQL Syntax Conventions

Syntax
sp_OACreate { progid | clsid } , objecttoken OUTPUT [ , context ]

Arguments
progid
Is the programmatic identifier (ProgID) of the OLE object to create. This character string describes the class of the
OLE object and has the form: 'OLEComponent.Object'
OLEComponent is the component name of the OLE Automation server, and Object is the name of the OLE object.
The specified OLE object must be valid and must support the IDispatch interface.
For example, SQLDMO.SQLServer is the ProgID of the SQL-DMO SQLServer object. SQL-DMO has a component
name of SQLDMO, the SQLServer object is valid, and (like all SQL-DMO objects) the SQLServer object supports
IDispatch.
clsid
Is the class identifier (CLSID) of the OLE object to create. This character string describes the class of the OLE object
and has the form: '{nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn}'. The specified OLE object must be valid and
must support the IDispatch interface.
For example, {00026BA1-0000-0000-C000-000000000046} is the CLSID of the SQL-DMO SQLServer object.
objecttoken OUTPUT
Is the returned object token, and must be a local variable of data type int. This object token identifies the created
OLE object and is used in calls to the other OLE Automation stored procedures.
context
Specifies the execution context in which the newly created OLE object runs. If specified, this value must be one of
the following:
1 = In-process (.dll) OLE server only.
4 = Local (.exe) OLE server only.
5 = Both in-process and local OLE server allowed
If not specified, the default value is 5. This value is passed as the dwClsContext parameter of the call to
CoCreateInstance.
If an in-process OLE server is allowed (by using a context value of 1 or 5 or by not specifying a context value), it has
access to memory and other resources owned by SQL Server. An in-process OLE server may damage SQL Server
memory or resources and cause unpredictable results, such as a SQL Server access violation.
When you specify a context value of 4, a local OLE server does not have access to any SQL Server resources, and it
cannot damage SQL Server memory or resources.

NOTE
The parameters for this stored procedure are specified by position, not by name.

Return Code Values


0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation
object.
For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

Remarks
If OLE automation procedures are enabled, a call to sp_OACreate will start the OLE Automation shared execution
environment. For more information about enabling OLE automation, see Ole Automation Procedures Server
Configuration Option.
The created OLE object is automatically destroyed at the end of the Transact-SQL statement batch.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
A. Using ProgID
The following example creates a SQL-DMO SQLServer object by using its ProgID.

DECLARE @object int;


DECLARE @hr int;
DECLARE @src varchar(255), @desc varchar(255);
EXEC @hr = sp_OACreate 'SQLDMO.SQLServer', @object OUT;
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object, @src OUT, @desc OUT
raiserror('Error Creating COM Component 0x%x, %s, %s',16,1, @hr, @src, @desc)
RETURN
END;
GO

B. Using CLSID
The following example creates a SQL-DMO SQLServer object by using its CLSID.
DECLARE @object int;
DECLARE @hr int;
DECLARE @src varchar(255), @desc varchar(255);
EXEC @hr = sp_OACreate '{00026BA1-0000-0000-C000-000000000046}',
@object OUT;
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object, @src OUT, @desc OUT
raiserror('Error Creating COM Component 0x%x, %s, %s',16,1, @hr, @src, @desc)
RETURN
END;
GO

See Also
OLE Automation Stored Procedures (Transact-SQL)
Ole Automation Procedures Server Configuration Option
OLE Automation Sample Script
sp_OADestroy (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Destroys a created OLE object.
Transact-SQL Syntax Conventions

Syntax
sp_OADestroy objecttoken

Arguments
objecttoken
Is the object token of an OLE object that was previously created by using sp_OACreate.

Return Code Values


0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation
object.
For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

Remarks
If sp_OADestroy is not called, the created OLE object is automatically destroyed at the end of the batch.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example destroys the previously created SQLServer object.

EXEC @hr = sp_OADestroy @object;


IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object
RETURN
END;

See Also
OLE Automation Stored Procedures (Transact-SQL)
OLE Automation Sample Script
sp_OAGetErrorInfo (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Obtains OLE Automation error information.
Transact-SQL Syntax Conventions

Syntax
sp_OAGetErrorInfo [ objecttoken ]
[ , source OUTPUT ]
[ , description OUTPUT ]
[ , helpfile OUTPUT ]
[ , helpid OUTPUT ]

Arguments
objecttoken
Is either the object token of an OLE object that was previously created by using sp_OACreate or it is NULL. If
objecttoken is specified, error information for that object is returned. If NULL is specified, the error information for
the entire batch is returned.
source OUTPUT
Is the source of the error information. If specified, it must be a local char, nchar, varchar, or nvarchar variable.
The return value is truncated to fit the local variable if necessary.
description OUTPUT
Is the description of the error. If specified, it must be a local char, nchar, varchar, or nvarchar variable. The return
value is truncated to fit the local variable if necessary.
helpfile OUTPUT
Is the help file for the OLE object. If specified, it must be a local char, nchar, varchar, or nvarchar variable. The
return value is truncated to fit the local variable if necessary.
helpid OUTPUT
Is the help file context ID. If specified, it must be a local int variable.

NOTE
The parameters for this stored procedure are specified by position, not name.

Return Code Values


0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation
object.
For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.
Result Sets
If no output parameters are specified, the error information is returned to the client as a result set.

COLUMN NAMES DATA TYPE DESCRIPTION

Error binary(4) Binary representation of the error


number.

Source nvarchar(nn) Source of the error.

Description nvarchar(nn) Description of the error.

Helpfile nvarchar(nn) Help file for the source.

HelpID int Help context ID in the Help source file.

Remarks
Each call to an OLE Automation stored procedure (except sp_OAGetErrorInfo) resets the error information;
therefore, sp_OAGetErrorInfo obtains error information only for the most recent OLE Automation stored
procedure call. Note that because sp_OAGetErrorInfo does not reset the error information, it can be called
multiple times to get the same error information.
The following table lists OLE Automation errors and their common causes.

ERROR AND HRESULT COMMON CAUSE

Bad variable type (0x80020008) Data type of a Transact-SQL value passed as a method
parameter did not match the Microsoft Visual Basic data type
of the method parameter, or a NULL value was passed as a
method parameter.

Unknown name (0x8002006) Specified property or method name was not found for the
specified object.

Invalid class string (0x800401f3) Specified ProgID or CLSID is not registered as an OLE object
on an instance of SQL Server. Custom OLE automation servers
must be registered before they can be instantiated using
sp_OACreate. This can be done by using the Regsvr32.exe
utility for in-process (.dll) servers, or the /REGSERVER
command-line switch for local (.exe) servers.

Server execution failed (0x80080005) Specified OLE object is registered as a local OLE server (.exe
file) but the .exe file could not be found or started.

The specified module could not be found (0x8007007e) Specified OLE object is registered as an in-process OLE server
(.dll file), but the .dll file could not be found or loaded.

Type mismatch (0x80020005) Data type of a Transact-SQL local variable that is used to store
a returned property value or a method return value did not
match the Visual Basic data type of the property or method
return value. Or, the return value of a property or a method
was requested, but it does not return a value.
ERROR AND HRESULT COMMON CAUSE

Datatype or value of the 'context' parameter of The value of the context parameter should be one of: 1, 4, or
sp_OACreate is invalid. (0x8004275B) 5.

For more information about processing HRESULT Return Codes, see OLE Automation Return Codes and Error
Information.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example displays OLE Automation error information.

DECLARE @output varchar(255);


DECLARE @hr int;
DECLARE @source varchar(255);
DECLARE @description varchar(255);
PRINT 'OLE Automation Error Information';
EXEC @hr = sp_OAGetErrorInfo @object, @source OUT, @description OUT;
IF @hr = 0
BEGIN
SELECT @output = ' Source: ' + @source
PRINT @output
SELECT @output = ' Description: ' + @description
PRINT @output
END
ELSE
BEGIN
PRINT ' sp_OAGetErrorInfo failed.'
RETURN
END;

See Also
OLE Automation Stored Procedures (Transact-SQL)
OLE Automation Sample Script
sp_OAGetProperty (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Gets a property value of an OLE object.
Transact-SQL Syntax Conventions

Syntax
sp_OAGetProperty objecttoken , propertyname
[ , propertyvalue OUTPUT ]
[ , index...]

Arguments
objecttoken
Is the object token of an OLE object that was previously created by using sp_OACreate.
propertyname
Is the property name of the OLE object to return.
propertyvalue OUTPUT
Is the returned property value. If specified, it must be a local variable of the appropriate data type.
If the property returns an OLE object, propertyvalue must be a local variable of data type int. An object token is
stored in the local variable, and this object token can be used with other OLE Automation stored procedures.
If the property returns a single value, either specify a local variable for propertyvalue, which returns the property
value in the local variable; or do not specify propertyvalue, which returns the property value to the client as a
single-column, single-row result set.
When the property returns an array, if propertyvalue is specified, it is set to NULL.
If propertyvalue is specified, but the property does not return a value, an error occurs. If the property returns an
array with more than two dimensions, an error occurs.
index
Is an index parameter. If specified, index must be a value of the appropriate data type.
Some properties have parameters. These properties are called indexed properties, and the parameters are called
index parameters. A property can have multiple index parameters.

NOTE
The parameters for this stored procedure are specified by position, not name.

Return Code Values


0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation
object.
For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

Result Sets
If the property returns an array with one or two dimensions, the array is returned to the client as a result set:
A one-dimensional array is returned to the client as a single-row result set with as many columns as there
are elements in the array. In other words, the array is returned as columns.
A two-dimensional array is returned to the client as a result set with as many columns as there are elements
in the first dimension of the array and with as many rows as there are elements in the second dimension of
the array. In other words, the array is returned as (columns, rows).
When a property return value or method return value is an array, sp_OAGetProperty or sp_OAMethod
returns a result set to the client. (Method output parameters cannot be arrays.) These procedures scan all the
data values in the array to determine the appropriate SQL Server data types and data lengths to use for each
column in the result set. For a particular column, these procedures use the data type and length required to
represent all data values in that column.
When all data values in a column share the same data type, that data type is used for the whole column.
When data values in a column are of different data types, the data type of the whole column is chosen based
on the following chart.

INT FLOAT MONEY DATETIME VARCHAR NVARCHAR

int int float money varchar varchar nvarchar

float float float money varchar varchar nvarchar

money money money money varchar varchar nvarchar

datetime varchar varchar varchar datetime varchar nvarchar

varchar varchar varchar varchar varchar varchar nvarchar

nvarchar nvarchar nvarchar nvarchar nvarchar nvarchar nvarchar

Remarks
You can also use sp_OAMethod to get a property value.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
A. Using a local variable
The following example gets the HostName property (of the previously created SQLServer object) and stores it in a
local variable.
DECLARE @property varchar(255);
EXEC @hr = sp_OAGetProperty @object, 'HostName', @property OUT;
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object
RETURN
END
PRINT @property;

B. Using a result set


The following example gets the HostName property (of the previously created SQLServer object) and returns it to
the client as a result set.

EXEC @hr = sp_OAGetProperty @object, 'HostName';


IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object
RETURN
END;

See Also
OLE Automation Stored Procedures (Transact-SQL)
OLE Automation Sample Script
sp_OAMethod (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Calls a method of an OLE object.
Transact-SQL Syntax Conventions

Syntax
sp_OAMethod objecttoken , methodname
[ , returnvalue OUTPUT ]
[ , [ @parametername = ] parameter [ OUTPUT ] [ ...n ] ]

Arguments
objecttoken
Is the object token of an OLE object that was previously created by using sp_OACreate.
methodname
Is the method name of the OLE object to call.
returnvalue OUTPUT
Is the return value of the method of the OLE object. If specified, it must be a local variable of the appropriate data
type.
If the method returns a single value, either specify a local variable for returnvalue, which returns the method return
value in the local variable, or do not specify returnvalue, which returns the method return value to the client as a
single-column, single-row result set.
If the method return value is an OLE object, returnvalue must be a local variable of data type int. An object token is
stored in the local variable, and this object token can be used with other OLE Automation stored procedures.
When the method return value is an array, if returnvalue is specified, it is set to NULL.
An error is raised when any one of the following occurs:
returnvalue is specified, but the method does not return a value.
The method returns an array with more than two dimensions.
The method returns an array as an output parameter.
[ @parametername= ] parameter[ OUTPUT ]
Is a method parameter. If specified, parameter must be a value of the appropriate data type.
To obtain the return value of an output parameter, parameter must be a local variable of the appropriate
data type, and OUTPUT must be specified. If a constant parameter is specified, or if OUTPUT is not
specified, any return value from an output parameter is ignored.
If specified, parametername must be the name of the Microsoft Visual Basic named parameter. Note that
@parameternameis not a Transact-SQL local variable. The at sign (@) is removed, and parameternameis
passed to the OLE object as the parameter name. All named parameters must be specified after all positional
parameters are specified.
n
Is a placeholder indicating that multiple parameters can be specified.

NOTE
@parametername can be a named parameter because it is part of the specified method and is passed through to the object.
The other parameters for this stored procedure are specified by position, not name.

Return Code Values


0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation
object.
For more information about HRESULT Return Codes, OLE Automation Return Codes and Error Information.

Result Sets
If the method return value is an array with one or two dimensions, the array is returned to the client as a result set:
A one-dimensional array is returned to the client as a single-row result set with as many columns as there
are elements in the array. In other words, the array is returned as (columns).
A two-dimensional array is returned to the client as a result set with as many columns as there are elements
in the first dimension of the array and with as many rows as there are elements in the second dimension of
the array. In other words, the array is returned as (columns, rows).
When a property return value or method return value is an array, sp_OAGetProperty or sp_OAMethod
returns a result set to the client. (Method output parameters cannot be arrays.) These procedures scan all the
data values in the array to determine the appropriate SQL Server data types and data lengths to use for each
column in the result set. For a particular column, these procedures use the data type and length required to
represent all data values in that column.
When all data values in a column share the same data type, that data type is used for the whole column.
When data values in a column are of different data types, the data type of the whole column is chosen based
on the following chart.

INT FLOAT MONEY DATETIME VARCHAR NVARCHAR

int int float money varchar varchar nvarchar

float float float money varchar varchar nvarchar

money money money money varchar varchar nvarchar

datetime varchar varchar varchar datetime varchar nvarchar

varchar varchar varchar varchar varchar varchar nvarchar

nvarchar nvarchar nvarchar nvarchar nvarchar nvarchar nvarchar

Remarks
You can also use sp_OAMethod to get a property value.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
A. Calling a method
The following example calls the Connect method of the previously created SQLServer object.

EXEC @hr = sp_OAMethod @object, 'Connect', NULL, 'my_server',


'my_login', 'my_password';
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object
RETURN
END;

B. Getting a property
The following example gets the HostName property (of the previously created SQLServer object) and stores it in a
local variable.

DECLARE @property varchar(255);


EXEC @hr = sp_OAMethod @object, 'HostName', @property OUT;
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object
RETURN
END;
PRINT @property;

See Also
OLE Automation Stored Procedures (Transact-SQL)
OLE Automation Sample Script
sp_OASetProperty (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Sets a property of an OLE object to a new value.
Transact-SQL Syntax Conventions

Syntax
sp_OASetProperty objecttoken , propertyname , newvalue [ , index... ]

Arguments
objecttoken
Is the object token of an OLE object that was previously created by sp_OACreate.
propertyname
Is the property name of the OLE object to set to a new value.
newvalue
Is the new value of the property, and must be a value of the appropriate data type.
index
Is an index parameter. If specified, index must be a value of the appropriate data type.
Some properties have parameters. These properties are called indexed properties, and the parameters are called
index parameters. A property can have multiple index parameters.

NOTE
The parameters for this stored procedure are specified by position, not name.

Return Code Values


0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation
object.
For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example sets the HostName property (of the previously created SQLServer object) to a new value.
EXEC @hr = sp_OASetProperty @object, 'HostName', 'Gizmo';
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object
RETURN
END'

See Also
OLE Automation Stored Procedures (Transact-SQL)
OLE Automation Sample Script
sp_OAStop (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Stops the server-wide OLE Automation stored procedure execution environment.
Transact-SQL Syntax Conventions

Syntax
sp_OAStop

Return Code Values


0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation
object.
For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

Remarks
A single execution environment is shared by all clients that are using the OLE Automation stored procedures. If one
client calls sp_OAStop the shared execution environment will be stopped for all clients. After the execution
environment has been stopped, any call to sp_OACreate restarts the execution environment.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example stops the shared OLE Automation execution environment.

EXEC sp_OAStop;
GO

See Also
OLE Automation Stored Procedures (Transact-SQL)
OLE Automation Sample Script
Policy-Based Management Stored Procedures
(Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
SQL Server supports the following system stored procedures that are used for Policy-Based Management.

IMPORTANT
Only the Policy-Based Management stored procedures that are documented in SQL Server Books Online are supported.
Undocumented stored procedures are used by internal Policy-Based Management components and should not be used to
administer Policy-Based Management.

sp_syspolicy_add_policy_category sp_syspolicy_rename_policy_category

sp_syspolicy_add_policy_category_subscription sp_syspolicy_repair_policy_automation

sp_syspolicy_configure sp_syspolicy_set_config_enabled

sp_syspolicy_delete_policy_category sp_syspolicy_set_config_history_retention

sp_syspolicy_delete_policy_category_subscription sp_syspolicy_set_log_on_success

sp_syspolicy_delete_policy_execution_history sp_syspolicy_subscribe_to_policy_category

sp_syspolicy_purge_health_state sp_syspolicy_unsubscribe_from_policy_category

sp_syspolicy_purge_history sp_syspolicy_update_policy_category

sp_syspolicy_rename_condition sp_syspolicy_update_policy_category_subscription

sp_syspolicy_rename_policy

See Also
Administer Servers by Using Policy-Based Management
sp_syspolicy_add_policy_category (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a policy category that can be used with Policy-Based Management. Policy categories enable you to organize
policies, and to set policy scope.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_add_policy_category [ @name = ] 'name'
[ , [ @mandate_database_subscriptions = ] mandate_database_subscriptions ]
, [ @policy_category_id = ] policy_category_id OUTPUT

Arguments
[ @name= ] 'name'
Is the name of the policy category. name is sysname, and is required. name cannot be NULL or an empty string.
[ @mandate_database_subscriptions = ] mandate_database_subscriptions
Determines whether database subscription is mandated for the policy category. mandate_database_subscriptions
is a bit value, with a default of 1 (enabled).
[ @policy_category_id= ] policy_category_id
Is the identifier for the policy category. policy_category_id is int, and is returned as OUTPUT.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_add_policy_category in the context of the msdb system database.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.
Examples
The following example creates a policy category where subscription to the category is not mandated. This means
that individual databases can be configured to opt in or opt out of policies in the category.

DECLARE @policy_category_id int;

EXEC msdb.dbo.sp_syspolicy_add_policy_category
@name = N'Table Naming Policies'
, @mandate_database_subscriptions = 0
, @policy_category_id = @policy_category_id OUTPUT;

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_add_policy_category_subscription (Transact-SQL)
sp_syspolicy_delete_policy_category (Transact-SQL)
sp_syspolicy_add_policy_category_subscription
(Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a policy category subscription to the specified database.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_add_policy_category_subscription [ @target_type = ] 'target_type'
, [ @target_object = ] 'target_object'
, [ @policy_category = ] 'policy_category'
[ , [ @policy_category_subscription_id = ] policy_category_subscription_id OUTPUT ]

Arguments
[ @target_type= ] 'target_type'
Is the target type of the category subscription. target_type is sysname, is required, and must be set to 'DATABASE'.
[ @target_object= ] 'target_object'
Is the name of the database that will subscribe to the category. target_object is sysname, and is required.
[ @policy_category= ] 'policy_category'
Is the name of the policy category to subscribe to. policy_category is sysname, and is required.
To obtain values for policy_category, query the msdb.dbo.syspolicy_policy_categories system view.
[ @policy_category_subscription_id= ] policy_category_subscription_id
Is the identifier for the category subscription. policy_category_subscription_id is int, and is returned as OUTPUT.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_add_policy_category_subscription in the context of the msdb system database.
If you specify a policy category that does not exist, a new policy category is created and the subscription is
mandated for all databases when you execute the stored procedure. If you then clear the mandated subscription
for the new category, the subscription will only apply for the database that you specified as the target_object. For
more information about how to change a mandated subscription setting, see sp_syspolicy_update_policy_category
(Transact-SQL).

Permissions
This stored procedure runs in the context of the current owner of the stored procedure.
Examples
The following example configures the specified database to subscribe to a policy category that is named 'Table
Naming Policies'.

EXEC msdb.dbo.sp_syspolicy_add_policy_category_subscription @target_type = N'DATABASE'


, @target_object = N'AdventureWorks2012'
, @policy_category = N'Table Naming Policies';

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_update_policy_category_subscription (Transact-SQL)
sp_syspolicy_unsubscribe_from_policy_category (Transact-SQL)
sp_syspolicy_configure (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Configures settings for Policy-Based Management, such as whether Policy-Based Management is enabled.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_configure [ @name = ] 'name'
, [ @value = ] value

Arguments
[ @name = ] 'name'
Is the name of the setting that you want to configure. name is sysname, is required, and cannot be NULL or an
empty string.
name can be any of the following values:
'Enabled' - Determines whether Policy-Based Management is enabled.
'HistoryRetentionInDays' - Specifies the number of days that policy evaluation history should be retained. If
set to 0, the history will not be automatically removed.
'LogOnSuccess' - Specifies whether Policy-Based Management logs successful policy evaluations.
[ @value = ] value
Is the value that is associated with the specified value for name. value is sql_variant, and is required.
If you specify 'Enabled' for name, you can use either of the following values:
0 = Disables Policy-Based Management.
1 = Enables Policy-Based Management.
If you specify 'HistoryRententionInDays' for name, specify the number of days as an integer value.
If you specify 'LogOnSuccess' for name, you can use either of the following values:
0 = Logs only failed policy evaluations.
1 = Logs both successful and failed policy evaluations.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_configure in the context of the msdb system database.
To view current values for these settings, query the msdb.dbo.syspolicy_configuration system view.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.

Examples
The following example enables Policy-Based Management.

EXEC msdb.dbo.sp_syspolicy_configure @name = N'Enabled'


, @value = 1;

GO

The following example sets the policy history retention to 14 days.

EXEC msdb.dbo.sp_syspolicy_configure @name = N'HistoryRetentionInDays'


, @value = 14;

GO

The following example configures Policy-Based Management to log both successful and failed policy evaluations.

EXEC msdb.dbo.sp_syspolicy_configure @name = N'LogOnSuccess'


, @value = 1;

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_set_config_enabled (Transact-SQL)
sp_syspolicy_set_config_history_retention (Transact-SQL)
sp_syspolicy_set_log_on_success (Transact-SQL)
sp_syspolicy_delete_policy_category (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes a policy category in Policy-Based Management.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_delete_policy_category { [ @name = ] 'name' | [ @policy_category_id = ] policy_category_id }

Arguments
[ @name= ] 'name'
Is the name of the policy category. name is sysname, and must be specified if policy_category_id is NULL.
[ @policy_category_id= ] policy_category_id
Is the identifier for the policy category. policy_category_id is int, and must be specified if name is NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_delete_policy_category in the context of the msdb system database.
You must specify a value for name or for policy_category_id. Both cannot be NULL. To obtain these values, query
the msdb.dbo.syspolicy_policy_categories system view.
To delete a policy category, the category must not be referenced by any policies.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.

Examples
The following example deletes a policy category that is named 'Finance'.
EXEC msdb.dbo.sp_syspolicy_delete_policy_category @name = N'Finance';

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_add_policy_category (Transact-SQL)
sp_syspolicy_update_policy_category (Transact-SQL)
sp_syspolicy_delete_policy_category_subscription
(Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes a policy category subscription for a specific database.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_delete_policy_category_subscription [ @policy_category_subscription_id = ]
policy_category_subscription_id

Arguments
[ @policy_category_subscription_id= ] policy_category_subscription_id
Is the identifier for the policy category subscription. policy_category_subscription_id is int.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_delete_policy_category_subscription in the context of the msdb system database.
You cannot delete a policy category subscription when the subscription is mandated.

Permissions
This stored procedure runs in the context of the current owner of the stored procedure.
To obtain values for policy_category_subscription_id, you can use the following query:

SELECT a.policy_category_subscription_id, a.target_object, b.name AS category_name


FROM msdb.dbo.syspolicy_policy_category_subscriptions AS a
INNER JOIN msdb.dbo.syspolicy_policy_categories AS b
ON a.policy_category_id = b.policy_category_id;

Examples
The following example deletes a policy category subscription with an ID of 1.
EXEC msdb.dbo.sp_syspolicy_delete_policy_category_subscription @policy_category_subscription_id = 1;

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_update_policy_category_subscription (Transact-SQL)
sp_syspolicy_delete_policy_execution_history
(Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes execution history for policies in Policy-Based Management. You can use this stored procedure to delete
execution history for a specific policy or for all policies, and to delete execution history before a specific date.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_delete_policy_execution_history [ @policy_id = ] policy_id ]
[ , [ @oldest_date = ] 'oldest_date' ]

Arguments
[ @policy_id= ] policy_id
Is the identifier of the policy for which you want to delete the execution history. policy_id is int, and is required. Can
be NULL.
[ @oldest_date= ] 'oldest_date'
Is the oldest date for which you want to keep policy execution history. Any execution history earlier than this date is
deleted. oldest_date is datetime, and is required. Can be NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_delete_policy_execution_history in the context of the msdb system database.
To obtain values for policy_id, and to view execution history dates, you can use the following query:

SELECT a.name AS N'policy_name', b.policy_id, b.start_date, b.end_date


FROM msdb.dbo.syspolicy_policies AS a
INNER JOIN msdb.dbo.syspolicy_policy_execution_history AS b
ON a.policy_id = b.policy_id

The following behavior applies if you specify NULL for one or both values:
To delete all policy execution history, specify NULL for both policy_id and for oldest_date.
To delete all policy execution history for a specific policy, specify a policy identifier for policy_id, and specify
NULL as oldest_date.
To delete policy execution history for all policies before a specific date, specify NULL for policy_id, and
specify a date for oldest_date.
To archive policy execution history, you can open the Policy History log in Object Explorer and export the
execution history to a file. To access the Policy History log, expand Management, right-click Policy
Management, and then click View History.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.

Examples
The following example deletes policy execution history before a specific date for a policy with an ID of 7.

EXEC msdb.dbo.sp_syspolicy_delete_policy_execution_history @policy_id = 7


, @oldest_date = '2009-02-16 16:00:00.000';

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_set_config_history_retention (Transact-SQL)
sp_syspolicy_purge_history (Transact-SQL)
sp_syspolicy_purge_health_state (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes the policy health states in Policy-Based Management. Policy health states are visual indicators (a scroll
symbol with a red "X") within Object Explorer that enable you to determine which nodes have failed a policy
evaluation.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_purge_health_state [ @target_tree_root_with_id = ] 'target_tree_root_with_id'

Arguments
[ @target_tree_root_with_id = ] 'target_tree_root_with_id'
Represents the node in Object Explorer where you want to clear the health state. target_tree_root_with_id is
nvarchar(400), with a default of NULL.
You can specify values from the target_query_expression_with_id column of the
msdb.dbo.syspolicy_system_health_state system view.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_purge_health_state in the context of the msdb system database.
If you run this stored procedure without any parameters, the system health state is deleted for all nodes in Object
Explorer.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.

Examples
The following example deletes the health states for a specific node in Object Explorer.

EXEC msdb.dbo.sp_syspolicy_purge_health_state @target_tree_root_with_id = 'Server/Database[@ID=7]';

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_purge_history (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the policy evaluation history according to the history retention interval setting.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_purge_history

Arguments
This stored procedure has no parameters.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_purge_history in the context of the msdb system database.
To view the history retention interval, you can use the following query:

SELECT current_value
FROM msdb.dbo.syspolicy_configuration
WHERE name = N'HistoryRetentionInDays';
GO

NOTE
If the history retention interval is set to 0, policy evaluation history will not be removed.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.
Examples
The following example removes the policy evaluation history.

EXEC msdb.dbo.sp_syspolicy_purge_history;

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_set_config_history_retention (Transact-SQL)
sp_syspolicy_delete_policy_execution_history (Transact-SQL)
sp_syspolicy_rename_condition (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Renames an existing condition in Policy-Based Management.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_rename_condition { [ @name = ] 'name' | [ @condition_id = ] condition_id }
, [ @new_name = ] 'new_name'

Arguments
[ @name= ] 'name'
Is the name of the condition that you want to rename. name is sysname, and must be specified if condition_id is
NULL.
[ @condition_id= ] condition_id
Is the identifier for the condition that you want to rename. condition_id is int, and must be specified if name is
NULL.
[ @new_name= ] 'new_name'
Is the new name of the condition. new_name is sysname, and is required. Cannot be NULL or an empty string.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_rename_condition in the context of the msdb system database.
You must specify a value for either name or condition_id. Both cannot be NULL. To obtain these values, query the
msdb.dbo.syspolicy_conditions system view.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.
Examples
The following example renames a condition that is named 'Change Tracking Enabled'.

EXEC msdb.dbo.sp_syspolicy_rename_condition @name = N'Change Tracking Enabled'


, @new_name = N'Verify Change Tracking Enabled';

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_rename_policy (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Renames an existing policy in Policy-Based Management.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_rename_policy { [ @name = ] 'name' | [ @policy_id = ] policy_id }
, [ @new_name = ] 'new_name'

Arguments
[ @name= ] 'name'
Is the name of the policy that you want to rename. name is sysname, and must be specified if policy_id is NULL.
[ @policy_id= ] policy_id
Is the identifier for the policy that you want to rename. policy_id is int, and must be specified if name is NULL.
[ @new_name= ] 'new_name'
Is the new name for the policy. new_name is sysname, and is required. Cannot be NULL or an empty string.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_rename_policy in the context of the msdb system database.
You must specify a value for either name or policy_id. Both cannot be NULL. To obtain these values, query the
msdb.dbo.syspolicy_policies system view.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.
Examples
The following example renames a policy that is named 'Test Policy 1' to 'Test Policy 2'.

EXEC msdb.dbo.sp_syspolicy_rename_policy @name = N'Test Policy 1'


, @new_name = N'Test Policy 2';

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_rename_policy_category (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Renames an existing policy category in Policy-Based Management.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_rename_policy_category { [ @name = ] 'name' | [ @policy_category_id = ] policy_category_id }
, [ @new_name = ] 'new_name'

Arguments
[ @name = ] 'name'
Is the name of the policy category that you want to rename. name is sysname, and must be specified if
policy_category_id is NULL.
[ @policy_category_id= ] policy_category_id
Is the identifier for the policy category that you want to rename. policy_category_id is int, and must be specified if
name is NULL.
[ @new_name= ] 'new_name'
Is the new name for the policy category. new_name is sysname, and is required. Cannot be NULL or an empty
string.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_rename_policy_category in the context of the msdb system database.
You must specify a value for either name or policy_category_id. Both cannot be NULL. To obtain these values,
query the msdb.dbo.syspolicy_policy_categories system view.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.
IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.

Examples
The following example renames a policy category that is named 'Test Category 1' to 'Test Category 2'.

EXEC msdb.dbo.sp_syspolicy_rename_policy_category @name = N'Test Category 1'


, @new_name = N'Test Category 2';

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_add_policy_category (Transact-SQL)
sp_syspolicy_delete_policy_category (Transact-SQL)
sp_syspolicy_update_policy_category (Transact-SQL)
sp_syspolicy_repair_policy_automation (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Repairs policy automation in Policy-Based Management. For example, you can use this stored procedure to repair
triggers and jobs that are associated with policies that are configured to use "On schedule" or "On change"
evaluation modes.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_repair_policy_automation

Arguments
This stored procedure has no parameters.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_repair_policy_automation in the context of the msdb system database.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.

Examples
The following example repairs policy automation.

EXEC msdb.dbo.sp_syspolicy_repair_policy_automation;

GO
See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_set_config_enabled (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Enables or disables Policy-Based Management.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_set_config_enabled [ @value = ] value

Arguments
[ @value= ] value
Determines whether Policy-Based Management is enabled. value is sqlvariant, and can be one of the following
values:
0 (or 'false') = Disabled
1 (or 'true') = Enabled

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_set_config_enabled in the context of the msdb system database.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.

Examples
The following example enables Policy-Based Management.
EXEC msdb.dbo.sp_syspolicy_set_config_enabled @value = 1;

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_configure (Transact-SQL)
sp_syspolicy_set_config_history_retention (Transact-
SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Specifies the number of days to keep policy evaluation history for Policy-Based Management.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_set_config_history_retention [ @value = ] value

Arguments
[ @value= ] value
Is the number of days to retain Policy-Based Management history. value is sqlvariant.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_set_config_history_retention in the context of the msdb system database.
If value is set to 0, the history will not be automatically removed.
To view the current value for history retention, run the following query:

SELECT current_value FROM msdb.dbo.syspolicy_configuration


WHERE name = 'HistoryRetentionInDays'

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.
Examples
The following example sets the policy evaluation history retention to 28 days.

EXEC msdb.dbo.sp_syspolicy_set_config_history_retention @value = 28;

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_configure (Transact-SQL)
sp_syspolicy_set_log_on_success (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Specifies whether successful policy evaluations are logged in the Policy History log for Policy-Based Management.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_set_log_on_success [ @value = ] value

Arguments
[ @value= ] value
Determines whether successful policy evaluations are logged. value is sqlvariant, and can be one of the following
values:
0 or 'false' = Successful policy evaluations are not logged.
1 or 'true' = Successful policy evaluations are logged.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_set_log_on_success in the context of the msdb system database.
When value is set to 0 or to 'false', only failed policy evaluations are logged.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT!! Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server
triggers and schedule policy executions that can affect the operation of the instance of the Database Engine.
For example, users in the PolicyAdministratorRole role can create a policy that can prevent most objects from
being created in the Database Engine. Because of this possible elevation of credentials, the
PolicyAdministratorRole role should be granted only to users who are trusted with controlling the
configuration of the Database Engine.

Examples
The following example enables the logging of successful policy evaluations.
EXEC msdb.dbo.sp_syspolicy_set_log_on_success @value = 1;

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_configure (Transact-SQL)
sp_syspolicy_subscribe_to_policy_category (Transact-
SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adds a policy category subscription for the specified database.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_subscribe_to_policy_category [ @policy_category = ] 'policy_category'

Arguments
[ @policy_category= ] 'policy_category'
Is the name of the policy category that you want the database to subscribe to. policy_category is sysname, and is
required.
To obtain values for policy_category, query the msdb.dbo.syspolicy_policy_categories system view.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_subscribe_to_policy_category in the context of the database where you want to add a
policy category subscription.

Permissions
Requires membership in the db_owner fixed database role.

Examples
The following example adds a subscription to the 'Finance' policy category for the specified database.

USE <database_name>;

EXEC sys.sp_syspolicy_subscribe_to_policy_category @policy_category = N'Finance';

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_unsubscribe_from_policy_category (Transact-SQL)
sp_syspolicy_unsubscribe_from_policy_category
(Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes a policy category subscription for the current database.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_unsubscribe_from_policy_category [ @policy_category = ] 'policy_category'

Arguments
[ @policy_category= ] 'policy_category'
Is the name of the policy category subscription that you want to delete. policy_category is sysname, and is
required.
To obtain values for policy_category, query the msdb.dbo.syspolicy_policy_categories system view.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_unsubscribe_from_policy_category in the context of the database where you want to
remove a policy category subscription.

Permissions
Requires membership in the db_owner fixed database role.

Examples
The following example deletes a subscription to the 'Finance' policy category for the specified database.

USE <database_name>;

EXEC sys.sp_syspolicy_unsubscribe_from_policy_category @policy_category = N'Finance';

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_subscribe_to_policy_category (Transact-SQL)
sp_syspolicy_update_policy_category (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates whether a policy category is set to mandate database subscriptions. If subscription is mandated, the
policy category applies to all databases.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_update_policy_category { [ @name = ] 'name' | [ @policy_category_id = ] policy_category_id }
, [ @mandate_database_subscriptions = ] mandate_database_subscriptions ]

Arguments
[ @name= ] 'name'
Is the name of the policy category. name is sysname, and must be specified if policy_category_id is NULL.
[ @policy_category_id= ] policy_category_id
Is the identifier for the policy category. policy_category_id is int, and must be specified if name is NULL.
[ @mandate_database_subscriptions= ] mandate_database_subscriptions
Determines whether database subscription is mandated for the policy category. mandate_database_subscriptions
is a bit value, with a default of NULL. You can use either of the following values:
0 = Not mandated
1 = Mandated

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_update_policy_category in the context of the msdb system database.
You must specify a value for either name or for policy_category_id. Both cannot be NULL. To obtain these values,
query the msdb.dbo.syspolicy_policy_categories system view.

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.
IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.

Examples
The following example updates the 'Finance' category to mandate database subscriptions.

EXEC msdb.dbo.sp_syspolicy_update_policy_category @name = N'Finance'


, @mandate_database_subscriptions = 1;

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_add_policy_category (Transact-SQL)
sp_syspolicy_delete_policy_category (Transact-SQL)
sp_syspolicy_rename_policy_category (Transact-SQL)
sp_syspolicy_update_policy_category_subscription
(Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates a policy category subscription for a specified database.
Transact-SQL Syntax Conventions

Syntax
sp_syspolicy_update_policy_category_subscription [ @policy_category_subscription_id = ]
policy_category_subscription_id
[ , [ @target_type = ] 'target_type' ]
[ , [ @target_object = ] 'target_object' ]
, [ @policy_category = ] 'policy_category'

Arguments
[ @policy_category_subscription_id= ] policy_category_subscription_id
Is the identifier for the policy category subscription that you want to update. policy_category_subscription_id is int,
and is required.
[ @target_type= ] 'target_type'
Is the target type of the category subscription. target_type is sysname, with a default of NULL.
If you specify target_type, the value must be set to 'DATABASE'.
[ @target_object= ] 'target_object'
Is the name of the database that will subscribe to the policy category. target_object is sysname, with a default of
NULL.
[ @policy_category= ] 'policy_category'
Is the name of the policy category that you want the database to subscribe to. policy_category is sysname, with a
default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
You must run sp_syspolicy_update_policy_category_subscription in the context of the msdb system database.
To obtain values for policy_category_subscription_id and for policy_category, you can use the following query:
SELECT a.policy_category_subscription_id, a.target_type, a.target_object
, b.name AS policy_category
FROM msdb.dbo.syspolicy_policy_category_subscriptions AS a
INNER JOIN msdb.dbo.syspolicy_policy_categories AS b
ON a.policy_category_id = b.policy_category_id;

Permissions
Requires membership in the PolicyAdministratorRole fixed database role.

IMPORTANT
Possible elevation of credentials: Users in the PolicyAdministratorRole role can create server triggers and schedule policy
executions that can affect the operation of the instance of the Database Engine. For example, users in the
PolicyAdministratorRole role can create a policy that can prevent most objects from being created in the Database Engine.
Because of this possible elevation of credentials, the PolicyAdministratorRole role should be granted only to users who are
trusted with controlling the configuration of the Database Engine.

Examples
The following example updates an existing policy category subscription so that the AdventureWorks2012 database
subscribes to the 'Finance' policy category.

EXEC msdb.dbo.sp_syspolicy_update_policy_category_subscription @policy_category_subscription_id = 1


, @target_object = 'AdventureWorks2012'
, @policy_category = 'Finance';

GO

See Also
Policy-Based Management Stored Procedures (Transact-SQL)
sp_syspolicy_add_policy_category_subscription (Transact-SQL)
sp_syspolicy_delete_policy_category_subscription (Transact-SQL)
Query Store Stored Procedures (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
This section contains the following stored procedures used to configure the query store.

In this Section
sp_query_store_flush_db (Transact-SQL)
sp_query_store_force_plan (Transact-SQL)
sp_query_store_remove_plan (Transct-SQL)
sp_query_store_remove_query (Transact-SQL)
sp_query_store_reset_exec_stats (Transact-SQL)
sp_query_store_unforce_plan (Transact-SQL)

See Also
Query Store Catalog Views (Transact-SQL)
Monitoring Performance By Using the Query Store
sp_query_store_flush_db (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Flushes the in-memory portion of the Query Store data to disk.
Transact-SQL Syntax Conventions

Syntax
sp_query_store_flush_db [;]

Return Code Values


0 (success) or 1 (failure)

Remarks
Permissions
Requires the EXECUTE permission on the database, and DELETE permission on the query store catalog views.

Examples
The following example flushes the in-memory portion of the Query Store data to disk.

EXEC sp_query_store_flush_db;

See Also
sp_query_store_force_plan (Transact-SQL)
sp_query_store_remove_query (Transact-SQL)
sp_query_store_unforce_plan (Transact-SQL)
sp_query_store_reset_exec_stats (Transact-SQL)
sp_query_store_remove_plan (Transct-SQL)
sp_query_store_reset_exec_stats (Transact-SQL)
Query Store Catalog Views (Transact-SQL)
Monitoring Performance By Using the Query Store
sp_query_store_force_plan (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Enables forcing a particular plan for a particular query.
When a plan is forced for a particular query, every time SQL Server encounters the query, it tries to force the plan
in the optimizer. If plan forcing fails, a XEvent is fired and the optimizer is instructed to optimize in the normal way.
Transact-SQL Syntax Conventions

Syntax
sp_query_store_force_plan [ @query_id = ] query_id , [ @plan_id = ] plan_id [;]

Arguments
[ @query_id = ] query_id
Is the id of the query. query_id is a bigint, with no default.
[ @plan_id = ] plan_id
Is the id of the query plan to be forced. plan_id is a bigint, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
Permissions
Requires the EXECUTE permission on the database, and INSERT, UPDATE, and DELETE permission on the query
store catalog views.

Examples
The following example returns information about the queries in the query store.

SELECT Txt.query_text_id, Txt.query_sql_text, Pl.plan_id, Qry.*


FROM sys.query_store_plan AS Pl
JOIN sys.query_store_query AS Qry
ON Pl.query_id = Qry.query_id
JOIN sys.query_store_query_text AS Txt
ON Qry.query_text_id = Txt.query_text_id ;

After you identify the query_id and plan_id that you want to force, use the following example to force the query to
use a plan.
EXEC sp_query_store_force_plan 3, 3;

See Also
sp_query_store_remove_plan (Transct-SQL)
sp_query_store_remove_query (Transact-SQL)
sp_query_store_unforce_plan (Transact-SQL)
Query Store Catalog Views (Transact-SQL)
Monitoring Performance By Using the Query Store
sp_query_store_reset_exec_stats (Transact-SQL)
sp_query_store_flush_db (Transact-SQL)
sp_query_store_remove_plan (Transct-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a single plan from the query store.
Transact-SQL Syntax Conventions

Syntax
sp_query_store_remove_plan [ @plan_id = ] plan_id [;]

Arguments
[ @plan_id = ] plan_id
Is the id of the query plan to be removed. plan_id is a bigint, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
Permissions
Requires the EXECUTE permission on the database, and DELETE permission on the query store catalog views.

Examples
The following example returns information about the queries in the query store.

SELECT Txt.query_text_id, Txt.query_sql_text, Pl.plan_id, Qry.*


FROM sys.query_store_plan AS Pl
JOIN sys.query_store_query AS Qry
ON Pl.query_id = Qry.query_id
JOIN sys.query_store_query_text AS Txt
ON Qry.query_text_id = Txt.query_text_id ;

After you identify the plan_id that you want to delete, use the following example to delete a query plan.

EXEC sp_query_store_remove_plan 3;

See Also
sp_query_store_force_plan (Transact-SQL)
sp_query_store_remove_query (Transact-SQL)
sp_query_store_unforce_plan (Transact-SQL)
sp_query_store_reset_exec_stats (Transact-SQL)
sp_query_store_flush_db (Transact-SQL)
Query Store Catalog Views (Transact-SQL)
Monitoring Performance By Using the Query Store
sp_query_store_remove_query (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the query, as well as all associated plans and runtime stats from the query store.
Transact-SQL Syntax Conventions

Syntax
sp_query_store_remove_query [ @query_id = ] query_id [;]

Arguments
[ @query_id = ] query_id
Is the id of the query to be removed from the query store. query_id is a bigint, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
Permissions
Requires the EXECUTE permission on the database, and DELETE permission on the query store catalog views.

Examples
The following example returns information about the queries in the query store.

SELECT Txt.query_text_id, Txt.query_sql_text, Pl.plan_id, Qry.*


FROM sys.query_store_plan AS Pl
JOIN sys.query_store_query AS Qry
ON Pl.query_id = Qry.query_id
JOIN sys.query_store_query_text AS Txt
ON Qry.query_text_id = Txt.query_text_id ;

After you identify the query_id that you want to delete, use the following example to delete the query.
The following example.

EXEC sp_query_store_remove_query 3;

See Also
sp_query_store_force_plan (Transact-SQL)
sp_query_store_remove_plan (Transct-SQL)
sp_query_store_unforce_plan (Transact-SQL)
sp_query_store_reset_exec_stats (Transact-SQL)
sp_query_store_flush_db (Transact-SQL)
Query Store Catalog Views (Transact-SQL)
Monitoring Performance By Using the Query Store
sp_query_store_reset_exec_stats (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Clears the runtime stats for a specific query plan from the query store.
Transact-SQL Syntax Conventions

Syntax
sp_query_store_reset_exec_stats [ @plan_id = ] plan_id [;]

Arguments
[ @plan_id = ] plan_id
Is the id of the query plan to being cleared. plan_id is a bigint, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
Permissions
Requires the EXECUTE permission on the database, and DELETE permission on the query store catalog views.

Examples
The following example returns information about the queries in the query store.

SELECT Txt.query_text_id, Txt.query_sql_text, Pl.plan_id, Qry.*


FROM sys.query_store_plan AS Pl
JOIN sys.query_store_query AS Qry
ON Pl.query_id = Qry.query_id
JOIN sys.query_store_query_text AS Txt
ON Qry.query_text_id = Txt.query_text_id ;

After you identify the plan_id that you want to clear the statistics, use the following example to delete the
execution stats for a specific query plan. This example deletes the execution stats for plan number 3.

EXEC sp_query_store_reset_exec_stats 3;

See Also
sp_query_store_force_plan (Transact-SQL)
sp_query_store_remove_query (Transact-SQL)
sp_query_store_unforce_plan (Transact-SQL)
sp_query_store_remove_plan (Transct-SQL)
sp_query_store_flush_db (Transact-SQL)
Query Store Catalog Views (Transact-SQL)
Monitoring Performance By Using the Query Store
sp_query_store_unforce_plan (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Enables unforcing a particular plan for a particular query.
Transact-SQL Syntax Conventions

Syntax
sp_query_store_unforce_plan [ @query_id = ] query_id , [ @plan_id = ] plan_id [;]

Arguments
[ @query_id = ] query_id
Is the id of the query. query_id is a bigint, with no default.
[ @plan_id = ] plan_id
Is the id of the query plan that will no longer be enforced. plan_id is a bigint, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
Permissions
Requires the EXECUTE permission on the database, and INSERT, UPDATE, and DELETE permission on the query
store catalog views.

Examples
The following example returns information about the queries in the query store.

SELECT Txt.query_text_id, Txt.query_sql_text, Pl.plan_id, Qry.*


FROM sys.query_store_plan AS Pl
JOIN sys.query_store_query AS Qry
ON Pl.query_id = Qry.query_id
JOIN sys.query_store_query_text AS Txt
ON Qry.query_text_id = Txt.query_text_id ;

After you identify the query_id and plan_id that you want to unforce, use the following example to unforce the
plan.

EXEC sp_query_store_unforce_plan 3, 3;
See Also
sp_query_store_force_plan (Transact-SQL)
sp_query_store_remove_plan (Transct-SQL)
sp_query_store_remove_query (Transact-SQL)
sp_query_store_reset_exec_stats (Transact-SQL)
sp_query_store_flush_db (Transact-SQL)
Query Store Catalog Views (Transact-SQL)
Monitoring Performance By Using the Query Store
Security Stored Procedures (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
SQL Server supports the following system stored procedures that are used to manage security. Some of these
stored procedures are deprecated but continue to be available to support backward compatibility. The topics
for deprecated procedures will list their replacement.

sys.sp_add_trusted_assembly sp_addapprole (Deprecated)

sp_addlinkedserver sp_addlinkedsrvlogin

sp_addlogin (Deprecated) sp_addremotelogin (Deprecated)

sp_addrole (Deprecated) sp_addrolemember (Deprecated)

sp_addserver (Deprecated) sp_addsrvrolemember (Deprecated)

sp_adduser (Deprecated) sp_approlepassword (Deprecated)

sp_audit_write sp_change_users_login

sp_changedbowner sp_changeobjectowner (Deprecated)

sp_control_dbmasterkey_password sp_dbfixedrolepermission (Deprecated)

sp_defaultdb (Deprecated) sp_defaultlanguage (Deprecated)

sp_denylogin (Deprecated) sp_describe_parameter_encryption

sp_dropalias (Deprecated) sys.sp_drop_trusted_assembly

sp_dropapprole (Deprecated) sp_droplinkedsrvlogin

sp_droplogin (Deprecated) sp_dropremotelogin (Deprecated)

sp_droprole (Deprecated) sp_droprolemember (Deprecated)

sp_dropserver sp_dropsrvrolemember (Deprecated)

sp_dropuser (Deprecated) sp_grantdbaccess (Deprecated)

sp_grantlogin (Deprecated) sp_helpdbfixedrole

sp_helplinkedsrvlogin sp_helplogins
sp_helpntgroup sp_helpremotelogin (Deprecated)

sp_helprole sp_helprolemember

sp_helprotect (Deprecated) sp_helpsrvrole

sp_helpsrvrolemember sp_helpuser (Deprecated)

sp_migrate_user_to_contained sp_MShasdbaccess

sp_password (Deprecated) sp_refresh_parameter_encryption

sp_remoteoption (Deprecated) sp_revokedbaccess (Deprecated)

sp_revokelogin (Deprecated) sp_setapprole

sp_srvrolepermission (Deprecated) sp_testlinkedserver

sp_unsetapprole sp_validatelogins

sp_xp_cmdshell_proxy_account

See Also
System Stored Procedures (Transact-SQL)
Security Functions (Transact-SQL)
sys.sp_add_trusted_assembly (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2017) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adds an assembly to the list of trusted assemblies for the server.
Transact-SQL Syntax Conventions

Syntax
sp_add_trusted_assembly
[ @hash = ] 'value'
[ , [ @description = ] 'description' ]

Remarks
This procedure adds an assembly to sys.trusted_assemblies.

Arguments
[ @hash = ] 'value'
The SHA2_512 hash value of the assembly to add to the list of trusted assemblies for the server. Trusted
assemblies may load when CLR strict security is enabled, even if the assembly is unsigned or the database is not
marked as trustworthy.
[ @description = ] 'description'
Optional user-defined description of the assembly. Microsoft recommends using the canonical name that encodes
the simple name, version number, culture, public key, and architecture of the assembly to trust. This value uniquely
identifies the assembly on the common language runtime (CLR) side and is the same as the clr_name value in
sys.assemblies.

Permissions
Requires membership in the sysadmin fixed server role or CONTROL SERVER permission.

Examples
The following example adds an assembly named pointudt to the list of trusted assemblies for the server. These
values are available from sys.assemblies.

EXEC sp_add_trusted_assembly
0x8893AD6D78D14EE43DF482E2EAD44123E3A0B684A8873C3F7BF3B5E8D8F09503F3E62370CE742BBC96FE3394477214B84C7C1B0F7A04
DCC788FA99C2C09DFCCC,
N'pointudt, version=0.0.0.0, culture=neutral, publickeytoken=null, processorarchitecture=msil';

See Also
sys.sp_drop_trusted_assembly
sys.trusted_assemblies
CREATE ASSEMBLY (Transact-SQL)
CLR strict security
sys.assemblies
sys.dm_clr_loaded_assemblies
sp_addapprole (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds an application role to the current database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use CREATE APPLICATION ROLE instead.

Transact-SQL Syntax Conventions

Syntax
sp_addapprole [ @rolename = ] 'role' , [ @password = ] 'password'

Arguments
[ @rolename = ] 'role'
Is the name of the new application role. role is sysname, with no default. role must be a valid identifier and cannot
already exist in the current database.
Application role names can contain from 1 up to 128 characters, including letters, symbols, and numbers. Role
names cannot contain a backslash (\) nor be NULL or an empty string ('').
[ @password = ] 'password'
Is the password required to activate the application role. password is sysname, with no default. password cannot
be NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
In earlier versions of SQL Server, users (and roles) are not fully distinct from schemas. Beginning with SQL Server
2005, schemas are fully distinct from roles. This new architecture is reflected in the behavior of CREATE
APPLICATION ROLE. This statement supersedes sp_addapprole.
To maintain backward compatibility with earlier versions of SQL Server, sp_addapprole will do the following:
If a schema with the same name as the application role does not already exist, such a schema will be
created. The new schema will be owned by the application role, and it will be the default schema of the
application role.
If a schema of the same name as the application role already exists, the procedure will fail.
Password complexity is not checked by sp_addapprole. But password complexity is checked by CREATE
APPLICATION ROLE.
The parameter password is stored as a one-way hash.
The sp_addapprole stored procedure cannot be executed from within a user-defined transaction.

IMPORTANT
The Microsoft ODBC encrypt option is not supported by SqlClient. When you can, prompt users to enter application role
credentials at run time. Avoid storing credentials in a file. If you must persist credentials, encrypt them by using the
CryptoAPI functions.

Permissions
Requires ALTER ANY APPLICATION ROLE permission on the database. If a schema with the same name and owner
as the new role does not already exist, also requires CREATE SCHEMA permission on the database.

Examples
The following example adds the new application role SalesApp with the password x97898jLJfcooFUYLKm387gf3 to
the current database.

EXEC sp_addapprole 'SalesApp', 'x97898jLJfcooFUYLKm387gf3' ;


GO

See Also
CREATE APPLICATION ROLE (Transact-SQL)
sp_addlogin (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a new SQL Server login that allows a user to connect to an instance of SQL Server by using SQL Server
authentication.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use CREATE LOGIN instead.

IMPORTANT
When possible, use Windows Authentication.

Transact-SQL Syntax Conventions

Syntax
sp_addlogin [ @loginame = ] 'login'
[ , [ @passwd = ] 'password' ]
[ , [ @defdb = ] 'database' ]
[ , [ @deflanguage = ] 'language' ]
[ , [ @sid = ] sid ]
[ , [ @encryptopt = ] 'encryption_option' ]
[;]

Arguments
[ @loginame= ] 'login'
Is the name of the login. login is sysname, with no default.
[ @passwd= ] 'password'
Is the login password. password is sysname, with a default of NULL.

IMPORTANT
Do not use a blank password. Use a strong password.

[ @defdb= ] 'database'
Is the default database of the login (the database to which the login is first connected after logging in). database is
sysname, with a default of master.
[ @deflanguage= ] 'language'
Is the default language of the login. language is sysname, with a default of NULL. If language is not specified, the
default language of the new login is set to the current default language of the server.
[ @sid= ] 'sid'
Is the security identification number (SID). sid is varbinary(16), with a default of NULL. If sid is NULL, the system
generates a SID for the new login. Despite the use of a varbinary data type, values other than NULL must be
exactly 16 bytes in length, and must not already exist. Specifying sid is useful, for example, when you are scripting
or moving SQL Server logins from one server to another and you want the logins to have the same SID on
different servers.
[ @encryptopt= ] 'encryption_option'
Specifies whether the password is passed in as clear text or as the hash of the clear text password. Note that no
encryption takes place. The word "encrypt" is used in this discussion for the sake of backward compatibility. If a
clear text password is passed in, it is hashed. The hash is stored. encryption_option is varchar(20), and can be one
of the following values.

VALUE DESCRIPTION

NULL The password is passed in clear. This is the default.

skip_encryption The password is already hashed. The Database Engine should


store the value without re-hashing it.

skip_encryption_old The supplied password was hashed by an earlier version of


SQL Server. The Database Engine should store the value
without re-hashing it. This option is provided for upgrade
purposes only.

Return Code Values


0 (success) or 1 (failure)

Remarks
SQL Server logins can contain from 1 to 128 characters, including letters, symbols, and numbers. Logins cannot
contain a backslash (\); be a reserved login name, for example sa or public, or already exist; or be NULL or an
empty string ( '' ).
If the name of a default database is supplied, you can connect to the specified database without executing the USE
statement. However, you cannot use the default database until you are given access to that database by the
database owner (by using sp_adduser or sp_addrolemember) or sp_addrole.
The SID number is a GUID that will uniquely identify the login in the server.
Changing the default language of the server does not change the default language of existing logins. To change
the default language of the server, use sp_configure.
Using skip_encryption to suppress password hashing is useful if the password is already hashed when the login
is added to SQL Server. If the password was hashed by an earlier version of SQL Server, use
skip_encryption_old.
sp_addlogin cannot be executed within a user-defined transaction.
The following table shows several stored procedures that are used with sp_addlogin.

STORED PROCEDURE DESCRIPTION

sp_grantlogin Adds a Windows user or group.


STORED PROCEDURE DESCRIPTION

sp_password Changes the password of a user.

sp_defaultdb Changes the default database of a user.

sp_defaultlanguage Changes the default language of a user.

Permissions
Requires ALTER ANY LOGIN permission.

Examples
A. Creating a SQL Server login
The following example creates a SQL Server login for the user Victoria , with a password of B1r12-36 , without
specifying a default database.

EXEC sp_addlogin 'Victoria', 'B1r12-36';


GO

B. Creating a SQL Server login that has a default database


The following example creates a SQL Server login for the user Albert , with a password of B5432-3M6 and a
default database of corporate .

EXEC sp_addlogin 'Albert', 'B5432-3M6', 'corporate';


GO

C. Creating a SQL Server login that has a different default language


The following example creates a SQL Server login for the user TzTodorov , with a password of 709hLKH7chjfwv ,a
default database of AdventureWorks2012 , and a default language of Bulgarian .

EXEC sp_addlogin 'TzTodorov', '709hLKH7chjfwv', 'AdventureWorks2012', N'български'

D. Creating a SQL Server login that has a specific SID


The following example creates a SQL Server login for the user Michael , with a password of B548bmM%f6 , a default
database of AdventureWorks2012 , a default language of us_english , and a SID of
0x0123456789ABCDEF0123456789ABCDEF .

EXEC sp_addlogin 'Michael', 'B548bmM%f6', 'AdventureWorks2012', 'us_english',


0x0123456789ABCDEF0123456789ABCDEF

See Also
CREATE LOGIN (Transact-SQL)
sp_droplogin (Transact-SQL)
sp_helpuser (Transact-SQL)
sp_revokelogin (Transact-SQL)
xp_logininfo (Transact-SQL)
sp_addremotelogin (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a new remote login ID on the local server. This enables remote servers to connect and execute remote
procedure calls.

IMPORTANT
This feature will be removed in the next version of Microsoft SQL Server. Do not use this feature in new development work,
and modify applications that currently use this feature as soon as possible. Use linked servers and linked server stored
procedures instead.

Transact-SQL Syntax Conventions

Syntax
sp_addremotelogin [ @remoteserver = ] 'remoteserver'
[ , [ @loginame = ] 'login' ]
[ , [ @remotename = ] 'remote_name' ]

Arguments
[ @remoteserver = ] 'remoteserver'
Is the name of the remote server that the remote login applies to. remoteserver is sysname, with no default. If only
remoteserver is specified, all users on remoteserver are mapped to existing logins of the same name on the local
server. The server must be known to the local server. This is added by using sp_addserver. When users on
remoteserver connect to the local server that is running SQL Server to execute a remote stored procedure, they
connect as the local login that matches their own login on remoteserver. remoteserver is the server that initiates
the remote procedure call.
[ @loginame = ] 'login'
Is the login ID of the user on the local instance of SQL Server. login is sysname, with a default of NULL. loginmust
already exist on the local instance of SQL Server. If login is specified, all users on remoteserver are mapped to that
specific local login. When users on remoteserver connect to the local instance of SQL Server to execute a remote
stored procedure, they connect as login.
[ @remotename = ] 'remote_name'
Is the login ID of the user on the remote server. remote_name is sysname, with a default of NULL. remote_name
must exist on remoteserver. If remote_name is specified, the specific user remote_name is mapped to login on the
local server. When remote_name on remoteserver connects to the local instance of SQL Server to execute a remote
stored procedure, it connects as login. The login ID of remote_name can be different from the login ID on the
remote server, login.

Return Code Values


0 (success) or 1 (failure)
Remarks
To execute distributed queries, use sp_addlinkedsrvlogin.
sp_addremotelogin cannot be used inside a user-defined transaction.

Permissions
Only members of the sysadmin and securityadmin fixed server roles can execute sp_addremotelogin.

Examples
A. Mapping one to one
The following example maps remote names to local names when the remote server ACCOUNTS and local server
have the same user logins.

EXEC sp_addremotelogin 'ACCOUNTS';

B. Mapping many to one


The following example creates an entry that maps all users from the remote server ACCOUNTS to the local login ID
Albert .

EXEC sp_addremotelogin 'ACCOUNTS', 'Albert';

C. Using explicit one -to -one mapping


The following example maps a remote login from the remote user Chris on the remote server ACCOUNTS to the
local user salesmgr .

EXEC sp_addremotelogin 'ACCOUNTS', 'salesmgr', 'Chris';

See Also
sp_addlinkedsrvlogin (Transact-SQL)
sp_addlogin (Transact-SQL)
sp_addserver (Transact-SQL)
sp_dropremotelogin (Transact-SQL)
sp_grantlogin (Transact-SQL)
sp_helpremotelogin (Transact-SQL)
sp_helpserver (Transact-SQL)
sp_remoteoption (Transact-SQL)
sp_revokelogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addrole (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a new database role in the current database.

IMPORTANT
sp_addrole is included for compatibility with earlier versions of Microsoft SQL Server and may not be supported in a future
release. Use CREATE ROLE instead.

Transact-SQL Syntax Conventions

Syntax
sp_addrole [ @rolename = ] 'role' [ , [ @ownername = ] 'owner' ]

Arguments
[ @rolename = ] 'role'
Is the name of the new database role. role is a sysname, with no default. role must be a valid identifier (ID) and
must not already exist in the current database.
[ @ownername =] 'owner'
Is the owner of the new database role. owner is a sysname, with a default of the current executing user. owner
must be a database user or database role in the current database.

Return Code Values


0 (success) or 1 (failure)

Remarks
The names of SQL Server database roles can contain from 1 through 128 characters, including letters, symbols,
and numbers. The names of database roles cannot :contain a backslash character (\), be NULL, or an empty string
('').
After you add a database role, use sp_addrolemember (Transact-SQL) to add principals to the role. When GRANT,
DENY, or REVOKE statements are used to apply permissions to the database role, members of the database role
inherit those permissions as if the permissions were applied directly to their accounts.

NOTE
New server roles cannot be created. Roles can only be created at the database level.

sp_addrole cannot be used inside a user-defined transaction.


Permissions
Requires CREATE ROLE permission on the database. If creating a schema, requires CREATE SCHEMA on the
database. If owner is specified as a user or group, requires IMPERSONATE on that user or group. If owner is
specified as a role, requires ALTER permission on that role or on a member of that role. If owner is specified as an
application role, requires ALTER permission on that application role.

Examples
The following example adds a new role called Managers to the current database.

EXEC sp_addrole 'Managers';

See Also
System Stored Procedures (Transact-SQL)
Security Stored Procedures (Transact-SQL)
CREATE ROLE (Transact-SQL)
sp_addrolemember (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a database user, database role, Windows login, or Windows group to a database role in the current
database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER ROLE instead.

Transact-SQL Syntax Conventions

Syntax
-- Syntax for SQL Server and Azure SQL Database

sp_addrolemember [ @rolename = ] 'role',


[ @membername = ] 'security_account'

-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse

sp_addrolemember 'role', 'security_account'

Arguments
[ @rolename= ] 'role'
Is the name of the database role in the current database. role is a sysname, with no default.
[ @membername= ] 'security_account'
Is the security account being added to the role. security_account is a sysname, with no default. security_account
can be a database user, database role, Windows login, or Windows group.

Return Code Values


0 (success) or 1 (failure)

Remarks
A member added to a role by using sp_addrolemember inherits the permissions of the role. If the new member is
a Windows-level principal without a corresponding database user, a database user will be created but may not be
fully mapped to the login. Always check that the login exists and has access to the database.
A role cannot include itself as a member. Such "circular" definitions are not valid, even when membership is only
indirectly implied by one or more intermediate memberships.
sp_addrolemember cannot add a fixed database role, fixed server role, or dbo to a role. sp_addrolemember
cannot be executed within a user-defined transaction.
Only use sp_addrolemember to add a member to a database role. To add a member to a server role, use
sp_addsrvrolemember (Transact-SQL).

Permissions
Adding members to flexible database roles requires one of the following:
Membership in the db_securityadmin or db_owner fixed database role.
Membership in the role that owns the role.
ALTER ANY ROLE permission or ALTER permission on the role.
Adding members to fixed database roles requires membership in the db_owner fixed database role.

Examples
A. Adding a Windows login
The following example adds the Windows login Contoso\Mary5 to the AdventureWorks2012 database as user
Mary5 . The user Mary5 is then added to the Production role.

NOTE
Because Contoso\Mary5 is known as the database user Mary5 in the AdventureWorks2012 database, the user name
Mary5 must be specified. The statement will fail unless a Contoso\Mary5 login exists. Test by using a login from your
domain.

USE AdventureWorks2012;
GO
CREATE USER Mary5 FOR LOGIN [Contoso\Mary5] ;
GO

B. Adding a database user


The following example adds the database user Mary5 to the Production database role in the current database.

EXEC sp_addrolemember 'Production', 'Mary5';

Examples: SQL Data Warehouse and Parallel Data Warehouse


C. Adding a Windows login
The following example adds the login LoginMary to the AdventureWorks2008R2 database as user UserMary . The
user UserMary is then added to the Production role.

NOTE
Because the login LoginMary is known as the database user UserMary in the AdventureWorks2012 database, the user
name UserMary must be specified. The statement will fail unless a Mary5 login exists. Logins and users usually have the
same name. This example uses different names to differentiate the actions affecting the login vs. the user.
-- Uses AdventureWorks

CREATE USER UserMary FOR LOGIN LoginMary ;


GO
EXEC sp_addrolemember 'Production', 'UserMary'

D. Adding a database user


The following example adds the database user UserMary to the Production database role in the current database.

EXEC sp_addrolemember 'Production', 'UserMary'

See Also
Security Stored Procedures (Transact-SQL)
sp_addsrvrolemember (Transact-SQL)
sp_droprolemember (Transact-SQL)
sp_grantdbaccess (Transact-SQL)
System Stored Procedures (Transact-SQL)
Database-Level Roles
sp_addserver (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Defines the name of the local instance of SQL Server. When the computer hosting SQL Server is renamed, use
sp_addserver to inform the instance of the SQL Server Database Engine of the new computer name. This
procedure must be executed on all instances of the Database Engine hosted on the computer. The instance name
of the Database Engine cannot be changed. To change the instance name of a named instance, install a new
instance with the desired name, detach the database files from old instance, attach the databases to the new
instance and drop the old instance. Alternatively, you can create a client alias name on the client computer,
redirecting the connection to different server and instance name or server:port combination without changing
the name of the instance on the server computer.
Transact-SQL Syntax Conventions

Syntax
sp_addserver [ @server = ] 'server' ,
[ @local = ] 'local'
[ , [ @duplicate_ok = ] 'duplicate_OK' ]

Arguments
[ @server = ] 'server'
Is the name of the server. Server names must be unique and follow the rules for Microsoft Windows computer
names, although spaces are not allowed. server is sysname, with no default.
When multiple instances of SQL Server are installed on a computer, an instance operates as if it is on a separate
server. Specify a named instance by referring to server as servername\instancename.
[ @local = ] 'LOCAL'
Specifies that the server that is being added as a local server. @local is varchar(10), with a default of NULL.
Specifying @local as LOCAL defines @server as the name of the local server and causes the @@SERVERNAME
function to return the value of server.
SQL Server Setup sets this variable to the computer name during installation. By default, the computer name is
the way users connect to an instance of SQL Server without requiring additional configuration.
The local definition takes effect only after the Database Engine is restarted. Only one local server can be defined in
each instance of the Database Engine.
[ @duplicate_ok = ] 'duplicate_OK'
Specifies whether a duplicate server name is allowed. @duplicate_OK is varchar(13), with a default of NULL.
@duplicate_OK can only have the value duplicate_OK or NULL. If duplicate_OK is specified and the server
name that is being added already exists, no error is raised. If named parameters are not used, @local must be
specified.

Return Code Values


0 (success) or 1 (failure)

Remarks
To set or clear server options, use sp_serveroption.
sp_addserver cannot be used inside a user-defined transaction.
Using sp_addserver to add a remote server is discontinued. Use sp_addlinkedserver instead.

Permissions
Requires membership in the setupadmin fixed server role.

Examples
The following example changes the Database Engine entry for the name of the computer hosting SQL Server to
ACCOUNTS .

sp_addserver 'ACCOUNTS', 'local';

See Also
Rename a Computer that Hosts a Stand-Alone Instance of SQL Server
sp_addlinkedserver (Transact-SQL)
sp_dropserver (Transact-SQL)
sp_helpserver (Transact-SQL)
System Stored Procedures (Transact-SQL)
Security Stored Procedures (Transact-SQL)
sp_addsrvrolemember (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a login as a member of a fixed server role.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER SERVER ROLE instead.

Transact-SQL Syntax Conventions

Syntax
sp_addsrvrolemember [ @loginame= ] 'login'
, [ @rolename = ] 'role'

Arguments
[ @loginame = ] 'login'
Is the name of the login being added to the fixed server role. login is sysname, with no default. login can be a SQL
Server login or a Windows login. If the Windows login has not already been granted access to SQL Server, access
is automatically granted.
[ @rolename = ] 'role'
Is the name of the fixed server role to which the login is being added. role is sysname, with a default of NULL, and
must be one of the following values:
sysadmin
securityadmin
serveradmin
setupadmin
processadmin
diskadmin
dbcreator
bulkadmin

Return Code Values


0 (success) or 1 (failure)
Remarks
When a login is added to a fixed server role, the login gains the permissions associated with that role.
The role membership of the sa login and public cannot be changed.
Use sp_addrolemember to add a member to a fixed database or user-defined role.
sp_addsrvrolemember cannot be executed within a user-defined transaction.

Permissions
Requires membership in the role to which the new member is being added.

Examples
The following example adds the Windows login Corporate\HelenS to the sysadmin fixed server role.

EXEC sp_addsrvrolemember 'Corporate\HelenS', 'sysadmin';


GO

See Also
Security Stored Procedures (Transact-SQL)
sp_addrolemember (Transact-SQL)
sp_dropsrvrolemember (Transact-SQL)
System Stored Procedures (Transact-SQL)
Security Functions (Transact-SQL)
CREATE SERVER ROLE (Transact-SQL)
DROP SERVER ROLE (Transact-SQL)
sp_adduser (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a new user to the current database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use CREATE USER instead.

Transact-SQL Syntax Conventions

Syntax
sp_adduser [ @loginame = ] 'login'
[ , [ @name_in_db = ] 'user' ]
[ , [ @grpname = ] 'role' ]

Arguments
[ @loginame = ] 'login'
Is the name of the SQL Server login or Windows login. login is a sysname, with no default. login must be an
existing SQL Server login or Windows login.
[ @name_in_db = ] 'user'
Is the name for the new database user. user is a sysname, with a default of NULL. If user is not specified, the name
of the new database user defaults to the login name. Specifying user gives the new user a name in the database
different from the server-level login name.
[ @grpname = ] 'role'
Is the database role of which the new user becomes a member. role is sysname, with a default of NULL. role must
be a valid database role in the current database.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_adduser will also create a schema that has the name of the user.
After a user has been added, use the GRANT, DENY, and REVOKE statements to define the permissions that control
the activities performed by the user.
Use sys.server_principals to display a list of valid login names.
Use sp_helprole to display a list of the valid role names. When you specify a role, the user automatically gains the
permissions that are defined for the role. If a role is not specified, the user gains the permissions granted to the
default public role. To add a user to a role, a value for the user name must be supplied. (username can be the
same as login_id.)
User guest already exists in every database. Adding user guest will enable this user, if it was previously disabled.
By default, user guest is disabled in new databases.
sp_adduser cannot be executed inside a user-defined transaction.
You cannot add a guest user because a guest user already exists inside every database. To enable the guest user,
grant guest CONNECT permission as shown:

GRANT CONNECT TO guest;


GO

Permissions
Requires ownership of the database.

Examples
A. Adding a database user
The following example adds the database user Vidur to the existing Recruiting role in the current database,
using the existing SQL Server login Vidur .

EXEC sp_adduser 'Vidur', 'Vidur', 'Recruiting';

B. Adding a database user with the same login ID


The following example adds user Arvind to the current database for the SQL Server login Arvind . This user
belongs to the default public role.

EXEC sp_adduser 'Arvind';

C. Adding a database user with a different name than its server-level login
The following example adds SQL Server login BjornR to the current database that has a user name of Bjorn , and
adds database user Bjorn to the Production database role.

EXEC sp_adduser 'BjornR', 'Bjorn', 'Production';

See Also
Security Stored Procedures (Transact-SQL)
sys.server_principals (Transact-SQL)
sp_addrole (Transact-SQL)
CREATE USER (Transact-SQL)
sp_dropuser (Transact-SQL)
sp_grantdbaccess (Transact-SQL)
sp_grantlogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_approlepassword (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the password of an application role in the current database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER APPLICATION ROLE instead.

Transact-SQL Syntax Conventions

Syntax
sp_approlepassword [ @rolename= ] 'role' , [ @newpwd = ] 'password'

Arguments
[ @rolename = ] 'role'
Is the name of the application role. Role is sysname, with no default. role must exist in the current database.
[ @newpwd = ] 'password'
Is the new password for the application role. password is sysname, with no default. password cannot be NULL.

IMPORTANT
Do not use a NULL password. Use a strong password. For more information, see Strong Passwords.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_approlepassword cannot be executed within a user-defined transaction.

Permissions
Requires ALTER ANY APPLICATION ROLE permission on the database.

Examples
The following example sets the password for the PayrollAppRole application role to B3r12-36 .
EXEC sp_approlepassword 'PayrollAppRole', '''B3r12-36';

See Also
Security Stored Procedures (Transact-SQL)
Application Roles
sp_addapprole (Transact-SQL)
sp_setapprole (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_audit_write (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a user-defined audit event to the USER_DEFINED_AUDIT_GROUP. If USER_DEFINED_AUDIT_GROUP is
not enabled, sp_audit_write is ignored.
Transact-SQL Syntax Conventions

Syntax
sp_audit_write [ @user_defined_event_id = ] user_defined_event_id ,
[ @succeeded = succeeded
[ , [ @user_defined_information = ] 'user_defined_information' ]
[ ; ]

Arguments
@user_defined_event_id
A parameter defined by the user and recorded in the user_defined_event_id column of the audit log.
@user_defined_event_id is type smallint.
@succeeded
A parameter passed by user to indicate whether the event was successful or not. This appears in the succeeded
column of the audit log. @succeeded is bit.
@user_defined_information
Is the text defined by the user and recorded in the new user_defined_event_id column of the audit log.
@user_defined_information is nvarchar(4000).

Return Code Values


0 (success) or 1 (failure)
Failures are caused by incorrect input parameters or failure to write to the target audit log.

Remarks
When the USER_DEFINED_AUDIT_GROUP is added to either a server audit specification or a database audit
specification, the event triggered by sp_audit_write will be included in the audit log.

Permissions
Requires membership in the public database role.

Examples
A. Creating a user-defined audit event with informational text
The following example creates an audit event with the id 27, the succeeded value of 0, and included optional
informational text.

EXEC sp_audit_write @user_defined_event_id = 27 ,


@succeeded = 0
, @user_defined_information = N'Access to a monitored object.' ;

B. Creating a user-defined audit event without informational text


The following example creates an audit event with the id 27, the succeeded value of 0, and does not include
optional informational text or the optional parameter names.

EXEC sp_audit_write 27, 0;

See Also
Security Stored Procedures (Transact-SQL)
sys.server_principals (Transact-SQL)
sp_addrole (Transact-SQL)
CREATE USER (Transact-SQL)
sp_dropuser (Transact-SQL)
sp_grantdbaccess (Transact-SQL)
sp_grantlogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_change_users_login (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Maps an existing database user to a SQL Server login. This feature will be removed in a future version of Microsoft
SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use
this feature. Use ALTER USER instead.
Transact-SQL Syntax Conventions

Syntax
sp_change_users_login [ @Action = ] 'action'
[ , [ @UserNamePattern = ] 'user' ]
[ , [ @LoginName = ] 'login' ]
[ , [ @Password = ] 'password' ]
[;]

Arguments
[ @Action= ] 'action'
Describes the action to be performed by the procedure. action is varchar(10). action can have one of the following
values.

VALUE DESCRIPTION

Auto_Fix Links a user entry in the sys.database_principals system


catalog view in the current database to a SQL Server login of
the same name. If a login with the same name does not exist,
one will be created. Examine the result from the Auto_Fix
statement to confirm that the correct link is in fact made.
Avoid using Auto_Fix in security-sensitive situations.

When you use Auto_Fix, you must specify user and password
if the login does not already exist, otherwise you must specify
user but password will be ignored. login must be NULL. user
must be a valid user in the current database. The login cannot
have another user mapped to it.

Report Lists the users and corresponding security identifiers (SID) in


the current database that are not linked to any login. user,
login, and password must be NULL or not specified.

To replace the report option with a query using the system


tables, compare the entries in sys.server_prinicpals with the
entries in sys.database_principals.

Update_One Links the specified user in the current database to an existing


SQL Server login. user and login must be specified. password
must be NULL or not specified.
[ @UserNamePattern= ] 'user'
Is the name of a user in the current database. user is sysname, with a default of NULL.
[ @LoginName= ] 'login'
Is the name of a SQL Server login. login is sysname, with a default of NULL.
[ @Password= ] 'password'
Is the password assigned to a new SQL Server login that is created by specifying Auto_Fix. If a matching login
already exists, the user and login are mapped and password is ignored. If a matching login does not exist,
sp_change_users_login creates a new SQL Server login and assigns password as the password for the new login.
password is sysname, and must not be NULL.

IMPORTANT!! Always use a strong Password!

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

UserName sysname Database user name.

UserSID varbinary(85) User's security identifier.

Remarks
Use sp_change_users_login to link a database user in the current database with a SQL Server login. If the login for a
user has changed, use sp_change_users_login to link the user to the new login without losing user permissions. The
new login cannot be sa, and the usercannot be dbo, guest, or an INFORMATION_SCHEMA user.
sp_change_users_login cannot be used to map database users to Windows-level principals, certificates, or
asymmetric keys.
sp_change_users_login cannot be used with a SQL Server login created from a Windows principal or with a user
created by using CREATE USER WITHOUT LOGIN.
sp_change_users_login cannot be executed within a user-defined transaction.

Permissions
Requires membership in the db_owner fixed database role. Only members of the sysadmin fixed server role can
specify the Auto_Fix option.

Examples
A. Showing a report of the current user to login mappings
The following example produces a report of the users in the current database and their security identifiers (SIDs).

EXEC sp_change_users_login 'Report';

B. Mapping a database user to a new SQL Server login


In the following example, a database user is associated with a new SQL Server login. Database user MB-Sales ,
which at first is mapped to another login, is remapped to login MaryB .

--Create the new login.


CREATE LOGIN MaryB WITH PASSWORD = '982734snfdHHkjj3';
GO
--Map database user MB-Sales to login MaryB.
USE AdventureWorks2012;
GO
EXEC sp_change_users_login 'Update_One', 'MB-Sales', 'MaryB';
GO

C. Automatically mapping a user to a login, creating a new login if it is required


The following example shows how to use Auto_Fix to map an existing user to a login of the same name, or to
create the SQL Server login Mary that has the password B3r12-3x$098f6 if the login Mary does not exist.

USE AdventureWorks2012;
GO
EXEC sp_change_users_login 'Auto_Fix', 'Mary', NULL, 'B3r12-3x$098f6';
GO

See Also
Security Stored Procedures (Transact-SQL)
CREATE LOGIN (Transact-SQL)
sp_adduser (Transact-SQL)
sp_helplogins (Transact-SQL)
System Stored Procedures (Transact-SQL)
sys.database_principals (Transact-SQL)
sp_changedbowner (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the owner of the current database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER AUTHORIZATION instead.

Transact-SQL Syntax Conventions

Syntax
sp_changedbowner [ @loginame = ] 'login'
[ , [ @map = ] remap_alias_flag ]

Arguments
[ @loginame= ] 'login'
Is the login ID of the new owner of the current database. login is sysname, with no default. login must be an
already existing SQL Server login or Windows user. login cannot become the owner of the current database if it
already has access to the database through an existing user security account within the database. To avoid this,
drop the user within the current database first.
[ @map= ] remap_alias_flag
The remap_alias_flag parameter is deprecated because login aliases have been removed from SQL Server. Using
the remap_alias_flag parameter does not cause an error but has no effect.

Return Code Values


0 (success) or 1 (failure)

Remarks
After sp_changedbowner is executed, the new owner is known as the dbo user inside the database. The dbo has
implied permissions to perform all activities in the database.
The owner of the master, model, or tempdb system databases cannot be changed.
To display a list of the valid login values, execute the sp_helplogins stored procedure.
Executing sp_changedbowner with only the login parameter changes database ownership to login.
You can change the owner of any securable by using the ALTER AUTHORIZATION statement. For more
information, see ALTER AUTHORIZATION (Transact-SQL).
Permissions
Requires TAKE OWNERSHIP permission on the database. If the new owner has a corresponding user in the
database, requires IMPERSONATE permission on the login, otherwise requires CONTROL SERVER permission on
the server.

Examples
The following example makes the login Albert the owner of the current database.

EXEC sp_changedbowner 'Albert';

See Also
Security Stored Procedures (Transact-SQL)
CREATE DATABASE (SQL Server Transact-SQL)
sp_dropalias (Transact-SQL)
sp_dropuser (Transact-SQL)
sp_helpdb (Transact-SQL)
sp_helplogins (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_changeobjectowner (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the owner of an object in the current database.

IMPORTANT
This stored procedure only works with the objects available in Microsoft SQL Server 2000. This feature will be removed in a
future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications
that currently use this feature. Use ALTER SCHEMA or ALTER AUTHORIZATION instead. sp_changeobjectowner changes
both the schema and the owner. To preserve compatibility with earlier versions of SQL Server, this stored procedure will only
change object owners when both the current owner and the new owner own schemas that have the same name as their
database user names.

IMPORTANT
A new permission requirement has been added to this stored procedure.

Transact-SQL Syntax Conventions

Syntax
sp_changeobjectowner [ @objname = ] 'object' , [ @newowner = ] 'owner'

Arguments
[ @objname = ] 'object'
Is the name of an existing table, view, user-defined function, or stored procedure in the current database. object is
an nvarchar(776), with no default. object can be qualified with the owner of the existing object, in the form
existing_owner.object if the schema and its owner have the same name.
[ @newowner=] 'owner '
Is the name of the security account that will be the new owner of the object. owner is sysname, with no default.
owner must be a valid database user, server role, Microsoft Windows login, or Windows group with access to the
current database. If the new owner is a Windows user or Windows group for which there is no corresponding
database-level principal, a database user will be created.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changeobjectowner removes all existing permissions from the object. You will have to reapply any
permissions that you want to keep after running sp_changeobjectowner. Therefore, we recommend that you
script out existing permissions before running sp_changeobjectowner. After ownership of the object has been
changed, you can use the script to reapply permissions. You must modify the object owner in the permissions
script before running.
To change the owner of a securable, use ALTER AUTHORIZATION. To change a schema, use ALTER SCHEMA.

Permissions
Requires membership in the db_owner fixed database role, or membership in both the db_ddladmin fixed
database role and the db_securityadmin fixed database role, and also CONTROL permission on the object.

Examples
The following example changes the owner of the authors table to Corporate\GeorgeW .

EXEC sp_changeobjectowner 'authors', 'Corporate\GeorgeW';


GO

See Also
ALTER SCHEMA (Transact-SQL)
ALTER DATABASE (Transact-SQL)
ALTER AUTHORIZATION (Transact-SQL)
sp_changedbowner (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_control_dbmasterkey_password (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adds or drops a credential containing the password needed to open a database master key.
Transact-SQL Syntax Conventions

Syntax
sp_control_dbmasterkey_password @db_name = 'database_name,
@password = 'master_key_password' , @action = { 'add' | 'drop' }

Arguments
@db_name=N'database_name'
Specifies the name of the database associated with this credential. Cannot be a system database. database_name is
nvarchar.
@password=N'password'
Specifies the password of the master key. password is nvarchar.
@action=N'add'
Specifies that a credential for the specified database will be added to the credential store. The credential will contain
the password of the database master key. The value passed to @action is nvarchar.
@action=N'drop'
Specifies that a credential for the specified database will be dropped from the credential store. The value passed to
@action is nvarchar.

Remarks
When SQL Server needs a database master key to decrypt or encrypt a key, SQL Server tries to decrypt the
database master key with the service master key of the instance. If the decryption fails, SQL Server searches the
credential store for master key credentials that have the same family GUID as the database for which it needs the
master key. SQL Server then tries to decrypt the database master key with each matching credential until the
decryption succeeds or there are no more credentials.
Cau t i on

Do not create a master key credential for a database that must be inaccessible to sa and other highly-privileged
server principals. You can configure a database so that its key hierarchy cannot be decrypted by the service master
key. This option is supported as a defense-in-depth for databases that contain encrypted information that should
not be accessible to sa or other highly privileged server principals. Creating a master key credential for such a
database removes this defense-in-depth, enabling sa and other highly privileged server principals to decrypt the
database.
Credentials that are created by using sp_control_dbmasterkey_password are visible in the
sys.master_key_passwords catalog view. The names of credentials that are created for database master keys have
the following format: ##DBMKEY_<database_family_guid>_<random_password_guid>## . The password is stored as the
credential secret. For each password added to the credential store there is a row in sys.credentials.
You cannot use sp_control_dbmasterkey_password to create a credential for the following system databases:
master, model, msdb, or tempdb.
sp_control_dbmasterkey_password does not verify that the password can open the master key of the specified
database.
If you specify a password that is already stored in a credential for the specified database,
sp_control_dbmasterkey_password will fail.

NOTE
Two databases from different server instances can share the same family GUID. If this occurs, the databases will share the
same master key records in the credential store.

Parameters passed to sp_control_dbmasterkey_password do not appear in traces.

NOTE
When you are using the credential that was added by using sp_control_dbmasterkey_password to open the database master
key, the database master key is re-encrypted by the service master key. If the database is in read-only mode, the re-
encryption operation will fail, and the database master key will remain unencrypted. For subsequent access to the database
master key, you must use the OPEN MASTER KEY statement and a password. To avoid using a password, create the
credential before you move the database to read-only mode.

Potential Backward Compatibility Issue: Currently, the stored procedure does not check whether a master key
exists. This is permitted for backward compatibility, but displays a warning. This behavior is deprecated. In a future
release the master key must exist and the password used in the stored procedure
sp_control_dbmasterkey_password must be the same password as one of the passwords used to encrypt the
database master key.

Permissions
Requires CONTROL permission on the database.

Examples
A. Creating a credential for the AdventureWorks2012 master key
The following example creates a credential for the AdventureWorks2012 database master key, and saves the master
key password as the secret in the credential. Because all parameters that are passed to
sp_control_dbmasterkey_password must be of data type nvarchar, the text strings are converted with the casting
operator N .

EXEC sp_control_dbmasterkey_password @db_name = N'AdventureWorks2012',


@password = N'sdfjlkj#mM00sdfdsf98093258jJlfdk4', @action = N'add';
GO

B. Dropping a credential for a database master key


The following example removes the credential created in example A. Note that all parameters are required,
including the password.
EXEC sp_control_dbmasterkey_password @db_name = N'AdventureWorks2012',
@password = N'sdfjlkj#mM00sdfdsf98093258jJlfdk4', @action = N'drop';
GO

See Also
Set Up an Encrypted Mirror Database
Security Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sys.credentials (Transact-SQL)
Credentials (Database Engine)
sp_dbfixedrolepermission (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Displays the permissions of a fixed database role. sp_dbfixedrolepermission returns correct information in SQL
Server 2000. The output does not reflect the changes to the permissions hierarchy that were implemented in SQL
Server 2005. For more information, seePermissions (Database Engine).

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature.

Transact-SQL Syntax Conventions

Syntax
sp_dbfixedrolepermission [ [ @rolename = ] 'role' ]

Arguments
[ @rolename = ] 'role'
Is the name of a valid SQL Server fixed database role. role is sysname, with a default of NULL. If role is not
specified, the permissions for all fixed database roles are displayed.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

DbFixedRole sysname Name of the fixed database role

Permission nvarchar(70) Permissions associated with


DbFixedRole

Remarks
To display a list of the fixed database roles, execute sp_helpdbfixedrole. The following table shows the fixed
database roles.
FIXED DATABASE ROLE DESCRIPTION

db_owner Database owners

db_accessadmin Database access administrators

db_securityadmin Database security administrators

db_ddladmin Database data definition language (DDL) administrators

db_backupoperator Database backup operators

db_datareader Database data readers

db_datawriter Database data writers

db_denydatareader Database deny data readers

db_denydatawriter Database deny data writers

Members of the db_owner fixed database role have the permissions of all the other fixed database roles. To
display the permissions for fixed server roles, execute sp_srvrolepermission.
The result set includes the Transact-SQL statements that can be executed, and other special activities that can be
performed, by members of the database role.

Permissions
Requires membership in the public role.

Examples
The following query returns the permissions for all fixed database roles because it does not specify a fixed
database role.

EXEC sp_dbfixedrolepermission;
GO

See Also
Security Stored Procedures (Transact-SQL)
sp_addrolemember (Transact-SQL)
sp_droprolemember (Transact-SQL)
sp_helpdbfixedrole (Transact-SQL)
sp_srvrolepermission (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_defaultdb (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the default database for a Microsoft SQL Server login.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER LOGIN instead.

Transact-SQL Syntax Conventions

Syntax
sp_defaultdb [ @loginame = ] 'login', [ @defdb = ] 'database'

Arguments
[ @loginame=] 'login'
Is the login name. login is sysname, with no default. login can be an existing SQL Server login or a Windows user
or group. If a login for the Windows user or group does not exist in SQL Server, it is automatically added.
[ @defdb=] 'database'
Is the name of the new default database. database is sysname, with no default. database must already exist.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_defaultdb calls ALTER LOGIN. This statement supports additional options. For information about changing
default database, see ALTER LOGIN (Transact-SQL).
sp_defaultdb cannot be executed within a user-defined transaction.

Permissions
Requires ALTER ANY LOGIN permission.

Examples
The following example sets AdventureWorks2012 as the default database for SQL Server login Victoria .

EXEC sp_defaultdb 'Victoria', 'AdventureWorks2012';


See Also
Security Stored Procedures (Transact-SQL)
ALTER LOGIN (Transact-SQL)
sp_addlogin (Transact-SQL)
sp_droplogin (Transact-SQL)
sp_grantdbaccess (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_defaultlanguage (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the default language of for a SQL Server login.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER LOGIN instead.

Transact-SQL Syntax Conventions

Syntax
sp_defaultlanguage [ @loginame = ] 'login'
[ , [ @language = ] 'language' ]

Arguments
[ @loginame = ] 'login'
Is the login name. login is sysname, with no default. login can be an existing SQL Server login or a Windows user
or group.
[ @language = ] 'language'
Is the default language of the login. language is sysname, with a default of NULL. language must be a valid
language on the server. If language is not specified, language is set to the server default language; default
language is defined by the sp_configure configuration variable default language. Changing the server default
language does not change the default language for existing logins.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_defaultlanguage calls ALTER LOGIN, which supports additional options. For information about changing
other login defaults, see ALTER LOGIN (Transact-SQL).
Use the SET LANGUAGE statement to change the language of the current session. Use the @@LANGUAGE function
to show the current language setting.
If the default language of a login is dropped from the server, the login acquires the default language of the server.
sp_defaultlanguage cannot be executed within a user-defined transaction.
Information about languages installed on the server is visible in the sys.syslanguages catalog view.
Permissions
Requires ALTER ANY LOGIN permission.

Examples
The following example uses ALTER LOGIN to change the default language for login Fathima to Arabic. This is the
preferred method.

ALTER LOGIN Fathima WITH DEFAULT_LANGUAGE = Arabic;


GO

See Also
Security Stored Procedures (Transact-SQL)
ALTER LOGIN (Transact-SQL)
@@LANGUAGE (Transact-SQL)
SET Statements (Transact-SQL)
sys.syslanguages (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_denylogin (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Prevents a Windows user or Windows group from connecting to an instance of SQL Server.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER LOGIN instead.

Transact-SQL Syntax Conventions

Syntax
sp_denylogin [ @loginame = ] 'login'

Arguments
[ @loginame = ] 'login '
Is the name of a Windows user or group. login is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_denylogin denies CONNECT SQL permission to the server-level principal mapped to the specified Windows
user or Windows group. If the server principal does not exist, it will be created. The new principal will be visible in
the sys.server_principals (Transact-SQL) catalog view.
sp_denylogin cannot be executed within a user-defined transaction.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example shows how to use sp_denylogin to prevent Windows user CORPORATE\GeorgeV from
connecting to the server.

EXEC sp_denylogin 'CORPORATE\GeorgeV';


See Also
sp_grantlogin (Transact-SQL)
Security Stored Procedures (Transact-SQL)
ALTER LOGIN (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_describe_parameter_encryption (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Analyzes the specified Transact-SQL statement and its parameters, to determine which parameters correspond to
database columns that are protected by using the Always Encrypted feature. Returns encryption metadata for the
parameters that correspond to encrypted columns.

Syntax
sp_describe_parameter_encryption
[ @tsql = ] N'Transact-SQL_batch' ,
[ @params = ] N'parameters'
[ ;]

Arguments
[ @tsql = ] 'Transact-SQL_batch'
One or more Transact-SQL statements. Transact-SQL_batch may be nvarchar(n) or nvarchar(max).
[ @params = ] N'parameters'
@params provides a declaration string for parameters for the Transact-SQL batch, which is similar to
sp_executesql. Parameters may be nvarchar(n) or nvarchar(max).
Is one string that contains the definitions of all parameters that have been embedded in the Transact-SQL_batch.
The string must be either a Unicode constant or a Unicode variable. Each parameter definition consists of a
parameter name and a data type. n is a placeholder that indicates additional parameter definitions. Every
parameter specified in the statement must be defined in @params. If the Transact-SQL statement or batch in the
statement does not contain parameters, @params is not required. NULL is the default value for this parameter.

Return Value
0 indicates success. Anything else indicate failure.

Result Sets
sp_describe_parameter_encryption returns two result sets:
The result set describing cryptographic keys configured for database columns, the parameters of the
specified Transact-SQL statement correspond to.
The result set describing how particular parameters should be encrypted. This result set references the keys
described in the first result set.
Each row of the first result set describes a pair of keys; an encrypted column encryption key and its
corresponding column master key.
COLUMN NAME DATA TYPE DESCRIPTION

column_encryption_key_ordinal int Id of the row in the resultset.

database_id int Database id.

column_encryption_key_id int The column encryption key id. Note: this


id denotes a row in the
sys.column_encryption_keys (Transact-
SQL) catalog view.

column_encryption_key_version int Reserved for future use. Currently,


always contains 1.

column_encryption_key_metadata_v binary(8) A timestamp representing the creation


ersion time of the column encryption key.

column_encryption_key_encrypted_v varbinary(4000) The encrypted value of the column


alue encryption key.

column_master_key_store_provider_ sysname The name of the provider for the key


name store that contains the column master
key, which was used to produce the
encrypted value of the column
encryption key.

column_master_key_path nvarchar(4000) The key path of the column master key,


which was used to produce the
encrypted value of the column
encryption key.

column_encryption_key_encryption_ sysname The name of the encryption algorithm


algorithm_name used to produce the encryption value of
the column encryption key.

Each row of the second result set contains encryption metadata for one parameter.

COLUMN NAME DATA TYPE DESCRIPTION

parameter_ordinal int Id of the row in the result set.

parameter_name sysname Name of one of the parameters


specified in the @params argument.

column_encryption_algorithm tinyint Code indicating the encryption


algorithm configured for the column,
the parameter corresponds to. The
currently supported values are: 2 for
AEAD_AES_256_CBC_HMAC_SHA_256
.
COLUMN NAME DATA TYPE DESCRIPTION

column_encryption_type tinyint Code indicating the encryption type


configured for the column, the
parameter corresponds to. The
supported values are:

0 – plaintext (the column is not


encrypted)

1 – randomized encryption

2 – deterministic encryption.

column_encryption_key_ordinal int Code of the row in the first result set.


The referenced row describes the
column encryption key configured for
the column, the parameter corresponds
to.

column_encryption_normalization_r tinyint Version number of the type


ule_version normalization algorithm.

Remarks
A SQL Server client driver, supporting Always Encrypted, automatically calls sp_describe_parameter_encryption
to retrieve encryption metadata for parameterized queries, issued by the application. Subsequently, the driver uses
the encryption metadata to encrypt the values of parameters that correspond to database columns protected with
Always Encrypted and substitutes the plaintext parameter values, submitted by the application, with the encrypted
parameter values, before sending the query to the database engine.

Permissions
Require the VIEW ANY COLUMN ENCRYPTION KEY DEFINITION and VIEW ANY COLUMN MASTER KEY
DEFINITION permissions in the database.

Examples
CREATE COLUMN MASTER KEY [CMK1]
WITH
(
KEY_STORE_PROVIDER_NAME = N'MSSQL_CERTIFICATE_STORE',
KEY_PATH = N'CurrentUser/my/A66BB0F6DD70BDFF02B62D0F87E340288E6F9305'
);
GO

CREATE COLUMN ENCRYPTION KEY [CEK1]


WITH VALUES
(
COLUMN_MASTER_KEY = [CMK1],
ALGORITHM = 'RSA_OAEP',
ENCRYPTED_VALUE =
0x016E000001630075007200720065006E00740075007300650072002F006D007
9002F00610036003600620062003000660036006400640037003000620064006
6006600300032006200360032006400300066003800370065003300340030003
200380038006500360066003900330030003500CA0D0CEC74ECADD1804CF991
37B4BD06BBAB15D7EA74E0C249A779C7768A5B659E0125D24FF827F5EA8CA51
7A8E197ECA1353BA814C2B0B2E6C8AB36E3AE6A1E972D69C3C573A963ADAB6
686CF5D24F95FE43140C4F9AF48FBA7DF2D053F3B4A1F5693A1F905440F8015B
DB43AF8A04BE4E045B89876A0097E5FBC4E6A3B9C3C0D278C540E46C53938B8
C957B689C4DC095821C465C73117CBA95B758232F9E5B2FCC7950B8CA00AFE3
74DE42847E3FBC2FDD277035A2DEF529F4B735C20D980073B4965B4542A3472
3276A1646998FC6E1C40A3FDB6ABCA98EE2B447F114D2AC7FF8C7D51657550E
C5C2BABFFE8429B851272086DCED94332CF18FA854C1D545A28B1EF4BE64F8E0
35175C1650F6FC5C4702ACF99850A4542B3747EAEC0CC726E091B36CE24392D8
01ECAA684DE344FECE05812D12CD72254A014D42D0EABDA41C89FC4F545E88B
4B8781E5FAF40D7199D4842D2BFE904D209728ED4F527CBC169E2904F6E711FF8
1A8F4C25382A2E778DD2A58552ED031AFFDA9D9D891D98AD82155F93C58202F
C24A77F415D4F8EF22419D62E188AC609330CCBD97CEE1AEF8A18B0195883360
4707FDF03B2B386487CC679D7E352D0B69F9FB002E51BCD814D077E82A09C14E
9892C1F8E0C559CFD5FA841CEF647DAB03C8191DC46B772E94D579D8C80FE93C
3827C9F0AE04D5325BC73111E07EEEDBE67F1E2A73580085
);
GO

CREATE TABLE t1 (
c1 INT ENCRYPTED WITH (
COLUMN_ENCRYPTION_KEY = [CEK_Auto1],
ENCRYPTION_TYPE = Randomized,
ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL,
);

EXEC sp_describe_parameter_encryption N'INSERT INTO t1 VALUES(@c1)', N'@c1 INT';

Here is the first result set:

COLUMN_ENCRYPT COLUMN_ENCRYPT
COLUMN_ENCRYPT COLUMN_ENCRYPT COLUMN_ENCRYPT ION_KEY_METADAT ION_KEY_ENCRYPT
ION_KEY_ORDINAL DATABASE_ID ION_KEY_ID ION_KEY_VERSION A_VERSION ED_VALUE

1 5 1 1 0x99EDA60083A 0x016E00000163
50000 0075007200720
065006E007400
7500730065007
2002F006D0079
002F006100360
0360062006200
3000660036006
4006400370030
0062006400660
0660030003200
6200360032006
4003000660038
0037006500330
0037006500330
COLUMN_ENCRYPT 0340030003200
COLUMN_ENCRYPT
COLUMN_ENCRYPT COLUMN_ENCRYPT COLUMN_ENCRYPT ION_KEY_METADAT 3800380065003
ION_KEY_ENCRYPT
ION_KEY_ORDINAL DATABASE_ID ION_KEY_ID ION_KEY_VERSION A_VERSION ED_VALUE
6006600390033
0030003500CA0
D0CEC74ECADD
1804CF99137B4
BD06BBAB15D7E
A74E0C249A779
C7768A5B659E0
125D24FF827F5
EA8CA517A8E19
7ECA1353BA814
C2B0B2E6C8AB3
6E3AE6A1E972D
69C3C573A963A
DAB6686CF5D24
F95FE43140C4F9
AF48FBA7DF2D0
53F3B4A1F5693
A1F905440F801
5BDB43AF8A04B
E4E045B89876A
0097E5FBC4E6A
3B9C3C0D278C5
40E46C53938B8
C957B689C4DC0
95821C465C731
17CBA95B75823
2F9E5B2FCC795
0B8CA00AFE374
DE42847E3FBC2
FDD277035A2DE
F529F4B735C20
D980073B4965B
4542A34723276
A1646998FC6E1
C40A3FDB6ABC
A98EE2B447F11
4D2AC7FF8C7D5
1657550EC5C2B
ABFFE8429B851
272086DCED943
32CF18FA854C1
D545A28B1EF4B
E64F8E035175C
1650F6FC5C470
2ACF99850A454
2B3747EAEC0CC
726E091B36CE2
4392D801ECAA6
84DE344FECE05
812D12CD72254
A014D42D0EAB
DA41C89FC4F54
5E88B4B8781E5F
AF40D7199D484
2D2BFE904D209
728ED4F527CBC
169E2904F6E711
FF81A8F4C2538
2A2E778DD2A58
552ED031AFFDA
9D9D891D98AD
82155F93C5820
2FC24A77F415D
4F8EF22419D62
COLUMN_ENCRYPT COLUMN_ENCRYPT
COLUMN_ENCRYPT COLUMN_ENCRYPT COLUMN_ENCRYPT ION_KEY_METADAT E188AC609330C
ION_KEY_ENCRYPT
ION_KEY_ORDINAL DATABASE_ID ION_KEY_ID ION_KEY_VERSION A_VERSION CBD97CEE1AEF8
ED_VALUE
A18B019588336
04707FDF03B2B
386487CC679D7
E352D0B69F9FB
002E51BCD814D
077E82A09C14E
9892C1F8E0C55
9CFD5FA841CEF
647DAB03C8191
DC46B772E94D5
79D8C80FE93C3
827C9F0AE04D5
325BC73111E07
EEEDBE67F1E2A7
3580085

(Results continue.)

COLUMN_MASTER_KEY_STORE_PROVIDER_ COLUMN_ENCRYPTION_KEY_ENCRYPTION_A
NAME COLUMN_MASTER_KEY_PATH LGORITHM_NAME

MSSQL_CERTIFICATE_STORE CurrentUser/my/A66BB0F6DD70BDFF0 RSA_OAEP


2B62D0F87E340288E6F9305

Here is the second result set:

COLUMN_ENCRYPTION_ALGOR
PARAMETER_ORDINAL PARAMETER_NAME ITHM COLUMN_ENCRYPTION_TYPE

1 @c1 1 1

(Results continue.)

COLUMN_ENCRYPTION_KEY_ORDINAL COLUMN_ENCRYPTION_NORMALIZATION_RULE_VERSION

1 1

See Also
Always Encrypted (Database Engine)
Always Encrypted (client development)
sys.sp_drop_trusted_assembly (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2017) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops an assembly from the list of trusted assemblies on the server.
Transact-SQL Syntax Conventions

Syntax
sp_drop_trusted_assembly
[ @hash = ] 'value'

Arguments
[ @hash = ] 'value'
The SHA2_512 hash value of the assembly to drop from the list of trusted assemblies for the server. Trusted
assemblies may load when clr strict security is enabled, even if the assembly is unsigned or the database is not
marked as trustworthy.

Remarks
This procedure removes an assembly from sys.trusted_assemblies.

Permissions
Requires membership in the sysadmin fixed server role or CONTROL SERVER permission.

Examples
The following example drops an assembly hash from the list of trusted assemblies for the server.

EXEC sp_drop_trusted_assembly
0x8893AD6D78D14EE43DF482E2EAD44123E3A0B684A8873C3F7BF3B5E8D8F09503F3E62370CE742BBC96FE3394477214B84C7C1B0F7A04
DCC788FA99C2C09DFCCC;

See Also
sys.sp_add_trusted_assembly sys.trusted_assemblies DROP ASSEMBLY (Transact-SQL)
sys.assemblies
sys.dm_clr_loaded_assemblies
sp_dropalias (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
sp_dropalias was removed for SQL Server 2012. For syntax, see sp_dropalias (Transact-SQL) in earlier
documentation.

Syntax
See previous version.

Remarks
sp_dropapprole (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes an application role from the current database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use DROP APPLICATION ROLE instead.

Transact-SQL Syntax Conventions

Syntax
sp_dropapprole [@rolename = ] 'role'

Arguments
[ @rolename = ] 'role'
Is the application role to remove. role is a sysname, with no default. role must exist in the current database.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropapprole can only be used to remove application roles. If a role owns any securables, the role cannot be
dropped. Before dropping an application role that owns securables, you must first transfer ownership of the
securables, or drop them.
sp_dropapprole cannot be executed within a user-defined transaction.

Permissions
Requires ALTER ANY APPLICATION ROLE permission on the database.

Examples
The following example removes the SalesApp application role from the current database.

EXEC sp_dropapprole 'SalesApp';

See Also
Security Stored Procedures (Transact-SQL)
sp_addapprole (Transact-SQL)
DROP APPLICATION ROLE (Transact-SQL)
sp_changeobjectowner (Transact-SQL)
sp_setapprole (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_droplogin (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a SQL Server login. This prevents access to an instance of SQL Server under that login name.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use DROP LOGIN instead.

Transact-SQL Syntax Conventions

Syntax
sp_droplogin [ @loginame = ] 'login'

Arguments
[ @loginame = ] 'login'
Is the login to be removed. login is sysname, with no default. login must already exist in SQL Server.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_droplogin calls DROP LOGIN.
sp_droplogin cannot be executed within a user-defined transaction.

Permissions
Requires ALTER ANY LOGIN permission on the server.

Examples
The following example uses DROP LOGIN to remove the login Victoria from an instance of SQL Server. This is the
preferred method.

DROP LOGIN Victoria;


GO

See Also
Security Stored Procedures (Transact-SQL)
DROP LOGIN (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_dropremotelogin (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a remote login mapped to a local login used to execute remote stored procedures against the local
server running SQL Server.

IMPORTANT
This feature will be removed in the next version of Microsoft SQL Server. Do not use this feature in new development work,
and modify applications that currently use this feature as soon as possible. Use linked servers and linked-server stored
procedures instead.

Transact-SQL Syntax Conventions

Syntax
sp_dropremotelogin [ @remoteserver = ] 'remoteserver'
[ , [ @loginame = ] 'login' ]
[ , [ @remotename = ] 'remote_name' ]

Arguments
[ @remoteserver = ] 'remoteserver'
Is the name of the remote server mapped to the remote login that is to be removed. remoteserver is sysname,
with no default. remoteserver must already exist.
[ @loginame = ] 'login'
Is the optional login name on the local server that is associated with the remote server. login is sysname, with a
default of NULL. login must already exist if specified.
[ @remotename = ] 'remote_name'
Is the optional name of the remote login that is mapped to login when logging in from the remote server.
remote_name is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
If only remoteserver is specified, all remote logins for that remote server are removed from the local server. If
login is also specified, all remote logins from remoteserver mapped to that specific local login are removed from
the local server. If remote_name is also specified, only the remote login for that remote user from remoteserver is
removed from the local server.
To add local server users, use sp_addlogin. To remove local server users, use sp_droplogin.
Remote logins are required only when you use earlier versions of SQL Server. SQL Server version 7.0 and later
versions use linked server logins instead. Use sp_addlinkedsrvlogin and sp_droplinkedsrvlogin to add and
remove linked server logins.
sp_dropremotelogin cannot be executed within a user-defined transaction.

Permissions
Requires membership in the sysadmin or securityadmin fixed server roles.

Examples
A. Dropping all remote logins for a remote server
The following example removes the entry for the remote server ACCOUNTS , and, therefore, removes all mappings
between logins on the local server and remote logins on the remote server.

EXEC sp_dropremotelogin 'ACCOUNTS';

B. Dropping a login mapping


The following example removes the entry for mapping remote logins from the remote server ACCOUNTS to the
local login Albert .

EXEC sp_dropremotelogin 'ACCOUNTS', 'Albert';

C. Dropping a remote user


The following example removes the login for the remote login Chris on the remote server ACCOUNTS that was
mapped to the local login salesmgr .

EXEC sp_dropremotelogin 'ACCOUNTS', 'salesmgr', 'Chris';

See Also
Security Stored Procedures (Transact-SQL)
sp_addlinkedsrvlogin (Transact-SQL)
sp_addlogin (Transact-SQL)
sp_addremotelogin (Transact-SQL)
sp_addserver (Transact-SQL)
sp_droplinkedsrvlogin (Transact-SQL)
sp_droplogin (Transact-SQL)
sp_helpremotelogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_droprole (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a database role from the current database.

IMPORTANT
In SQL Server 2005, sp_droprole was replaced by the DROP ROLE statement. sp_droprole is included only for
compatibility with earlier versions of SQL Server and may not be supported in a future release.

Transact-SQL Syntax Conventions

Syntax
sp_droprole [ @rolename= ] 'role'

Arguments
[ @rolename = ] 'role'
Is the name of the database role to remove from the current database. role is a sysname, with no default. role
must already exist in the current database.

Return Code Values


0 (success) or 1 (failure)

Remarks
Only database roles can be removed by using sp_droprole.
A database role with existing members cannot be removed. All members of a database role must be removed
before the database role can be removed. To remove users from a role, use sp_droprolemember. If any users are
still members of the role, sp_droprole displays those members.
Fixed roles and the public role cannot be removed.
A role cannot be removed if it owns any securables. Before dropping an application role that owns securables, you
must first transfer ownership of the securables, or drop them. Use ALTER AUTHORIZATION to change the owner of
objects that must not be removed.
sp_droprole cannot be executed within a user-defined transaction.

Permissions
Requires CONTROL permission on the role.
Examples
The following example removes the application role Sales .

EXEC sp_droprole 'Sales';


GO

See Also
Security Stored Procedures (Transact-SQL)
sp_addrole (Transact-SQL)
DROP ROLE (Transact-SQL)
ALTER AUTHORIZATION (Transact-SQL)
sp_dropapprole (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_droprolemember (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a security account from a SQL Server role in the current database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER ROLE instead.

Transact-SQL Syntax Conventions

Syntax
-- Syntax for SQL Server and Azure SQL Database

sp_droprolemember [ @rolename = ] 'role' ,


[ @membername = ] 'security_account'

-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse

sp_droprolemember 'role' ,
'security_account'

Arguments
[ @rolename = ] 'role'
Is the name of the role from which the member is being removed. role is sysname, with no default. role must exist
in the current database.
[ @membername = ] 'security_account'
Is the name of the security account being removed from the role. security_account is sysname, with no default.
security_account can be a database user, another database role, a Windows login, or a Windows group.
security_account must exist in the current database.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_droprolemember removes a member from a database role by deleting a row from the sysmembers table.
When a member is removed from a role the member loses any permissions it has by membership in that role.
To remove a user from a fixed server role, use sp_dropsrvrolemember. Users cannot be removed from the public
role, and dbo cannot be removed from any role.
Use sp_helpuser to see the members of a SQL Server role, and use ALTER ROLE to add a member to a role.
Permissions
Requires ALTER permission on the role.

Examples
The following example removes the user JonB from the role Sales .

EXEC sp_droprolemember 'Sales', 'Jonb';

Examples: Azure SQL Data Warehouse and Parallel Data Warehouse


The following example removes the user JonB from the role Sales .

EXEC sp_droprolemember 'Sales', 'JonB'

See Also
Security Stored Procedures (Transact-SQL)
sp_addrolemember (Transact-SQL)
sp_droprole (Transact-SQL)
sp_dropsrvrolemember (Transact-SQL)
sp_helpuser (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_dropserver (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a server from the list of known remote and linked servers on the local instance of SQL Server.
Transact-SQL Syntax Conventions

Syntax
sp_dropserver [ @server = ] 'server'
[ , [ @droplogins = ] { 'droplogins' | NULL} ]

Arguments
[ @server = ] 'server'
Is the server to be removed. server is sysname, with no default. server must exist.
[ @droplogins = ] 'droplogins' | NULL
Indicates that related remote and linked server logins for server must also be removed if droplogins is specified.
@droplogins is char(10), with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
If you run sp_dropserver on a server that has associated remote and linked server login entries, or is configured
as a replication publisher, an error message is returned. To remove all remote and linked server logins for a server
when you remove the server, use the droplogins argument.
sp_dropserver cannot be executed inside a user-defined transaction.

Permissions
Requires ALTER ANY LINKED SERVER permission on the server.

Examples
The following example removes the remote server ACCOUNTS and all associated remote logins from the local
instance of SQL Server.

sp_dropserver 'ACCOUNTS', 'droplogins';

See Also
Security Stored Procedures (Transact-SQL)
sp_addserver (Transact-SQL)
sp_dropremotelogin (Transact-SQL)
sp_helpremotelogin (Transact-SQL)
sp_helpserver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_dropsrvrolemember (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a SQL Server login or a Windows user or group from a fixed server role.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER SERVER ROLE instead.

Transact-SQL Syntax Conventions

Syntax
sp_dropsrvrolemember [ @loginame = ] 'login' , [ @rolename = ] 'role'

Arguments
[ @loginame = ] 'login'
Is the name of a login to remove from the fixed server role. login is sysname, with no default. login must exist.
[ @rolename = ] 'role'
Is the name of a server role. role is sysname, with a default of NULL. role must be one of the following values:
sysadmin
securityadmin
serveradmin
setupadmin
processadmin
diskadmin
dbcreator
bulkadmin

Return Code Values


0 (success) or 1 (failure)

Remarks
Only sp_dropsrvrolemember can be used to remove a login from a fixed server role. Use sp_droprolemember to
remove a member from a database role.
The sa login cannot be removed from any fixed server role.
sp_dropsrvrolemember cannot be executed within a user-defined transaction.

Permissions
Requires membership in the sysadmin fixed server role, or both ALTER ANY LOGIN permission on the server and
membership in the role from which the member is being dropped.

Examples
The following example removes the login JackO from the sysadmin fixed server role.

EXEC sp_dropsrvrolemember 'JackO', 'sysadmin';

See Also
CREATE SERVER ROLE (Transact-SQL)
DROP SERVER ROLE (Transact-SQL)
Security Stored Procedures (Transact-SQL)
sp_addsrvrolemember (Transact-SQL)
sp_droprolemember (Transact-SQL)
System Stored Procedures (Transact-SQL)
Security Functions (Transact-SQL)
sp_dropuser (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a database user from the current database. sp_dropuser provides compatibility with earlier versions of
SQL Server.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use DROP USER instead.

Transact-SQL Syntax Conventions

Syntax
sp_dropuser [ @name_in_db = ] 'user'

Arguments
[ @name_in_db =] 'user'
Is the name of the user to remove. user is a sysname, with no default. user must exist in the current database.
When specifying a Windows login, use the name by which the database knows that login.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropuser executes sp_revokedbaccess to remove the user from the current database.
Use sp_helpuser to display a list of the user names that can be removed from the current database.
When a database user is removed, any aliases to that user are also removed. If the user owns an empty schema
with the same name as the user, the schema will be dropped. If the user owns any other securables in the
database, the user will not be dropped. Ownership of the objects must first be transferred to another principal. For
more information, see ALTER AUTHORIZATION (Transact-SQL). Removing a database user automatically removes
the permissions associated with that user and removes the user from any database roles of which it is a member.
sp_dropuser cannot be used to remove the database owner (dbo) INFORMATION_SCHEMA users, or the guest
user from the master or tempdb databases. In nonsystem databases, EXEC sp_dropuser 'guest' will revoke
CONNECT permission from user guest. But the user itself will not be dropped.
sp_dropuser cannot be executed within a user-defined transaction.

Permissions
Requires ALTER ANY USER permission on the database.

Examples
The following example removes the user Albert from the current database.

EXEC sp_dropuser 'Albert';


GO

See Also
Security Stored Procedures (Transact-SQL)
sp_grantdbaccess (Transact-SQL)
DROP USER (Transact-SQL)
sp_revokedbaccess (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_grantdbaccess (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a database user to the current database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use CREATE USER instead.

Transact-SQL Syntax Conventions

Syntax
sp_grantdbaccess [ @loginame = ] 'login'
[ , [ @name_in_db = ] 'name_in_db' [ OUTPUT ] ]

Arguments
[ @loginame = ] 'login '
Is the name of the Windows group, Windows login or SQL Server login to be mapped to the new database user.
Names of Windows groups and Windows logins must be qualified with a Windows domain name in the form
Domain\login; for example, LONDON\Joeb. The login cannot already be mapped to a user in the database. login
is a sysname, with no default.
[ @name_in_db=] 'name_in_db' [ OUTPUT]
Is the name for the new database user. name_in_db is an OUTPUT variable with a data type of sysname, and a
default of NULL. If not specified, login is used. If specified as an OUTPUT variable with a value of NULL,
@name_in_db is set to login. name_in_db must not already exist in the current database.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_grantdbaccess calls CREATE USER, which supports additional options. For information about creating
database users, see CREATE USER (Transact-SQL). To remove a database user from a database, use DROP USER.
sp_grantdbaccess cannot be executed within a user-defined transaction.

Permissions
Requires membership in the db_owner fixed database role or the db_accessadmin fixed database role.

Examples
The following example uses CREATE USER to add a database user for the Windows login Edmonds\LolanSo to the
current database. The new user is named Lolan . This is the preferred method for creating a database user.

CREATE USER Lolan FOR LOGIN [Edmonds\LolanSo];


GO

See Also
Security Stored Procedures (Transact-SQL)
CREATE USER (Transact-SQL)
DROP USER (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_grantlogin (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a SQL Server login.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development
work, and plan to modify applications that currently use this feature. Use CREATE LOGIN instead.

Transact-SQL Syntax Conventions

Syntax
sp_grantlogin [@loginame=] 'login'

Arguments
[ @loginame = ] 'login'
Is the name of a Windows user or group. The Windows user or group must be qualified with a Windows domain
name in the form Domain\User; for example, London\Joeb. login is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_grantlogin calls CREATE LOGIN, which supports additional options. For information on creating SQL Server
logins, see CREATE LOGIN (Transact-SQL)
sp_grantlogin cannot be executed within a user-defined transaction.

Permissions
Requires ALTER ANY LOGIN permission on the server.

Examples
The following example uses CREATE LOGIN to create a SQL Server login for the Windows user Corporate\BobJ.
This is the preferred method.

CREATE LOGIN [Corporate\BobJ] FROM WINDOWS;


GO
See Also
Security Stored Procedures (Transact-SQL)
CREATE LOGIN (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpdbfixedrole (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns a list of the fixed database roles.
Transact-SQL Syntax Conventions

Syntax
sp_helpdbfixedrole [ [ @rolename = ] 'role' ]

Arguments
[ @rolename = ] 'role'
Is the name of a fixed database role. role is sysname, with a default of NULL. If role is specified, only information
about that role is returned; otherwise, a list and description of all fixed database roles is returned.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

DbFixedRole sysname Name of the fixed database role.

Description nvarchar(70) Description of DbFixedRole.

Remarks
Fixed database roles, as shown in the following table, are defined at the database level and have permissions to
perform specific database-level administrative activities. Fixed database roles cannot be added or removed. The
permissions granted to a fixed database role cannot be changed.

FIXED DATABASE ROLE DESCRIPTION

db_owner Database owners

db_accessadmin Database access administrators

db_securityadmin Database security administrators

db_ddladmin Database DDL administrators


FIXED DATABASE ROLE DESCRIPTION

db_backupoperator Database backup operators

db_datareader Database data readers

db_datawriter Database data writers

db_denydatareader Database deny data readers

db_denydatawriter Database deny data writers

The following table shows stored procedures that are used for modifying database roles.

STORED PROCEDURE ACTION

sp_addrolemember Adds a database user to a fixed database role.

sp_helprole Displays a list of the members of a fixed database role.

sp_droprolemember Removes a member from a fixed database role.

Permissions
Requires membership in the public role.
Information returned is subject to restrictions on access to metadata. Entities on which the principal has no
permission do not appear. For more information, see Metadata Visibility Configuration.

Examples
The following example shows a list of all fixed database roles.

EXEC sp_helpdbfixedrole;
GO

See Also
Security Stored Procedures (Transact-SQL)
sp_addrolemember (Transact-SQL)
sp_dbfixedrolepermission (Transact-SQL)
sp_droprolemember (Transact-SQL)
sp_helprole (Transact-SQL)
sp_helprolemember (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helplinkedsrvlogin (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Provides information about login mappings defined against a specific linked server used for distributed queries
and remote stored procedures.
Transact-SQL Syntax Conventions

Syntax
sp_helplinkedsrvlogin [ [ @rmtsrvname = ] 'rmtsrvname' ]
[ , [ @locallogin = ] 'locallogin' ]

Arguments
[ @rmtsrvname=] 'rmtsrvname'
Is the name of the linked server that the login mapping applies to. rmtsrvname is sysname, with a default of NULL.
If NULL, all login mappings defined against all the linked servers defined in the local computer running SQL Server
are returned.
[ @locallogin=] 'locallogin'
Is the SQL Server login on the local server that has a mapping to the linked server rmtsrvname. locallogin is
sysname, with a default of NULL. NULL specifies that all login mappings defined on rmtsrvname are returned. If
not NULL, a mapping for locallogin to rmtsrvname must already exist. locallogin can be a SQL Server login or a
Windows user. The Windows user must have been granted access to SQL Server either directly or through its
membership in a Windows group that has been granted access.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

Linked Server sysname Linked server name.

Local Login sysname Local login for which the mapping


applies.

Is Self Mapping smallint 0 = Local Login is mapped to Remote


Login when connecting to Linked
Server.

1 = Local Login is mapped to the same


login and password when connecting to
Linked Server.
COLUMN NAME DATA TYPE DESCRIPTION

Remote Login sysname Login name on LinkedServer that is


mapped to LocalLogin when
IsSelfMapping is 0. If IsSelfMapping
is 1, RemoteLogin is NULL.

Remarks
Before you delete login mappings, use sp_helplinkedsrvlogin to determine the linked servers that are involved.

Permissions
No permissions are checked.

Examples
A. Displaying all login mappings for all linked servers
The following example displays all login mappings for all linked servers defined on the local computer running SQL
Server.

EXEC sp_helplinkedsrvlogin;
GO

Here is the result set.

Linked Server Local Login Is Self Mapping Remote Login


---------------- ------------- --------------- --------------
Accounts NULL 1 NULL
Sales NULL 1 NULL
Sales Mary 0 sa
Marketing NULL 1 NULL

(4 row(s) affected)

B. Displaying all login mappings for a linked server


The following example displays all locally defined login mappings for the Sales linked server.

EXEC sp_helplinkedsrvlogin 'Sales';


GO

Here is the result set.

Linked Server Local Login Is Self Mapping Remote Login


---------------- ------------- --------------- --------------
Sales NULL 1 NULL
Sales Mary 0 sa

(2 row(s) affected)

C. Displaying all login mappings for a local login


The following example displays all locally defined login mappings for the login Mary .
EXEC sp_helplinkedsrvlogin NULL, 'Mary';
GO

Here is the result set.

Linked Server Local Login Is Self Mapping Remote Login


---------------- ------------- --------------- --------------
Sales NULL 1 NULL
Sales Mary 0 sa

(2 row(s) affected)

See Also
Security Stored Procedures (Transact-SQL)
sp_addlinkedserver (Transact-SQL)
sp_droplinkedsrvlogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helplogins (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Provides information about logins and the users associated with them in each database.
Transact-SQL Syntax Conventions

Syntax
sp_helplogins [ [ @LoginNamePattern = ] 'login' ]

Arguments
[ @LoginNamePattern = ] 'login'
Is a login name. login is sysname, with a default of NULL. login must exist if specified. If login is not specified,
information about all logins is returned.

Return Code Values


0 (success) or 1 (failure)

Result Sets
The first report contains information about each login specified, as shown in the following table.

COLUMN NAME DATA TYPE DESCRIPTION

LoginName sysname Login name.

SID varbinary(85) Login security identifier (SID).

DefDBName sysname Default database that LoginName uses


when connecting to an instance of SQL
Server.

DefLangName sysname Default language used by LoginName.

Auser char(5) Yes = LoginName has an associated


user name in a database.

No = LoginName does not have an


associated user name.
COLUMN NAME DATA TYPE DESCRIPTION

ARemote char(7) Yes = LoginName has an associated


remote login.

No = LoginName does not have an


associated login.

The second report contains information about users mapped to each login, and the role memberships of the login
as shown in the following table.

COLUMN NAME DATA TYPE DESCRIPTION

LoginName sysname Login name.

DBName sysname Default database that LoginName uses


when connecting to an instance of SQL
Server.

UserName sysname User account that LoginName is


mapped to in DBName, and the roles
that LoginName is a member of in
DBName.

UserOrAlias char(8) MemberOf = UserName is a role.

User = UserName is a user account.

Remarks
Before removing a login, use sp_helplogins to identify user accounts that are mapped to the login.

Permissions
Requires membership in the securityadmin fixed server role.
To identify all user accounts mapped to a given login, sp_helplogins must check all databases within the server.
Therefore, for each database on the server, at least one of the following conditions must be true:
The user that is executing sp_helplogins has permission to access the database.
The guest user account is enabled in the database.
If sp_helplogins cannot access a database, sp_helplogins will return as much information as it can and
display error message 15622.

Examples
The following example reports information about the login John .
EXEC sp_helplogins 'John';
GO

LoginName SID DefDBName DefLangName AUser ARemote


--------- -------------------------- --------- ----------- ----- -------
John 0x23B348613497D11190C100C master us_english yes no

(1 row(s) affected)

LoginName DBName UserName UserOrAlias


--------- ------ -------- -----------
John pubs John User

(1 row(s) affected)

See Also
Security Stored Procedures (Transact-SQL)
sp_helpdb (Transact-SQL)
sp_helpuser (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpntgroup (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Reports information about Windows groups with accounts in the current database.
Transact-SQL Syntax Conventions

Syntax
sp_helpntgroup [ [ @ntname= ] 'name' ]

Arguments
[ @ntname = ] 'name'
Is the name of the Windows group. name is sysname, with a default of NULL. name must be a valid Windows
group with access to the current database. If name is not specified, all Windows groups with access to the current
database are included in the output.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

NTGroupName sysname Name of the Windows group.

NTGroupId smallint Group identifier (ID).

SID varbinary(85) Security identifier (SID) of


NTGroupName.

HasDbAccess int 1 = Windows group has permission to


access the database.

Remarks
To see a list of the SQL Server roles in the current database, use sp_helprole.

Permissions
Requires membership in the public role.

Examples
The following example prints a list of the Windows groups with access to the current database.

EXEC sp_helpntgroup;

See Also
Security Stored Procedures (Transact-SQL)
sp_grantdbaccess (Transact-SQL)
sp_helprole (Transact-SQL)
sp_revokedbaccess (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpremotelogin (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports information about remote logins for a particular remote server, or for all remote servers, defined on the
local server.

IMPORTANT
This feature will be removed in the next version of Microsoft SQL Server. Do not use this feature in new development work,
and modify applications that currently use this feature as soon as possible. Use linked servers and linked server stored
procedures instead.

Transact-SQL Syntax Conventions

Syntax
sp_helpremotelogin [ [ @remoteserver = ] 'remoteserver' ]
[ , [ @remotename = ] 'remote_name' ]

Arguments
[ @remoteserver = ] 'remoteserver'
Is the remote server about which the remote login information is returned. remoteserver is sysname, with a
default of NULL. If remoteserver is not specified, information about all remote servers defined on the local server
is returned.
[ @remotename = ] 'remote_name'
Is a specific remote login on the remote server. remote_name is sysname, with a default of NULL. If remote_name
is not specified, information about all remote users defined for remoteserver is returned.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

server sysname Name of a remote server defined on


the local server.

local_user_name sysname Login on the local server that remote


logins from server map to.
COLUMN NAME DATA TYPE DESCRIPTION

remote_user_name sysname Login on the remote server that maps


to local_user_name.

options sysname Trusted = The remote login does not


need to supply a password when
connecting to the local server from the
remote server.

Untrusted (or blank) = The remote


login is prompted for a password when
connecting to the local server from the
remote server.

Remarks
Use sp_helpserver to list the names of remote servers defined on the local server.

Permissions
No permissions are checked.

Examples
A. Reporting help on a single server
The following example displays information about all remote users on the remote server Accounts .

EXEC sp_helpremotelogin 'Accounts';

B. Reporting help on all remote users


The following example displays information about all remote users on all remote servers known to the local
server.

EXEC sp_helpremotelogin;

See Also
sp_addremotelogin (Transact-SQL)
sp_dropremotelogin (Transact-SQL)
sp_helpserver (Transact-SQL)
sp_remoteoption (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helprole (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about the roles in the current database.
Transact-SQL Syntax Conventions

Syntax
sp_helprole [ [ @rolename = ] 'role' ]

Arguments
[ @rolename = ] 'role'
Is the name of a role in the current database. role is sysname, with a default of NULL. role must exist in the current
database. If role is not specified, information about all roles in the current database is returned.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

RoleName sysname Name of the role in the current


database.

RoleId smallint ID of RoleName.

IsAppRole int 0 = RoleName is not an application


role.

1 = RoleName is an application role.

Remarks
To view the permissions associated with the role, use sp_helprotect. To view the members of a database role, use
sp_helprolemember.

Permissions
Requires membership in the public role.

Examples
The following query returns all the roles in the current database.

EXEC sp_helprole

See Also
Security Stored Procedures (Transact-SQL)
Server-Level Roles
Database-Level Roles
sp_addapprole (Transact-SQL)
sp_addrole (Transact-SQL)
sp_droprole (Transact-SQL)
sp_helprolemember (Transact-SQL)
sp_helpsrvrolemember (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helprolemember (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about the direct members of a role in the current database.
Transact-SQL Syntax Conventions

Syntax
sp_helprolemember [ [ @rolename = ] 'role' ]

Arguments
[ @rolename = ] ' role '
Is the name of a role in the current database. role is sysname, with a default of NULL. role must exist in the current
database. If role is not specified, then all roles that contain at least one member from the current database are
returned.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

DbRole sysname Name of the role in the current


database.

MemberName sysname Name of a member of DbRole.

MemberSID varbinary(85) Security identifier of MemberName.

Remarks
If the database contains nested roles, MemberName may be the name of a role. sp_helprolemember does not
show membership obtained through nested roles. For example if User1 is a member of Role1, and Role1 is a
member of Role2, EXEC sp_helprolemember 'Role2' ; will return Role1, but not the members of Role1 (User1 in this
example). To return nested memberships, you must execute sp_helprolemember repeatedly for each nested role.
Use sp_helpsrvrolemember to display the members of a fixed server role.
Use IS_ROLEMEMBER (Transact-SQL) to check role membership for a specified user.

Permissions
Requires membership in the public role.

Examples
The following example displays the members of the Sales role.

EXEC sp_helprolemember 'Sales';

See Also
Security Stored Procedures (Transact-SQL)
sp_addrolemember (Transact-SQL)
sp_droprolemember (Transact-SQL)
sp_helprole (Transact-SQL)
sp_helpsrvrolemember (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helprotect (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns a report that has information about user permissions for an object, or statement permissions, in the
current database.

IMPORTANT
sp_helprotect does not return information about securables that were introduced in SQL Server 2005. Use
sys.database_permissions and fn_builtin_permissions instead.

Does not list permissions that are always assigned to the fixed server roles or fixed database roles. Does not
include logins or users that receive permissions based on their membership in a role.
Transact-SQL Syntax Conventions

Syntax
sp_helprotect [ [ @name = ] 'object_statement' ]
[ , [ @username = ] 'security_account' ]
[ , [ @grantorname = ] 'grantor' ]
[ , [ @permissionarea = ] 'type' ]

Arguments
[ @name = ] 'object_statement'
Is the name of the object in the current database, or a statement, that has the permissions to report.
object_statement is nvarchar(776), with a default of NULL, which returns all object and statement permissions. If
the value is an object (table, view, stored procedure, or extended stored procedure), it must be a valid object in the
current database. The object name can include an owner qualifier in the form owner.object.
If object_statement is a statement, it can be a CREATE statement.
[ @username = ] 'security_account'
Is the name of the principal for which permissions are returned. security_account is sysname, with a default of
NULL, which returns all principals in the current database. security_account must exist in the current database.
[ @grantorname = ] 'grantor'
Is the name of the principal that granted permissions. grantor is sysname, with a default of NULL, which returns
all information for permissions granted by any principal in the database.
[ @permissionarea = ] 'type'
Is a character string that indicates whether to display object permissions (character string o), statement
permissions (character string s), or both (os). type is varchar(10),with a default of os. type can be any combination
of o and s, with or without commas or spaces between o and s.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

Owner sysname Name of the object owner.

Object sysname Name of the object.

Grantee sysname Name of the principal to which


permissions were granted.

Grantor sysname Name of the principal that granted


permissions to the specified grantee.

ProtectType nvarchar(10) Name of the type of protection:

GRANT REVOKE

Action nvarchar(60) Name of the permission. Valid


permission statements depend upon
the type of object.

Column sysname Type of permission:

All = Permission covers all current


columns of the object.

New = Permission covers any new


columns that might be changed (by
using the ALTER statement) on the
object in the future.

All+New = Combination of All and New.

Returns a period if the type of


permission does not apply to columns.

Remarks
All the parameters in the following procedure are optional. If executed with no parameters, sp_helprotect displays
all the permissions that have been granted or denied in the current database.
If some but not all the parameters are specified, use named parameters to identify the particular parameter, or
NULL as a placeholder. For example, to report all permissions for the grantor database owner ( dbo ), execute the
following:

EXEC sp_helprotect NULL, NULL, dbo;

Or

EXEC sp_helprotect @grantorname = 'dbo';

The output report is sorted by permission category, owner, object, grantee, grantor, protection type category,
protection type, action, and column sequential ID.

Permissions
Requires membership in the public role.
Information returned is subject to restrictions on access to metadata. Entities on which the principal has no
permission do not appear. For more information, see Metadata Visibility Configuration.

Examples
A. Listing the permissions for a table
The following example lists the permissions for the titles table.

EXEC sp_helprotect 'titles';

B. Listing the permissions for a user


The following example lists all permissions that user Judy has in the current database.

EXEC sp_helprotect NULL, 'Judy';

C. Listing the permissions granted by a specific user


The following example lists all permissions that were granted by user Judy in the current database, and uses
NULL as a placeholder for the missing parameters.

EXEC sp_helprotect NULL, NULL, 'Judy';

D. Listing the statement permissions only


The following example lists all the statement permissions in the current database, and uses NULL as a placeholder
for the missing parameters.

EXEC sp_helprotect NULL, NULL, NULL, 's';

e. Listing the permissions for a CREATE statement


The following example list all users who have been granted the CREATE TABLE permission.

EXEC sp_helprotect @name = 'CREATE TABLE';

See Also
Security Stored Procedures (Transact-SQL)
DENY (Transact-SQL)
GRANT (Transact-SQL)
REVOKE (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpsrvrole (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a list of the SQL Server fixed server roles.
Transact-SQL Syntax Conventions

Syntax
sp_helpsrvrole [ [ @srvrolename = ] 'role' ]

Arguments
[ @srvrolename= ] 'role'
Is the name of the fixed server role. role is sysname, with a default of NULL. role can be one of the following
values.

FIXED SERVER ROLE DESCRIPTION

sysadmin System administrators

securityadmin Security administrators

serveradmin Server administrators

setupadmin Setup administrators

processadmin Process administrators

diskadmin Disk administrators

dbcreator Database creators

bulkadmin Can execute BULK INSERT statements

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

ServerRole sysname Name of the server role


COLUMN NAME DATA TYPE DESCRIPTION

Description sysname Description of ServerRole

Remarks
Fixed server roles are defined at the server level and have permissions to perform specific server-level
administrative activities. Fixed server roles cannot be added, removed, or changed.
To add or removed members from server roles, see ALTER SERVER ROLE (Transact-SQL).
All logins are a member of public. sp_helpsrvrole does not recognize the public role because, internally, SQL Server
does not implement public as a role.
sp_helpsrvrole does not take a user-defined server role as an argument. To list the user-defined server roles, see
the examples in ALTER SERVER ROLE (Transact-SQL).

Permissions
Requires membership in the public role.

Examples
A. Listing the fixed server roles
The following query returns the list of fixed server roles.

EXEC sp_helpsrvrole ;

B. Listing fixed and user-defined server roles


The following query returns a list of both fixed and user-defined server roles.

SELECT * FROM sys.server_principals WHERE type = 'R' ;

C. Returning a description of a fixed server role


The following query returns the name and description of the diskadmin fixed server roles.

sp_helpsrvrole 'diskadmin' ;

See Also
Security Stored Procedures (Transact-SQL)
Server-Level Roles
sp_addsrvrolemember (Transact-SQL)
sp_dropsrvrolemember (Transact-SQL)
sp_helpsrvrolemember (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpsrvrolemember (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about the members of a SQL Server fixed server role.
Transact-SQL Syntax Conventions

Syntax
sp_helpsrvrolemember [ [ @srvrolename = ] 'role' ]

Arguments
[ @srvrolename = ] 'role'
Is the name of a fixed server role. role is sysname, with a default of NULL. If roleis not specified, the result set
includes information about all fixed server roles.
role can be any of the following values.

FIXED SERVER ROLE DESCRIPTION

sysadmin System administrators

securityadmin Security administrators

serveradmin Server administrators

setupadmin Setup administrators

processadmin Process administrators

diskadmin Disk administrators

dbcreator Database creators

bulkadmin Can execute BULK INSERT statements

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

ServerRole sysname Name of the server role

MemberName sysname Name of a member of ServerRole

MemberSID varbinary(85) Security identifier of MemberName

Remarks
Use sp_helprolemember to display the members of a database role.
All logins are a member of public. sp_helpsrvrolemember does not recognize the public role because, internally,
SQL Server does not implement public as a role.
To add or removed members from server roles, see ALTER SERVER ROLE (Transact-SQL).
sp_helpsrvrolemember does not take a user-defined server role as an argument. To determine the members of a
user-defined server role, see the examples in ALTER SERVER ROLE (Transact-SQL).

Permissions
Requires membership in the public role.

Examples
The following example lists the members of the sysadmin fixed server role.

EXEC sp_helpsrvrolemember 'sysadmin';

See Also
sp_helprole (Transact-SQL)
sp_helprolemember (Transact-SQL)
System Stored Procedures (Transact-SQL)
Security Stored Procedures (Transact-SQL)
Security Functions (Transact-SQL)
sp_helpuser (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports information about database-level principals in the current database.

IMPORTANT
sp_helpuser does not return information about securables that were introduced in SQL Server 2005. Use
sys.database_principals instead.

Transact-SQL Syntax Conventions

Syntax
sp_helpuser [ [ @name_in_db = ] 'security_account' ]

Arguments
[ @name_in_db = ] 'security_account'
Is the name of database user or database role in the current database. security_account must exist in the current
database. security_account is sysname, with a default of NULL. If security_account is not specified, sp_helpuser
returns information about all database principals.

Return Code Values


0 (success) or 1 (failure)

Result Sets
The following table shows the result set when neither a user account nor a SQL Server or Windows user is
specified for security_account.

COLUMN NAME DATA TYPE DESCRIPTION

UserName sysname Users in the current database.

RoleName sysname Roles to which UserName belongs.

LoginName sysname Login of UserName.

DefDBName sysname Default database of UserName.

DefSchemaName sysname Default schema of the database user.


COLUMN NAME DATA TYPE DESCRIPTION

UserID smallint ID of UserName in the current


database.

SID smallint User security identification number


(SID).

The following table shows the result set when no user account is specified and aliases exist in the current
database.

COLUMN NAME DATA TYPE DESCRIPTION

LoginName sysname Logins aliased to users in the current


database.

UserNameAliasedTo sysname User name in the current database to


which the login is aliased.

The following table shows the result set when a role is specified for security_account.

COLUMN NAME DATA TYPE DESCRIPTION

Role_name sysname Name of the role in the current


database.

Role_id smallint Role ID for the role in the current


database.

Users_in_role sysname Member of the role in the current


database.

Userid smallint User ID for the member of the role.

Remarks
To see information about membership of database roles, use sys.database_role_members. To see information
about server role members, use sys.server_role_members, and to see information about server-level principals,
use sys.server_principals.

Permissions
Requires membership in the public role.
Information returned is subject to restrictions on access to metadata. Entities on which the principal has no
permission do not appear. For more information, see Metadata Visibility Configuration.

Examples
A. Listing all users
The following example lists all users in the current database.

EXEC sp_helpuser;
B. Listing information for a single user
The following example lists information about the user database owner ( dbo ).

EXEC sp_helpuser 'dbo';

C. Listing information for a database role


The following example lists information about the db_securityadmin fixed database role.

EXEC sp_helpuser 'db_securityadmin';

See Also
Security Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
Principals (Database Engine)
sys.database_principals (Transact-SQL)
sys.database_role_members (Transact-SQL)
sys.server_principals (Transact-SQL)
sys.server_role_members (Transact-SQL)
sp_migrate_user_to_contained (Transact-SQL)
1/2/2018 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Converts a database user that is mapped to a SQL Server login, to a contained database user with password. In a
contained database, use this procedure to remove dependencies on the instance of SQL Server where the database
is installed. sp_migrate_user_to_contained separates the user from the original SQL Server login, so that settings
such as password and default language can be administered separately for the contained database.
sp_migrate_user_to_contained can be used before moving the contained database to a different instance of the
SQL Server Database Engine to eliminate dependencies on the current SQL Server instance logins.
Note This procedure is only used in a contained database. For more information, see Contained Databases.

Syntax
sp_migrate_user_to_contained [ @username = ] N'user' ,
[ @rename = ] { N'copy_login_name' | N'keep_name' } ,
[ @disablelogin = ] { N'disable_login' | N'do_not_disable_login' }

Arguments
[@username = ] N'user'
Name of a user in the current contained database that is mapped to a SQL Server authenticated login. The value is
sysname, with a default of NULL.
[@rename = ] N'copy_login_name' | N'keep_name'
When a database user based on a login has a different user name than the login name, use keep_name to retain
the database user name during the migration. Use copy_login_name to create the new contained database user
with the name of the login, instead of the user. When a database user based on a login has the same user name as
the login name, both options create the contained database user without changing the name.
[@disablelogin = ] N'disable_login' | N'do_not_disable_login'
disable_login disables the login in the master database. To connect when the login is disabled, the connection must
provide the contained database name as the initial catalog as part of the connection string.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_migrate_user_to_contained creates the contained database user with password, regardless of the properties
or permissions of the login. For example, the procedure can succeed if the login is disabled or if the user is denied
the CONNECT permission to the database.
sp_migrate_user_to_contained has the following restrictions.
The user name cannot already exist in the database.
Built-in users, for example dbo and guest, cannot be converted.
The user cannot be specified in the EXECUTE AS clause of a signed stored procedure.
The user cannot own a stored procedure that includes the EXECUTE AS OWNER clause.
sp_migrate_user_to_contained cannot be used in a system database.

Security
When migrating users, be careful not to disable or delete all the administrator logins from the instance of SQL
Server. If all logins are deleted, see Connect to SQL Server When System Administrators Are Locked Out.
If the BUILTIN\Administrators login is present, administrators can connect by starting their application using the
Run as Administrator option.
Permissions
Requires the CONTROL SERVER permission.

Examples
A. Migrating a single user
The following example migrates a SQL Server login named Barry , to a contained database user with password.
The example retains the does not change the user name, and retains the login as enabled.

sp_migrate_user_to_contained
@username = N'Barry',
@rename = N'keep_name',
@disablelogin = N'do_not_disable_login' ;

B. Migrating all database users with logins to contained database users without logins
The following example migrates all users that are based on SQL Server logins to contained database users with
passwords. The example excludes logins that are not enabled. The example must be executed in the contained
database.

DECLARE @username sysname ;


DECLARE user_cursor CURSOR
FOR
SELECT dp.name
FROM sys.database_principals AS dp
JOIN sys.server_principals AS sp
ON dp.sid = sp.sid
WHERE dp.authentication_type = 1 AND sp.is_disabled = 0;
OPEN user_cursor
FETCH NEXT FROM user_cursor INTO @username
WHILE @@FETCH_STATUS = 0
BEGIN
EXECUTE sp_migrate_user_to_contained
@username = @username,
@rename = N'keep_name',
@disablelogin = N'disable_login';
FETCH NEXT FROM user_cursor INTO @username
END
CLOSE user_cursor ;
DEALLOCATE user_cursor ;

See Also
Migrate to a Partially Contained Database
Contained Databases
sp_MShasdbaccess (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Lists the name and owner of all the databases to which the user has access.
Transact-SQL Syntax Conventions

Syntax
sp_MShasdbaccess

Return Code Values


0 (success) or 1 (failure)

Permissions
Execute permission is granted to the public role.

See Also
sys.sysdatabases (Transact-SQL)
sp_password (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds or changes a password for a Microsoft SQL Server login.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use ALTER LOGIN instead.

Transact-SQL Syntax Conventions

Syntax
sp_password [ [ @old = ] 'old_password' , ]
{ [ @new =] 'new_password' }
[ , [ @loginame = ] 'login' ]

Arguments
[ @old= ] 'old_password'
Is the old password. old_password is sysname, with a default of NULL.
[ @new= ] 'new_password'
Is the new password. new_password is sysname, with no default. old_password must be specified if named
parameters are not used.

IMPORTANT
Do not use a NULL password. Use a strong password. For more information, see Strong Passwords.

[ @loginame= ] 'login'
Is the name of the login affected by the password change. login is sysname, with a default of NULL. login must
already exist and can be specified only by members of the sysadmin or securityadmin fixed server roles.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_password calls ALTER LOGIN. This statement supports additional options. For information on changing
passwords, see ALTER LOGIN (Transact-SQL).
sp_password cannot be executed within a user-defined transaction.
Permissions
Requires ALTER ANY LOGIN permission. Also requires CONTROL SERVER permission to reset a password without
supplying the old password, or if the login that is being changed has CONTROL SERVER permission.
A principal can change its own password.

Examples
A. Changing the password of a login without knowing the old password
The following example shows how to use ALTER LOGIN to change the password for the login Victoria to
B3r1000d#2-36 . This is the preferred method. The user that is executing this command must have CONTROL
SERVER permission.

ALTER LOGIN Victoria WITH PASSWORD = 'B3r1000d#2-36';


GO

B. Changing a password
The following example shows how to use ALTER LOGIN to change the password for the login Victoria from
B3r1000d#2-36 to V1cteAmanti55imE . This is the preferred method. User Victoria can execute this command
without additional permissions. Other users require ALTER ANY LOGIN permission.

ALTER LOGIN Victoria WITH


PASSWORD = 'V1cteAmanti55imE'
OLD_PASSWORD = 'B3r1000d#2-36';
GO

See Also
Security Stored Procedures (Transact-SQL)
ALTER LOGIN (Transact-SQL)
CREATE LOGIN (Transact-SQL)
sp_addlogin (Transact-SQL)
sp_adduser (Transact-SQL)
sp_grantlogin (Transact-SQL)
sp_revokelogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_refresh_parameter_encryption (Transact-SQL)
1/2/2018 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates the Always Encrypted metadata for the parameters of the specified non-schema-bound stored procedure,
user-defined function, view, DML trigger, database-level DDL trigger, or server-level DDL trigger in the current
database.
Transact-SQL Syntax Conventions

Syntax
sys.sp_refresh_parameter_encryption [ @name = ] 'module_name'
[ , [ @namespace = ] '<class>' ]
[ ; ]

<class> ::=
{ DATABASE_DDL_TRIGGER | SERVER_DDL_TRIGGER }

Arguments
[ @name = ] 'module_name'
Is the name of the stored procedure, user-defined function, view, DML trigger, database-level DDL trigger, or
server-level DDL trigger. module_name cannot be a common language runtime (CLR) stored procedure or a CLR
function. module_name cannot be schema-bound. module_name is nvarchar , with no default. module_name can
be a multi-part identifier, but can only refer to objects in the current database.
[ @namespace = ] ' < class > '
Is the class of the specified module. When module_name is a DDL trigger, <class> is required. <class> is
nvarchar(20) . Valid inputs are DATABASE_DDL_TRIGGER and SERVER_DDL_TRIGGER .

Return Code Values


0 (success) or a nonzero number (failure)

Remarks
The encryption metadata for parameters of a module can become outdated, if:
Encryption properties of a column in a table the module references, have been updated. For example, a column
has been dropped and a new column with the same name, but a different encryption type, encryption key or an
encryption algorithm has been added.
The module references another module with outdated parameter encryption metadata.
When encryption properties of a table are modified, sp_refresh_parameter_encryption should be run for any
modules directly or indirectly referencing the table. This stored procedure can be called on those modules in any
order, without requiring the user to first refresh the inner module before moving to its callers.
sp_refresh_parameter_encryption does not affect any permissions, extended properties, or SET options that are
associated with the object.
To refresh a server-level DDL trigger, execute this stored procedure from the context of any database.

NOTE
Any signatures that are associated with the object are dropped when you run sp_refresh_parameter_encryption .

Permissions
Requires ALTER permission on the module and REFERENCES permission on any CLR user-defined types and XML
schema collections that are referenced by the object.
When the specified module is a database-level DDL trigger, requires ALTER ANY DATABASE DDL TRIGGER permission in
the current database.
When the specified module is a server-level DDL trigger, requires CONTROL SERVER permission.
For modules that are defined with the EXECUTE AS clause, IMPERSONATE permission is required on the specified
principal. Generally, refreshing an object does not change its EXECUTE AS principal, unless the module was defined
with EXECUTE AS USER and the user name of the principal now resolves to a different user than it did at the time the
module was created.

Examples
The following example creates a table and a procedure referencing the table, configures Always Encrypted, and
then demonstrates altering the table and running the sp_refresh_parameter_encryption procedure.
First create the initial table and a stored procedure referencing the table.

CREATE TABLE [Patients]([PatientID] [int] IDENTITY(1,1) NOT NULL,


[SSN] [char](11),
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NOT NULL,
[MiddleName] [nvarchar](50) NULL,
[StreetAddress] [nvarchar](50) NOT NULL,
[City] [nvarchar](50) NOT NULL,
[ZipCode] [char](5) NOT NULL,
[State] [char](2) NOT NULL,
[BirthDate] [date] NOT NULL,
CONSTRAINT [PK_Patients] PRIMARY KEY CLUSTERED
(
[PatientID] ASC
) WITH
(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY];
GO

CREATE PROCEDURE [find_patient] @SSN [char](11)


AS
BEGIN
SELECT * FROM [Patients] WHERE SSN=@SSN
END;
GO

Then set up Always Encrypted keys.


CREATE COLUMN MASTER KEY [CMK1]
WITH
(
KEY_STORE_PROVIDER_NAME = N'MSSQL_CERTIFICATE_STORE',
KEY_PATH = N'CurrentUser/my/A66BB0F6DD70BDFF02B62D0F87E340288E6F9305'
);
GO

CREATE COLUMN ENCRYPTION KEY [CEK1]


WITH VALUES
(
COLUMN_MASTER_KEY = [CMK1],
ALGORITHM = 'RSA_OAEP',
ENCRYPTED_VALUE =

0x016E000001630075007200720065006E00740075007300650072002F006D0079002F0061003600360062006200300066003600640064
00370030006200640066006600300032006200360032006400300066003800370065003300340030003200380038006500360066003900
330030003500CA0D0CEC74ECADD1804CF99137B4BD06BBAB15D7EA74E0C249A779C7768A5B659E0125D24FF827F5EA8CA517A8E197ECA1
353BA814C2B0B2E6C8AB36E3AE6A1E972D69C3C573A963ADAB6686CF5D24F95FE43140C4F9AF48FBA7DF2D053F3B4A1F5693A1F905440F
8015BDB43AF8A04BE4E045B89876A0097E5FBC4E6A3B9C3C0D278C540E46C53938B8C957B689C4DC095821C465C73117CBA95B758232F9
E5B2FCC7950B8CA00AFE374DE42847E3FBC2FDD277035A2DEF529F4B735C20D980073B4965B4542A34723276A1646998FC6E1C40A3FDB6
ABCA98EE2B447F114D2AC7FF8C7D51657550EC5C2BABFFE8429B851272086DCED94332CF18FA854C1D545A28B1EF4BE64F8E035175C165
0F6FC5C4702ACF99850A4542B3747EAEC0CC726E091B36CE24392D801ECAA684DE344FECE05812D12CD72254A014D42D0EABDA41C89FC4
F545E88B4B8781E5FAF40D7199D4842D2BFE904D209728ED4F527CBC169E2904F6E711FF81A8F4C25382A2E778DD2A58552ED031AFFDA9
D9D891D98AD82155F93C58202FC24A77F415D4F8EF22419D62E188AC609330CCBD97CEE1AEF8A18B01958833604707FDF03B2B386487CC
679D7E352D0B69F9FB002E51BCD814D077E82A09C14E9892C1F8E0C559CFD5FA841CEF647DAB03C8191DC46B772E94D579D8C80FE93C38
27C9F0AE04D5325BC73111E07EEEDBE67F1E2A73580085
);
GO

Finally we replace the SSN column with the encrypted column, and then runs the sp_refresh_parameter_encryption
procedure to update the Always Encrypted components.

ALTER TABLE [Patients] DROP COLUMN [SSN];


GO

ALTER TABLE [Patients]


ADD [SSN] [char](11) COLLATE Latin1_General_BIN2
ENCRYPTED WITH
(COLUMN_ENCRYPTION_KEY = [CEK1],
ENCRYPTION_TYPE = Deterministic,
ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256')
NOT NULL;
GO

EXEC sp_refresh_parameter_encryption [find_patient];


GO

See Also
Always Encrypted
Always Encrypted Wizard
sp_remoteoption (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Displays or changes options for a remote login defined on the local server running SQL Server.

NOTE
This feature will be removed in the next version of Microsoft SQL Server. Do not use this feature in new development work,
and modify applications that currently use this feature as soon as possible.sp_remoteoption does not change any options
and returns an error message. It is supported for backward compatibility only.

Transact-SQL Syntax Conventions

Syntax
sp_remoteoption [ [ @remoteserver = ] 'remoteserver' ]
[ , [ @loginame = ] 'loginame' ]
[ , [ @remotename = ] 'remotename' ]
[ , [ @optname = ] 'optname' ]
[ , [ @optvalue = ] 'optvalue' ]

Remarks
This stored procedure returns the following error message:
The trusted option in remote login mapping is no longer supported.

See Also
Linked Servers (Database Engine)
sp_revokelogin (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the login entries from SQL Server for a Windows user or group created by using CREATE LOGIN,
sp_grantlogin, or sp_denylogin.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development
work, and plan to modify applications that currently use this feature. Use DROP LOGIN instead.

Transact-SQL Syntax Conventions

Syntax
sp_revokelogin [ @loginame= ] 'login'

Arguments
[ @loginame=] 'login'
Is the name of the Windows user or group. login is sysname, with no default. login can be any existing Windows
user name or group in the form Computer name\User or Domain\User.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_revokelogin disables connections using the account specified by the login parameter. But Windows users
that have been granted access to an instance of SQL Server through membership in a Windows group can still
connect as the group after their individual access has been revoked. Similarly, if the login parameter specifies the
name of a Windows group, members of that group that have been separately granted access to the instance of
SQL Server will still be able to connect.
For example, if Windows user ADVWORKS\john is a member of the Windows group ADVWORKS\Admins,
and sp_revokelogin revokes the access of ADVWORKS\john :

sp_revokelogin [ADVWORKS\john]

User ADVWORKS\john can still connect if ADVWORKS\Admins has been granted access to an instance of SQL
Server. Similarly, if Windows group ADVWORKS\Admins has its access revoked but ADVWORKS\john is
granted access, ADVWORKS\john can still connect.
Use sp_denylogin to explicitly prevent users from connecting to an instance of SQL Server, regardless of their
Windows group memberships.
sp_revokelogin cannot be executed within a user-defined transaction.

Permissions
Requires ALTER ANY LOGIN permission on the server.

Examples
The following example removes the login entries for the Windows user Corporate\MollyA .

EXEC sp_revokelogin 'Corporate\MollyA';

Or

EXEC sp_revokelogin [Corporate\MollyA];

See Also
Security Stored Procedures (Transact-SQL)
DROP LOGIN (Transact-SQL)
sp_denylogin (Transact-SQL)
sp_droplogin (Transact-SQL)
sp_grantlogin (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_revokedbaccess (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a database user from the current database.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use DROP USER instead.

Transact-SQL Syntax Conventions

Syntax
sp_revokedbaccess [ @name_in_db = ] 'name'

Arguments
[ @name_in_db = ] 'name'
Is the name of the database user to be removed. name is a sysname with no default. name can be the name of a
server login, a Windows login, or a Windows group, and must exist in the current database. When you specify a
Windows login or Windows group, specify the name by which it is known in the database.

Return Code Values


0 (success) or 1 (failure)

Remarks
When the database user is removed, the permissions and aliases that depend on the user are also removed.
sp_revokedbaccess can remove only database users from the current database. Before removing a database user
that owns objects in the current database, you must either transfer ownership of the objects or drop them from
the database. For more information, see ALTER AUTHORIZATION (Transact-SQL).
sp_revokedbaccess cannot be executed within a user-defined transaction.

Permissions
Requires ALTER ANY USER permission on the database.

Examples
The following example removes the database user mapped to Edmonds\LolanSo from the current database.
EXEC sp_revokedbaccess 'Edmonds\LolanSo';
GO

See Also
Security Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
DROP USER (Transact-SQL)
ALTER AUTHORIZATION (Transact-SQL)
sp_setapprole (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Activates the permissions associated with an application role in the current database.
Transact-SQL Syntax Conventions

Syntax
sp_setapprole [ @rolename = ] 'role',
[ @password = ] { encrypt N'password' }
|
'password' [ , [ @encrypt = ] { 'none' | 'odbc' } ]
[ , [ @fCreateCookie = ] true | false ]
[ , [ @cookie = ] @cookie OUTPUT ]

Arguments
[ @rolename = ] 'role'
Is the name of the application role defined in the current database. role is sysname, with no default. role must
exist in the current database.
[ @password = ] { encrypt N'password' }
Is the password required to activate the application role. password is sysname, with no default. password can be
obfuscated by using the ODBC encrypt function. When you use the encrypt function, the password must be
converted to a Unicode string by placing N before the first quotation mark.
The encrypt option is not supported on connections that are using SqlClient.

IMPORTANT
The ODBC encrypt function does not provide encryption. You should not rely on this function to protect passwords that
are transmitted over a network. If this information will be transmitted across a network, use SSL or IPSec.

@encrypt = 'none'
Specifies that no obfuscation be used. The password is passed to SQL Server as plain text. This is the default.
@encrypt= 'odbc'
Specifies that ODBC will obfuscate the password by using the ODBC encrypt function before sending the
password to the SQL Server Database Engine. This can be specified only when you are using either an ODBC client
or the OLE DB Provider for SQL Server.
[ @fCreateCookie = ] true | false
Specifies whether a cookie is to be created. true is implicitly converted to 1. false is implicitly converted to 0.
[ @cookie = ] @cookie OUTPUT
Specifies an output parameter to contain the cookie. The cookie is generated only if the value of @fCreateCookie
is true. varbinary(8000)
NOTE
The cookie OUTPUT parameter for sp_setapprole is currently documented as varbinary(8000) which is the correct
maximum length. However the current implementation returns varbinary(50). Applications should continue to reserve
varbinary(8000) so that the application continues to operate correctly if the cookie return size increases in a future release.

Return Code Values


0 (success) and 1 (failure)

Remarks
After an application role is activated by using sp_setapprole, the role remains active until the user either
disconnects from the server or executes sp_unsetapprole. sp_setapprole can be executed only by direct
Transact-SQL statements. sp_setapprole cannot be executed within another stored procedure or within a user-
defined transaction.
For an overview of application roles, see Application Roles.

IMPORTANT
To protect the application role password when it is transmitted across a network, you should always use an encrypted
connection when enabling an application role..
The Microsoft ODBC encrypt option is not supported by SqlClient. If you must store credentials, encrypt them with the
crypto API functions. The parameter password is stored as a one-way hash. To preserve compatibility with earlier versions of
SQL Server, password complexity policy is not enforced by sp_addapprole. To enforce password complexity policy, use
CREATE APPLICATION ROLE.

Permissions
Requires membership in public and knowledge of the password for the role.

Examples
A. Activating an application role without the encrypt option
The following example activates an application role named SalesAppRole , with the plain-text password
AsDeF00MbXX , created with permissions specifically designed for the application used by the current user.

EXEC sp_setapprole 'SalesApprole', 'AsDeF00MbXX';


GO

B. Activating an application role with a cookie and then reverting to the original context
The following example activates the Sales11 application role with password fdsd896#gfdbfdkjgh700mM , and creates
a cookie. The example returns the name of the current user, and then reverts to the original context by executing
sp_unsetapprole .
DECLARE @cookie varbinary(8000);
EXEC sp_setapprole 'Sales11', 'fdsd896#gfdbfdkjgh700mM'
, @fCreateCookie = true, @cookie = @cookie OUTPUT;
-- The application role is now active.
SELECT USER_NAME();
-- This will return the name of the application role, Sales11.
EXEC sp_unsetapprole @cookie;
-- The application role is no longer active.
-- The original context has now been restored.
GO
SELECT USER_NAME();
-- This will return the name of the original user.
GO

See Also
System Stored Procedures (Transact-SQL)
Security Stored Procedures (Transact-SQL)
CREATE APPLICATION ROLE (Transact-SQL)
DROP APPLICATION ROLE (Transact-SQL)
sp_unsetapprole (Transact-SQL)
sp_srvrolepermission (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Displays the permissions of a fixed server role.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature.

Transact-SQL Syntax Conventions

Syntax
sp_srvrolepermission [ [ @srvrolename = ] 'role']

Arguments
[ @srvrolename = ] 'role'
Is the name of the fixed server role for which permissions are returned. role is sysname, with a default of NULL. If
no role is specified, the permissions for all fixed server roles are returned. role can have one of the following
values.

VALUE DESCRIPTION

sysadmin System administrators

securityadmin Security administrators

serveradmin Server administrators

setupadmin Setup administrators

processadmin Process administrators

diskadmin Disk administrators

dbcreator Database creators

bulkadmin Can execute BULK INSERT statements

Return Code Values


0 (success) or 1 (failure)
Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

ServerRole sysname Name of a fixed server role

Permission sysname Permission associated with ServerRole

Remarks
The permissions listed include the Transact-SQL statements that can be executed, and other special activities that
can be performed by members of the fixed server role. To display a list of the fixed server roles, execute
sp_helpsrvrole.
The sysadmin fixed server role has the permissions of all the other fixed server roles.

Permissions
Requires membership in the public role.

Examples
The following query returns the permissions associated with the sysadmin fixed server role.

EXEC sp_srvrolepermission 'sysadmin';


GO

See Also
Security Stored Procedures (Transact-SQL)
sp_addsrvrolemember (Transact-SQL)
sp_dropsrvrolemember (Transact-SQL)
sp_helpsrvrole (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_unsetapprole (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deactivates an application role and reverts to the previous security context.
Transact-SQL Syntax Conventions

Syntax
sp_unsetapprole @cookie

Arguments
@cookie
Specifies the cookie that was created when the application role was activated. The cookie is created by
sp_setapprole (Transact-SQL). varbinary(8000).

NOTE
The cookie OUTPUT parameter for sp_setapprole is currently documented as varbinary(8000) which is the correct
maximum length. However the current implementation returns varbinary(50). Applications should continue to reserve
varbinary(8000) so that the application continues to operate correctly if the cookie return size increases in a future release.

Return Code Values


0 (success) and 1 (failure)

Remarks
After an application role is activated by using sp_setapprole, the role remains active until the user either
disconnects from the server or executes sp_unsetapprole.
For an overview of application roles, see Application Roles.

Permissions
Requires membership in public and knowledge of the cookie saved when the application role was activated.

Examples
Activating an application role with a cookie, then reverting to the previous context
The following example activates the Sales11 application role with password fdsd896#gfdbfdkjgh700mM , and creates
a cookie. The example returns the name of the current user, and then reverts to the original context by executing
sp_unsetapprole.
DECLARE @cookie varbinary(8000);
EXEC sp_setapprole 'Sales11', 'fdsd896#gfdbfdkjgh700mM'
, @fCreateCookie = true, @cookie = @cookie OUTPUT;
-- The application role is now active.
SELECT USER_NAME();
-- This will return the name of the application role, Sales11.
EXEC sp_unsetapprole @cookie;
-- The application role is no longer active.
-- The original context has now been restored.
GO
SELECT USER_NAME();
-- This will return the name of the original user.
GO

See Also
sp_setapprole (Transact-SQL)
System Stored Procedures (Transact-SQL)
Security Stored Procedures (Transact-SQL)
CREATE APPLICATION ROLE (Transact-SQL)
DROP APPLICATION ROLE (Transact-SQL)
sp_validatelogins (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Reports information about Windows users and groups that are mapped to SQL Server principals but no longer
exist in the Windows environment.
Transact-SQL Syntax Conventions

Syntax
sp_validatelogins

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

SID varbinary(85) Windows security identifier (SID) of the


Windows user or group.

NT Login sysname Name of the Windows user or group.

Remarks
If the orphaned server-level principal owns a database user, the database user must be removed before the
orphaned server principal can be removed. To remove a database user, use DROP USER. If the server-level
principal owns securables in the database, ownership of the securables must be transferred or they must be
dropped. To transfer ownership of database securables, use ALTER AUTHORIZATION.
To remove mappings to Windows users and groups that no longer exist, use DROP LOGIN.

Permissions
Requires membership in the sysadmin or securityadmin fixed server role.

Examples
The following example displays the Windows users and groups that no longer exist but are still granted access to
an instance of SQL Server.

EXEC sp_validatelogins;
GO
See Also
System Stored Procedures (Transact-SQL)
Security Stored Procedures (Transact-SQL)
DROP USER (Transact-SQL)
DROP LOGIN (Transact-SQL)
ALTER AUTHORIZATION (Transact-SQL)
sp_xp_cmdshell_proxy_account (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a proxy credential for xp_cmdshell.

NOTE
xp_cmdshell is disabled by default. To enable xp_cmdshell, see xp_cmdshell Server Configuration Option.

Transact-SQL Syntax Conventions

Syntax
sp_xp_cmdshell_proxy_account [ NULL | { 'account_name' , 'password' } ]

Arguments
NULL
Specifies that the proxy credential should be deleted.
account_name
Specifies a Windows login that will be the proxy.
password
Specifies the password of the Windows account.

Return Code Values


0 (success) or 1 (failure)

Remarks
The proxy credential will be called ##xp_cmdshell_proxy_account##.
When it is executed using the NULL option, sp_xp_cmdshell_proxy_account deletes the proxy credential.

Permissions
Requires CONTROL SERVER permission.

Examples
A. Creating the proxy credential
The following example shows how to create a proxy credential for a Windows account called ADVWKS\Max04 with
password ds35efg##65 .
EXEC sp_xp_cmdshell_proxy_account 'ADVWKS\Max04', 'ds35efg##65';
GO

B. Dropping the proxy credential


The following example removes the proxy credential from the credential store.

EXEC sp_xp_cmdshell_proxy_account NULL;


GO

See Also
xp_cmdshell (Transact-SQL)
CREATE CREDENTIAL (Transact-SQL)
sys.credentials (Transact-SQL)
System Stored Procedures (Transact-SQL)
Security Stored Procedures (Transact-SQL)
SQL Data Warehouse Stored Procedures
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
SQL Data Warehouse provides built-in procedures that you can use to perform operations related to database
roles. SQL Data Warehouse includes the following system procedures:

sp_datatype_info_90 (SQL Data Warehouse)


sp_pdw_add_network_credentials (SQL Data Warehouse)
sp_pdw_database_encryption (SQL Data Warehouse)
sp_pdw_database_encryption_regenerate_system_keys (SQL Data Warehouse)
sp_pdw_log_user_data_masking (SQL Data Warehouse)
sp_pdw_remove_network_credentials (SQL Data Warehouse)
sp_special_columns_100 (SQL Data Warehouse)

NOTE
Some additional system stored procedures are used only within an instance of SQL Server or through client APIs and are not
intended for general customer use. These procedures are listed at System Stored Procedures (Transact-SQL). These
procedures are subject to change and compatibility is not guaranteed. All procedures on the list are not available in SQL Data
Warehouse.

See Also
System Stored Functions (Transact-SQL)
Data Types (Transact-SQL)
sp_datatype_info_90 (SQL Data Warehouse)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
Returns information about the data types supported by the current environment.
Transact-SQL Syntax Conventions (Transact-SQL)

Syntax
-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse

sp_datatype_info_90 [ [ @data_type = ] data_type ]


[ , [ @ODBCVer = ] odbc_version ]

Arguments
[ @data_type= ] data_type
Is the code number for the specified data type. To obtain a list of all data types, omit this parameter. data_type is
int, with a default of 0.
[ @ODBCVer= ] odbc_version
Is the version of ODBC that is used. odbc_version is tinyint, with a default of 2.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

TYPE_NAME sysname DBMS-dependent data type.

DATA_TYPE smallint Code for the ODBC type to which all


columns of this type are mapped.

PRECISION int Maximum precision of the data type on


the data source. NULL is returned for
data types for which precision is not
applicable. The return value for the
PRECISION column is in base 10.

LITERAL_PREFIX varchar(32) Character or characters used before a


constant. For example, a single
quotation mark (') for character types
and 0x for binary.
COLUMN NAME DATA TYPE DESCRIPTION

LITERAL_SUFFIX varchar(32) Character or characters used to


terminate a constant. For example, a
single quotation mark (') for character
types and no quotation marks for
binary.

CREATE_PARAMS varchar(32) Description of the creation parameters


for this data type. For example, decimal
is "precision, scale", float is NULL, and
varchar is "max_length".

NULLABLE smallint Specifies nullability.

1 = Allows null values.

0 = Does not allow null values.

CASE_SENSITIVE smallint Specifies case sensitivity.

1 = All columns of this type are case-


sensitive (for collations).

0 = All columns of this type are case-


insensitive.

SEARCHABLE smallint Specifies the search capability of the


column type:

1 = Cannot be searched.

2 = Searchable with LIKE.

3 = Searchable with WHERE.

4 = Searchable with WHERE or LIKE.

UNSIGNED_ATTRIBUTE smallint Specifies the sign of the data type.

1 = Data type unsigned.

0 = Data type signed.

MONEY smallint Specifies the money data type.

1 = money data type.

0 = Not a money data type.


COLUMN NAME DATA TYPE DESCRIPTION

AUTO_INCREMENT smallint Specifies autoincrementing.

1 = Autoincrementing.

0 = Not autoincrementing.

NULL = Attribute not applicable.

An application can insert values into a


column that has this attribute, but the
application cannot update the values in
the column. With the exception of the
bit data type, AUTO_INCREMENT is
valid only for data types that belong to
the Exact Numeric and Approximate
Numeric data type categories.

LOCAL_TYPE_NAME sysname Localized version of the data source-


dependent name of the data type. For
example, DECIMAL is DECIMALE in
French. NULL is returned if a localized
name is not supported by the data
source.

MINIMUM_SCALE smallint Minimum scale of the data type on the


data source. If a data type has a fixed
scale, the MINIMUM_SCALE and
MAXIMUM_SCALE columns both
contain this value. NULL is returned
where scale is not applicable.

MAXIMUM_SCALE smallint Maximum scale of the data type on the


data source. If the maximum scale is not
defined separately on the data source,
but is instead defined to be the same as
the maximum precision, this column
contains the same value as the
PRECISION column.

SQL_DATA_TYPE smallint Value of the SQL data type as it appears


in the TYPE field of the descriptor. This
column is the same as the DATA_TYPE
column, except for the datetime and
ANSI interval data types. This field
always returns a value.

SQL_DATETIME_SUB smallint datetime or ANSI interval subcode if


the value of SQL_DATA_TYPE is
SQL_DATETIME or SQL_INTERVAL. For
data types other than datetime and
ANSI interval, this field is NULL.
COLUMN NAME DATA TYPE DESCRIPTION

NUM_PREC_RADIX int Number of bits or digits for calculating


the maximum number that a column
can hold. If the data type is an
approximate numeric data type, this
column contains the value 2 to indicate
several bits. For exact numeric types,
this column contains the value 10 to
indicate several decimal digits.
Otherwise, this column is NULL. By
combining the precision with radix, the
application can calculate the maximum
number that the column can hold.

INTERVAL_PRECISION smallint Value of interval leading precision if


data_type is interval; otherwise NULL.

USERTYPE smallint usertype value from the systypes table.

Remarks
sp_datatype_info is equivalent to SQLGetTypeInfo in ODBC. The results returned are ordered by DATA_TYPE and
then by how closely the data type maps to the corresponding ODBC SQL data type.

Permissions
Requires membership in the public role.

Examples: Azure SQL Data Warehouse and Parallel Data Warehouse


The following example retrieves information for the sysname and nvarchar data types by specifying the
data_type value of -9 .

USE master;
GO
EXEC sp_datatype_info_90 -9;
GO

See Also
SQL Data Warehouse Stored Procedures
Data Types (Transact-SQL)
sp_pdw_add_network_credentials (SQL Data
Warehouse)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
This stores network credentials in SQL Data Warehouse and associates them with a server. For example, use this
stored procedure to give SQL Data Warehouse appropriate read/write permissions to perform database backup
and restore operations on a target server, or to create a backup of a certificate used for TDE.
Transact-SQL Syntax Conventions (Transact-SQL)

Syntax
-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse

sp_pdw_add_network_credentials 'target_server_name', 'user_name', ꞌpasswordꞌ

Arguments
'target_server_name'
Specifies the target server host name or IP address. SQL Data Warehouse will access this server by using the
username and password credentials passed to this stored procedure.
To connect through the InfiniBand network, use the InfiniBand IP address of the target server.
target_server_name is defined as nvarchar(337).
'user_name'
Specifies the user_name that has permissions to access the target server. If credentials already exist for the target
server, they will be updated to the new credentials.
user_name is defined as nvarchar (513).
'passwordꞌ
Specifies the password for user_name.

Return Code Values


0 (success) or 1 (failure)

Permissions
Requires ALTER SERVER STATE permission.

Error Handling
An error occurs if adding credentials does not succeed on the Control node and all Compute nodes.

General Remarks
This stored procedure adds network credentials to the NetworkService account for SQL Data Warehouse. The
NetworkService account runs each instance of SMP SQL Server on the Control node and the Compute nodes. For
example, when a backup operation runs, the Control node and each Compute node will use the NetworkService
account credentials to gain read and write permission to the target server.

Examples: Azure SQL Data Warehouse and Parallel Data Warehouse


A. Add credentials for performing a database backup
The following example associates the user name and password credentials for the domain user seattle\david with a
target server that has an IP address of 10.172.63.255. The user seattle\david has read/write permissions to the
target server. SQL Data Warehouse will store these credentials and use them to read and write to and from the
target server, as necessary for backup and restore operations.

EXEC sp_pdw_add_network_credentials '10.172.63.255', 'seattle\david', '********';

The backup command requires that the server name be entered as an IP address.

NOTE
To perform the database backup over InfiniBand, be sure to use the InfiniBand IP address of the backup server.

See Also
sp_pdw_remove_network_credentials (SQL Data Warehouse)
sp_pdw_database_encryption (SQL Data Warehouse)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
Use sp_pdw_database_encryption to enable transparent data encryption on for a SQL Data Warehouse
appliance. When sp_pdw_database_encryption set to 1, use the ALTER DATABASE statement to encrypt a
database by using TDE.

Syntax
-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse

sp_pdw_database_encryption [ [ @enabled = ] enabled ] ;

Parameters
[ @enabled= ] enabled
Determines whether transparent data encryption is enabled. enabled is int, and can be one of the following values:
0 = Disabled
1 = Enabled
Executing sp_pdw_database_encryption without parameters returns the current state of TDE on the
appliance as a scalar result set: 0 for disabled, or 1 for enabled.

Return Code Values


0 (success) or 1 (failure)

Remarks
When the TDE is enabled using sp_pdw_database_encryption, the tempdb database is dropped, recreated and
encrypted. For that reason, the TDE cannot be enabled on an appliance while there are other active sessions using
tempdb. Enabling or disabling TDE on an appliance is an action that changes the state of the appliance, in most
cases is expected to be performed once in the appliance lifetime, and should be executed when there is no traffic
on the appliance.

Permissions
Requires membership in the sysadmin fixed database role, or CONTROL SERVER permission.

Example
The following example enables TDE on the appliance.

EXEC sys.sp_pdw_database_encryption 1;

See Also
sp_pdw_database_encryption_regenerate_system_keys (SQL Data Warehouse)
sp_pdw_log_user_data_masking (SQL Data Warehouse)
sp_pdw_database_encryption_regenerate_system_keys
(SQL Data Warehouse)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
Use sp_pdw_database_encryption_regenerate_system_keys to rotate the certificate and database encryption
key for internal databases that are encrypted when TDE is enabled on the appliance. This includes tempdb . This will
succeed only if TDE is enabled.

Syntax
-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse

sp_pdw_database_encryption_regenerate_system_keys ;

Return Code Values


0 (success) or 1 (failure)

Remarks
The procedure has no parameters.
This procedure should be used when the traffic in the appliance is low.

Permissions
Requires membership in the sysadmin fixed database role, or CONTROL SERVER permission.

Example
The following example regenerates the database encryption keys.

EXEC sys.sp_pdw_database_encryption_regenerate_system_keys;

See Also
sp_pdw_database_encryption (SQL Data Warehouse)
sp_pdw_log_user_data_masking (SQL Data Warehouse)
sp_pdw_log_user_data_masking (SQL Data
Warehouse)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
Use sp_pdw_log_user_data_masking to enable user data masking in SQL Data Warehouse activity logs. User
data masking affects the statements on all databases on the appliance.

IMPORTANT
The SQL Data Warehouse activity logs affected by sp_pdw_log_user_data_masking are certain SQL Data Warehouse
activity logs. sp_pdw_log_user_data_masking does not affect database transaction logs, or SQL Server error logs.

Background: In the default configuration SQL Data Warehouse activity logs contain full Transact-SQL statements,
and can in some cases include user data contained in operations such as INSERT, UPDATE, and SELECT
statements. In case of a problem on the appliance, this permits the analysis of the conditions that caused the
problem without a need to reproduce the issue. In order to prevent the user data from being written to SQL Data
Warehouse activity logs, customers can choose to turn on the user data masking by using this stored procedure.
The statements will still be written to SQL Data Warehouse activity logs, but all the literals in statements that may
contain user data will be masked; replaced with some predefined constant values.
When transparent data encryption is enabled on the appliance, masking of the user data in SQL Data Warehouse
activity logs is automatically turned on.

Syntax
-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse

sp_pdw_log_user_data_masking [ [ @masking_mode = ] value ] ;

Parameters
[ @masking_mode= ] masking_mode
Determines whether transparent data encryption log user data masking is enabled. masking_mode is int, and can
be one of the following values:
0 = Disabled, user data appears in the SQL Data Warehouse activity logs.
1 = Enabled, user data statements appear in the SQL Data Warehouse activity logs but the user data is
masked.
2 = Statements containing user data are not written to the SQL Data Warehouse activity logs.
Executing sp_pdw_ log_user_data_masking without parameters returns the current state of TDE log user
data masking on the appliance as a scalar result set.

Remarks
User data masking in SQL Data Warehouse activity logs enables replacement of literals with predefined constant
values in SELECT and DML statements, as they can contain user data. Setting masking_mode to 1 does not mask
metadata, such as column names or table names. Setting masking_mode to 2 removes statements with metadata,
such as column names or table names.
User data masking in SQL Data Warehouse activity logs is implemented in the following way:
TDE and user data masking in SQL Data Warehouse activity logs are turned off by default. The statements
will not be automatically masked if database encryption is not enabled on the appliance.
Enabling TDE on the appliance automatically turns on the user data masking in SQL Data Warehouse
activity logs.
Disabling TDE does not affect user data masking in SQL Data Warehouse activity logs.
You can explicitly enable user data masking in SQL Data Warehouse activity logs by using the
sp_pdw_log_user_data_masking procedure.

Permissions
Requires membership in the sysadmin fixed database role, or CONTROL SERVER permission.

Example
The following example enables TDE log user data masking on the appliance.

EXEC sp_pdw_log_user_data_masking 1;

See Also
sp_pdw_database_encryption (SQL Data Warehouse)
sp_pdw_database_encryption_regenerate_system_keys (SQL Data Warehouse)
sp_pdw_remove_network_credentials (SQL Data
Warehouse)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
This removes network credentials stored in SQL Data Warehouse to access a network file share. For example, use
this stored procedure to remove permission for SQL Data Warehouse to perform backup and restore operations
on a server that resides within your own network.
Transact-SQL Syntax Conventions (Transact-SQL)

Syntax
-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse

sp_pdw_remove_network_credentials 'target_server_name'

Arguments
'target_server_name'
Specifies the target server host name or IP address. Credentials to access this server will be removed from SQL
Data Warehouse. This does not change or remove any permissions on the actual target server which is managed
by your own team.
target_server_name is defined as nvarchar(337).

Return Code Values


0 (success) or 1 (failure)

Permissions
Requires ALTER SERVER STATE permission.

Error Handling
An error occurs if removing credentials does not succeed on the Control node and all Compute nodes.

General Remarks
This stored procedure removes network credentials from the NetworkService account for SQL Data Warehouse.
The NetworkService account runs each instance of SMP SQL Server on the Control node and the Compute nodes.
For example, when a backup operation runs, the Control node and each Compute node will use the
NetworkService account credentials to access the target server.

Metadata
To list all credentials and to verify the credentials have been removed, use sys.dm_pdw_network_credentials
(Transact-SQL).
To add credentials, use sp_pdw_add_network_credentials (SQL Data Warehouse).

Examples: Azure SQL Data Warehouse and Parallel Data Warehouse


A. Remove credentials for performing a database backup
The following example removes user name and password credentials for accessing the target server which has an
IP address of 10.192.147.63.

EXEC sp_pdw_remove_network_credentials '10.192.147.63';


sp_special_columns_100 (SQL Data Warehouse)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data
Warehouse
Returns the optimal set of columns that uniquely identify a row in the table. Also returns columns automatically
updated when any value in the row is updated by a transaction.
Transact-SQL Syntax Conventions (Transact-SQL)

Syntax
-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse

sp_special_columns_100 [ @table_name = ] 'table_name'


[ , [ @table_owner = ] 'table_owner' ]
[ , [ @qualifier = ] 'qualifier' ]
[ , [ @col_type = ] 'col_type' ]
[ , [ @scope = ] 'scope' ]
[ , [ @nullable = ] 'nullable' ]
[ , [ @ODBCVer = ] 'ODBCVer' ]
[ ; ]

Arguments
[ @table_name=] 'table_name'
Is the name of the table used to return catalog information. name is sysname, with no default. Wildcard pattern
matching is not supported.
[ @table_owner=] 'table_owner'
Is the table owner of the table used to return catalog information. owner is sysname, with a default of NULL.
Wildcard pattern matching is not supported. If owner is not specified, the default table visibility rules of the
underlying DBMS apply.
In SQL Server, if the current user owns a table with the specified name, the columns of that table are returned. If
owner is not specified and the current user does not own a table of the specified name, this procedure looks for a
table of the specified name owned by the database owner. If the table exists, its columns are returned.
[ @qualifier=] 'qualifier'
Is the name of the table qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support
three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In
some products, it represents the server name of the database environment of the table.
[ @col_type=] 'col_type'
Is the column type. col_type is char(1), with a default of R. Type R returns the optimal column or set of columns
that, by retrieving values from the column or columns, allows for any row in the specified table to be uniquely
identified. A column can be either a pseudocolumn specifically designed for this purpose, or the column or
columns of any unique index for the table. Type V returns the column or columns in the specified table, if any, that
are automatically updated by the data source when any value in the row is updated by any transaction.
[ @scope=] 'scope'
Is the minimum required scope of the ROWID. scope is char(1), with a default of T. Scope C specifies that the
ROWID is valid only when positioned on that row. Scope T specifies that the ROWID is valid for the transaction.
[ @nullable=] 'nullable'
Is whether the special columns can accept a null value. nullable is char(1), with a default of U. O specifies special
columns that do not allow null values. U specifies columns that are partially nullable.
[ @ODBCVer=] 'ODBCVer'
Is the ODBC version being used. ODBCVer is int(4), with a default of 2. This indicates ODBC version 2.0. For more
information about the difference between ODBC version 2.0 and ODBC version 3.0, see the ODBC
SQLSpecialColumns specification for ODBC version 3.0.

Return Code Values


None

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

SCOPE smallint Actual scope of the row ID. Can be 0, 1,


or 2. SQL Server always returns 0. This
field always returns a value.

0 = SQL_SCOPE_CURROW. The row ID


is guaranteed to be valid only while
positioned on that row. A later reselect
using the row ID may not return a row
if the row was updated or deleted by
another transaction.

1 = SQL_SCOPE_TRANSACTION. The
row ID is guaranteed to be valid for the
duration of the current transaction.

2 = SQL_SCOPE_SESSION. The row ID is


guaranteed to be valid for the duration
of the session (across transaction
boundaries).

COLUMN_NAME sysname Column name for each column of the


tablereturned. This field always returns
a value.

DATA_TYPE smallint ODBC SQL data type.

TYPE_NAME sysname Data source-dependent data type


name; for example, char, varchar,
money, or text.

PRECISION Int Precision of the column on the data


source. This field always returns a value.

LENGTH Int Length, in bytes, required for the data


type in its binary form in the data
source, for example, 10 for char(10), 4
for integer, and 2 for smallint.
COLUMN NAME DATA TYPE DESCRIPTION

SCALE smallint Scale of the column on the data source.


NULL is returned for data types for
which scale is not applicable.

PSEUDO_COLUMN smallint Indicates whether the column is a


pseudocolumn. SQL Server always
returns 1:

0 = SQL_PC_UNKNOWN

1 = SQL_PC_NOT_PSEUDO

2 = SQL_PC_PSEUDO

Remarks
sp_special_columns is equivalent to SQLSpecialColumns in ODBC. The results returned are ordered by SCOPE.

Permissions
Requires SELECT permission on the schema.

Examples: Azure SQL Data Warehouse and Parallel Data Warehouse


The following example returns information about the column that uniquely identifies rows in the FactFinance
table.

-- Uses AdventureWorks

EXEC sp_special_columns_100 @table_name = 'FactFinance';

See Also
SQL Data Warehouse Stored Procedures
SQL Server Agent Stored Procedures (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
SQL Server supports the following system stored procedures that are used by SQL Server Agent to manage
scheduled and event-driven activities.

sp_add_alert sp_help_jobactivity

sp_add_category sp_help_jobcount

sp_add_job sp_help_jobhistory

sp_add_jobschedule sp_help_jobs_in_schedule

sp_add_jobserver sp_help_jobschedule

sp_add_jobstep sp_help_jobserver

sp_add_notification sp_help_jobstep

sp_add_operator sp_help_jobsteplog

sp_add_schedule sp_help_notification

sp_add_targetservergroup sp_help_operator

sp_add_targetsvrgrp_member sp_help_proxy

sp_apply_job_to_targets sp_help_schedule

sp_attach_schedule sp_help_targetserver

sp_cycle_agent_errorlog sp_help_targetservergroup

sp_cycle_errorlog sp_manage_jobs_by_login

sp_delete_alert sp_msx_defect

sp_delete_category sp_msx_enlist

sp_delete_job sp_msx_get_account

sp_delete_jobschedule sp_msx_set_account

sp_delete_jobserver sp_notify_operator
sp_delete_jobstep sp_post_msx_operation

sp_delete_jobsteplog sp_purge_jobhistory

sp_delete_notification sp_remove_job_from_targetss

sp_delete_operator sp_resync_targetserver

sp_delete_proxy sp_revoke_login_from_proxy

sp_delete_schedule sp_revoke_proxy_from_subsystem

sp_delete_targetserver sp_start_job

sp_delete_targetservergroup sp_stop_job

sp_delete_targetsvrgrp_member sp_update_alert

sp_detach_schedule sp_update_category

sp_enum_login_for_proxy sp_update_job

sp_enum_proxy_for_subsystem sp_update_jobschedule

sp_enum_sqlagent_subsystems sp_update_jobstep

sp_grant_proxy_to_subsystem sp_update_notification

sp_grant_login_to_proxy sp_update_operator

sp_help_alert sp_update_proxy

sp_help_category sp_update_schedule

sp_help_downloadlist sp_update_targetservergroup

sp_help_job

See Also
System Stored Procedures (Transact-SQL)
sp_add_alert (Transact-SQL)
11/17/2017 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates an alert.
Transact-SQL Syntax Conventions

Syntax
sp_add_alert [ @name = ] 'name'
[ , [ @message_id = ] message_id ]
[ , [ @severity = ] severity ]
[ , [ @enabled = ] enabled ]
[ , [ @delay_between_responses = ] delay_between_responses ]
[ , [ @notification_message = ] 'notification_message' ]
[ , [ @include_event_description_in = ] include_event_description_in ]
[ , [ @database_name = ] 'database' ]
[ , [ @event_description_keyword = ] 'event_description_keyword_pattern' ]
[ , { [ @job_id = ] job_id | [ @job_name = ] 'job_name' } ]
[ , [ @raise_snmp_trap = ] raise_snmp_trap ]
[ , [ @performance_condition = ] 'performance_condition' ]
[ , [ @category_name = ] 'category' ]
[ , [ @wmi_namespace = ] 'wmi_namespace' ]
[ , [ @wmi_query = ] 'wmi_query' ]

Arguments
[ @name = ] 'name'
The name of the alert. The name appears in the e-mail or pager message sent in response to the alert. It must be
unique and can contain the percent (%) character. name is sysname, with no default.
[ @message_id = ] message_id
The message error number that defines the alert. (It usually corresponds to an error number in the sysmessages
table.) message_id is int, with a default of 0. If severity is used to define the alert, message_id must be 0 or NULL.

NOTE
Only sysmessages errors written to the Microsoft Windows application log can cause an alert to be sent.

[ @severity = ] severity
The severity level (from 1 through 25) that defines the alert. Any SQL Server message stored in the sysmessages
table sent to the Microsoft Windows application log with the indicated severity causes the alert to be sent. severity
is int, with a default of 0. If message_id is used to define the alert, severity must be 0.
[ @enabled = ] enabled
Indicates the current status of the alert. enabled is tinyint, with a default of 1 (enabled). If 0, the alert is not
enabled and does not fire.
[ @delay_between_responses = ] delay_between_responses
The wait period, in seconds, between responses to the alert. delay_between_responsesis int, with a default of 0,
which means there is no waiting between responses (each occurrence of the alert generates a response). The
response can be in either or both of these forms:
One or more notifications sent through e-mail or pager.
A job to execute.
By setting this value, it is possible to prevent, for example, unwanted e-mail messages from being sent
when an alert repeatedly occurs in a short period of time.
[ @notification_message = ] 'notification_message'
Is an optional additional message sent to the operator as part of the e-mail, net send, or pager notification.
notification_message is nvarchar(512), with a default of NULL. Specifying notification_message is useful
for adding special notes such as remedial procedures.
[ @include_event_description_in = ] include_event_description_in
Is whether the description of the SQL Server error should be included as part of the notification message.
include_event_description_inis tinyint, with a default of 5 (e-mail and net send), and can have one or more
of these values combined with an OR logical operator.

IMPORTANT
The Pager and net send options will be removed from SQL Server Agent in a future version of Microsoft SQL Server. Avoid
using these features in new development work, and plan to modify applications that currently use these features.

VALUE DESCRIPTION

0 None

1 E-mail

2 Pager

4 net send

[ @database_name = ] 'database'
The database in which the error must occur for the alert to fire. If databaseis not supplied, the alert fires regardless
of where the error occurred. database is sysname. Names that are enclosed in brackets ([ ]) are not allowed. The
default value is NULL.
[ @event_description_keyword = ] 'event_description_keyword_pattern'
The sequence of characters that the description of the SQL Server error must be like. Transact-SQL LIKE expression
pattern-matching characters can be used. event_description_keyword_pattern is nvarchar(100), with a default of
NULL. This parameter is useful for filtering object names (for example, %customer_table%).
[ @job_id = ] job_id
The job identification number of the job to run in response to this alert. job_id is uniqueidentifier, with a default
of NULL.
[ @job_name = ] 'job_name'
The name of the job to be executed in response to this alert. job_nameis sysname, with a default of NULL.
NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @raise_snmp_trap = ] raise_snmp_trap
Not implemented in SQL Server version 7.0. raise_snmp_trap is tinyint, with a default of 0.
[ @performance_condition = ] 'performance_condition'
Is a value expressed in the format 'itemcomparatorvalue'. performance_condition is nvarchar(512) with a default
of NULL, and consists of these elements.

FORMAT ELEMENT DESCRIPTION

Item A performance object, performance counter, or named


instance of the counter

Comparator One of these operators: >, <, or =

Value Numeric value of the counter

[ @category_name = ] 'category'
The name of the alert category. category is sysname, with a default of NULL.
[ @wmi_namespace= ] 'wmi_namespace'
The WMI namespace to query for events. wmi_namespace is sysname, with a default of NULL. Only namespaces
on the local server are supported.
[ @wmi_query= ] 'wmi_query'
The query that specifies the WMI event for the alert. wmi_query is nvarchar(512), with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_add_alert must be run from the msdb database.
These are the circumstances under which errors/messages generated by SQL Server and SQL Server applications
are sent to the Windows application log and can therefore raise alerts:
Severity 19 or higher sys.messages errors
Any RAISERROR statement invoked with WITH LOG syntax
Any sys.messages error modified or created using sp_altermessage
Any event logged using xp_logevent
SQL Server Management Studio provides an easy, graphical way to manage the entire alerting system and
is the recommended way to configure an alert infrastructure.
If an alert is not functioning properly, check whether:
The SQL Server Agent service is running.
The event appeared in the Windows application log.
The alert is enabled.
Events generated with xp_logevent occur in the master database. Therefore, xp_logevent does not trigger
an alert unless the @database_name for the alert is 'master' or NULL.

Permissions
By default, only members of the sysadmin fixed server role can execute sp_add_alert.

Examples
The following example adds an alert (Test Alert) that runs the Back up the AdventureWorks2012 Database job when
fired.

NOTE
This example assumes that the message 55001 and the Back up the AdventureWorks2012 Database job already exist. The
example is shown for illustrative purposes only.

USE msdb ;
GO

EXEC dbo.sp_add_alert
@name = N'Test Alert',
@message_id = 55001,
@severity = 0,
@notification_message = N'Error 55001 has occurred. The database will be backed up...',
@job_name = N'Back up the AdventureWorks2012 Database' ;
GO

See Also
sp_add_notification (Transact-SQL)
sp_altermessage (Transact-SQL)
sp_delete_alert (Transact-SQL)
sp_help_alert (Transact-SQL)
sp_update_alert (Transact-SQL)
sys.sysperfinfo (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_add_category (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds the specified category of jobs, alerts, or operators to the server.
Transact-SQL Syntax Conventions

Syntax
sp_add_category
[ [ @class = ] 'class', ]
[ [ @type = ] 'type', ]
{ [ @name = ] 'name' }

Arguments
[ @class = ] 'class'
The class of the category to be added. class is varchar(8) with a default value of JOB, and can be one of these
values.

VALUE DESCRIPTION

JOB Adds a job category.

ALERT Adds an alert category.

OPERATOR Adds an operator category.

[ @type = ] 'type'
The type of category to be added. type is varchar(12), with a default value of LOCAL, and can be one of these
values.

VALUE DESCRIPTION

LOCAL A local job category.

MULTI-SERVER A multiserver job category.

NONE A category for a class other than JOB.

[ @name = ] 'name'
The name of the category to be added. The name must be unique within the specified class. name is sysname,
with no default.

Return Code Values


0 (success) or 1 (failure)
Result Sets
None

Remarks
sp_add_category must be run from the msdb database.

Permissions
Only members of the sysadmin fixed server role can execute sp_add_category.

Examples
The following example creates a local job category named AdminJobs .

USE msdb ;
GO

EXEC dbo.sp_add_category
@class=N'JOB',
@type=N'LOCAL',
@name=N'AdminJobs' ;
GO

See Also
sp_delete_category (Transact-SQL)
sp_help_category (Transact-SQL)
sp_update_category (Transact-SQL)
dbo.sysjobs (Transact-SQL)
dbo.sysjobservers (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_add_job (Transact-SQL)
11/17/2017 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a new job executed by the SQLServerAgent service.
Transact-SQL Syntax Conventions

Syntax
sp_add_job [ @job_name = ] 'job_name'
[ , [ @enabled = ] enabled ]
[ , [ @description = ] 'description' ]
[ , [ @start_step_id = ] step_id ]
[ , [ @category_name = ] 'category' ]
[ , [ @category_id = ] category_id ]
[ , [ @owner_login_name = ] 'login' ]
[ , [ @notify_level_eventlog = ] eventlog_level ]
[ , [ @notify_level_email = ] email_level ]
[ , [ @notify_level_netsend = ] netsend_level ]
[ , [ @notify_level_page = ] page_level ]
[ , [ @notify_email_operator_name = ] 'email_name' ]
[ , [ @notify_netsend_operator_name = ] 'netsend_name' ]
[ , [ @notify_page_operator_name = ] 'page_name' ]
[ , [ @delete_level = ] delete_level ]
[ , [ @job_id = ] job_id OUTPUT ]

Arguments
[ @job_name = ] 'job_name'
The name of the job. The name must be unique and cannot contain the percent (%) character. job_nameis
nvarchar(128), with no default.
[ @enabled = ] enabled
Indicates the status of the added job. enabledis tinyint, with a default of 1 (enabled). If 0, the job is not enabled
and does not run according to its schedule; however, it can be run manually.
[ @description = ] 'description'
The description of the job. description is nvarchar(512), with a default of NULL. If description is omitted, "No
description available" is used.
[ @start_step_id = ] step_id
The identification number of the first step to execute for the job. step_idis int, with a default of 1.
[ @category_name = ] 'category'
The category for the job. categoryis sysname, with a default of NULL.
[ @category_id = ] category_id
A language-independent mechanism for specifying a job category. category_idis int, with a default of NULL.
[ @owner_login_name = ] 'login'
The name of the login that owns the job. loginis sysname, with a default of NULL, which is interpreted as the
current login name. Only members of the sysadmin fixed server role can set or change the value for
@owner_login_name. If users who are not members of the sysadmin role set or change the value of
@owner_login_name, execution of this stored procedure fails and an error is returned.
[ @notify_level_eventlog = ] eventlog_level
A value indicating when to place an entry in the Microsoft Windows application log for this job. eventlog_levelis
int, and can be one of these values.

VALUE DESCRIPTION

0 Never

1 On success

2 (default) On failure

3 Always

[ @notify_level_email = ] email_level
A value that indicates when to send an e-mail upon the completion of this job. email_levelis int, with a default of 0,
which indicates never. email_leveluses the same values as eventlog_level.
[ @notify_level_netsend = ] netsend_level
A value that indicates when to send a network message upon the completion of this job. netsend_levelis int, with a
default of 0, which indicates never. netsend_level uses the same values as eventlog_level.
[ @notify_level_page = ] page_level
A value that indicates when to send a page upon the completion of this job. page_levelis int, with a default of 0,
which indicates never. page_leveluses the same values as eventlog_level.
[ @notify_email_operator_name = ] 'email_name'
The e-mail name of the person to send e-mail to when email_level is reached. email_name is sysname, with a
default of NULL.
[ @notify_netsend_operator_name = ] 'netsend_name'
The name of the operator to whom the network message is sent upon completion of this job. netsend_nameis
sysname, with a default of NULL.
[ @notify_page_operator_name = ] 'page_name'
The name of the person to page upon completion of this job. page_nameis sysname, with a default of NULL.
[ @delete_level = ] delete_level
A value that indicates when to delete the job. delete_valueis int, with a default of 0, which means never.
delete_leveluses the same values as eventlog_level.

NOTE
When delete_level is 3, the job is executed only once, regardless of any schedules defined for the job. Furthermore, if a job
deletes itself, all history for the job is also deleted.

[ @job_id = ] job_idOUTPUT
The job identification number assigned to the job if created successfully. job_idis an output variable of type
uniqueidentifier, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
@originating_server exists in sp_add_job, but is not listed under Arguments. @originating_server is reserved
for internal use.
After sp_add_job has been executed to add a job, sp_add_jobstep can be used to add steps that perform the
activities for the job. sp_add_jobschedule can be used to create the schedule that the SQL Server Agent service
uses to execute the job. Use sp_add_jobserver to set the SQL Server instance where the job executes, and
sp_delete_jobserver to remove the job from the SQL Server instance.
If the job will execute on one or more target servers in a multiserver environment, use sp_apply_job_to_targets
to set the target servers or target server groups for the job. To remove jobs from target servers or target server
groups, use sp_remove_job_from_targets.
SQL Server Management Studio provides an easy, graphical way to manage jobs, and is the recommended way to
create and manage the job infrastructure.

Permissions
To run this stored procedure, users must be a member of the sysadmin fixed server role, or be granted one of the
following SQL Server Agent fixed database roles, which reside in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For information about the specific permissions that are associated with each of these fixed database roles,
see SQL Server Agent Fixed Database Roles.
Only members of the sysadmin fixed server role can set or change the value for @owner_login_name. If
users who are not members of the sysadmin role set or change the value of @owner_login_name,
execution of this stored procedure fails and an error is returned.

Examples
A. Adding a job
This example adds a new job named NightlyBackups .

USE msdb ;
GO

EXEC dbo.sp_add_job
@job_name = N'NightlyBackups' ;
GO

B. Adding a job with pager, e -mail, and net send information


This example creates a job named Ad hoc Sales Data Backup that notifies François Ajenstat (by pager, e-mail, or
network pop-up message) if the job fails, and deletes the job upon successful completion.
NOTE
This example assumes that an operator named François Ajenstat and a login named françoisa already exist.

USE msdb ;
GO

EXEC dbo.sp_add_job
@job_name = N'Ad hoc Sales Data Backup',
@enabled = 1,
@description = N'Ad hoc backup of sales data',
@owner_login_name = N'françoisa',
@notify_level_eventlog = 2,
@notify_level_email = 2,
@notify_level_netsend = 2,
@notify_level_page = 2,
@notify_email_operator_name = N'François Ajenstat',
@notify_netsend_operator_name = N'François Ajenstat',
@notify_page_operator_name = N'François Ajenstat',
@delete_level = 1 ;
GO

See Also
sp_add_schedule (Transact-SQL)
sp_add_jobstep (Transact-SQL)
sp_add_jobserver (Transact-SQL)
sp_apply_job_to_targets (Transact-SQL)
sp_delete_job (Transact-SQL)
sp_delete_jobserver (Transact-SQL)
sp_remove_job_from_targets (Transact-SQL)
sp_help_job (Transact-SQL)
sp_help_jobstep (Transact-SQL)
sp_update_job (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_add_jobschedule (Transact-SQL)
1/2/2018 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a schedule for a job.
Transact-SQL Syntax Conventions

Syntax
sp_add_jobschedule [ @job_id = ] job_id, | [ @job_name = ] 'job_name', [ @name = ] 'name'
[ , [ @enabled = ] enabled_flag ]
[ , [ @freq_type = ] frequency_type ]
[ , [ @freq_interval = ] frequency_interval ]
[ , [ @freq_subday_type = ] frequency_subday_type ]
[ , [ @freq_subday_interval = ] frequency_subday_interval ]
[ , [ @freq_relative_interval = ] frequency_relative_interval ]
[ , [ @freq_recurrence_factor = ] frequency_recurrence_factor ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @active_start_time = ] active_start_time ]
[ , [ @active_end_time = ] active_end_time ]
[ , [ @schedule_id = ] schedule_id OUTPUT ]

Arguments
[ @job_id= ] job_id
Job identification number of the job to which the schedule is added. job_id is uniqueidentifier, with no default.
[ @job_name= ] 'job_name'
Name of the job to which the schedule is added. job_name is nvarchar(128), with no default.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @name= ] 'name'
Name of the schedule. name is nvarchar(128), with no default.
[ @enabled= ] enabled_flag
Indicates the current status of the schedule. enabled_flag is tinyint, with a default of 1 (enabled). If 0, the schedule
is not enabled. When the schedule is disabled, the job will not be run.
[ @freq_type= ] frequency_type
Value that indicates when the job is to be executed. frequency_type is int, with a default of 0, and can be one of the
following values:

VALUE DESCRIPTION

1 Once
VALUE DESCRIPTION

4 Daily

8 Weekly

16 Monthly

32 Monthly, relative to frequency_interval.

64 Run when the SQL Server Agent service starts.

128 Run when the computer is idle.

[ @freq_interval= ] frequency_interval
Day that the job is executed. frequency_interval is int, with a default of 0, and depends on the value of
frequency_type as indicated in the following table:

VALUE EFFECT

1 (once) frequency_interval is unused.

4 (daily) Every frequency_interval days.

8 (weekly) frequency_interval is one or more of the following (combined


with an OR logical operator):

1 = Sunday

2 = Monday

4 = Tuesday

8 = Wednesday

16 = Thursday

32 = Friday

64 = Saturday

16 (monthly) On the frequency_interval day of the month.


VALUE EFFECT

32 (monthly relative) frequency_interval is one of the following:

1 = Sunday

2 = Monday

3 = Tuesday

4 = Wednesday

5 = Thursday

6 = Friday

7 = Saturday

8 = Day

9 = Weekday

10 = Weekend day

64 (when the SQL Server Agent service starts) frequency_interval is unused.

128 frequency_interval is unused.

[ @freq_subday_type= ] frequency_subday_type
Specifies the units for frequency_subday_interval. frequency_subday_type is int, with no default, and can be one of
the following values:

VALUE DESCRIPTION (UNIT)

0x1 At the specified time

0x4 Minutes

0x8 Hours

[ @freq_subday_interval= ] frequency_subday_interval
Number of frequency_subday_type periods to occur between each execution of the job. frequency_subday_interval
is int, with a default of 0.
[ @freq_relative_interval= ] frequency_relative_interval
Further defines the frequency_interval when frequency_type is set to 32 (monthly relative).
frequency_relative_interval is int, with no default, and can be one of the following values:

VALUE DESCRIPTION (UNIT)

1 First

2 Second

4 Third
VALUE DESCRIPTION (UNIT)

8 Fourth

16 Last

frequency_relative_interval indicates the occurrence of the interval. For example, if frequency_relative_interval is


set to 2, frequency_type is set to 32, and frequency_interval is set to 3, the scheduled job would occur on the
second Tuesday of each month.
[ @freq_recurrence_factor= ] frequency_recurrence_factor
Number of weeks or months between the scheduled execution of the job. frequency_recurrence_factor is used only
if frequency_type is set to 8, 16, or 32. frequency_recurrence_factor is int, with a default of 0.
[ @active_start_date= ] active_start_date
Date on which job execution can begin. active_start_date is int, with no default. The date is formatted as
YYYYMMDD. If active_start_date is set, the date must be greater than or equal to 19900101.
After the schedule is created, review the start date and confirm that it is the correct date. For more information, see
the section "Scheduling Start Date" in Create and Attach Schedules to Jobs.
[ @active_end_date= ] active_end_date
Date on which job execution can stop. active_end_date is int, with no default. The date is formatted as YYYYMMDD.
[ @active_start_time= ] active_start_time
Time on any day between active_start_date and active_end_date to begin job execution. active_start_time is int,
with no default. The time is formatted as HHMMSS on a 24-hour clock.
[ @active_end_time=active_end_time
Time on any day between active_start_date and active_end_date to end job execution. active_end_time is int, with
no default. The time is formatted as HHMMSS on a 24-hour clock.
[ @schedule_id=schedule_idOUTPUT
Schedule identification number assigned to the schedule if it is created successfully. schedule_id is an output
variable of type int, with no default.
[ @schedule_uid= ] schedule_uidOUTPUT
A unique identifier for the schedule. schedule_uid is a variable of type uniqueidentifier.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Job schedules can now be managed independently of jobs. To add a schedule to a job, use sp_add_schedule to
create the schedule and sp_attach_schedule to attach the schedule to a job.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.

Example
The following example assigns a job schedule to SaturdayReports which will execute every Saturday at 2:00
AM.

EXEC msdb.dbo.sp_add_jobschedule
@job_name = N'SaturdayReports', -- Job name
@name = N'Weekly_Sat_2AM', -- Schedule name
@freq_type = 8, -- Weekly
@freq_interval = 64, -- Saturday
@freq_recurrence_factor = 1, -- every week
@active_start_time = 20000 -- 2:00 AM

See Also
Create and Attach Schedules to Jobs
Schedule a Job
Create a Schedule
SQL Server Agent Stored Procedures (Transact-SQL)
sp_add_schedule (Transact-SQL)
sp_update_schedule (Transact-SQL)
sp_delete_schedule (Transact-SQL)
sp_help_schedule (Transact-SQL)
sp_attach_schedule (Transact-SQL)
sp_add_jobserver (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Targets the specified job at the specified server.
Transact-SQL Syntax Conventions

Syntax
sp_add_jobserver [ @job_id = ] job_id | [ @job_name = ] 'job_name'
[ , [ @server_name = ] 'server' ]

Arguments
[ @job_id = ] job_id
The identification number of the job. job_id is uniqueidentifier, with a default of NULL.
[ @job_name = ] 'job_name'
The name of the job. job_name is sysname, with a default of NULL.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @server_name = ] 'server'
The name of the server at which to target the job. server is nvarchar(30), with a default of N'(LOCAL)'. servercan
be either (LOCAL) for a local server, or the name of an existing target server.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
@automatic_post exists in sp_add_jobserver, but is not listed under Arguments. @automatic_post is reserved
for internal use.
SQL Server Management Studio provides an easy, graphical way to manage jobs, and is the recommended way to
create and manage the job infrastructure.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Only members of the sysadmin fixed server role can execute sp_add_jobserver for jobs that involve
multiple servers.

Examples
A. Assigning a job to the local server
The following example assigns the job NightlyBackups to run on the local server.

NOTE
This example assumes that the NightlyBackups job already exists.

USE msdb ;
GO

EXEC dbo.sp_add_jobserver
@job_name = N'NightlyBackups' ;
GO

B. Assigning a job to run on a different server


The following example assigns the multiserver job Weekly Sales Backups to the server SEATTLE2 .

NOTE
This example assumes that the Weekly Sales Backups job already exists and that SEATTLE2 is registered as a target
server for the current instance.

USE msdb ;
GO

EXEC dbo.sp_add_jobserver
@job_name = N'Weekly Sales Backups',
@server_name = N'SEATTLE2' ;
GO

See Also
sp_apply_job_to_targets (Transact-SQL)
sp_delete_jobserver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_add_jobstep (Transact-SQL)
11/17/2017 • 7 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a step (operation) to a job.
Transact-SQL Syntax Conventions

Syntax
sp_add_jobstep [ @job_id = ] job_id | [ @job_name = ] 'job_name'
[ , [ @step_id = ] step_id ]
{ , [ @step_name = ] 'step_name' }
[ , [ @subsystem = ] 'subsystem' ]
[ , [ @command = ] 'command' ]
[ , [ @additional_parameters = ] 'parameters' ]
[ , [ @cmdexec_success_code = ] code ]
[ , [ @on_success_action = ] success_action ]
[ , [ @on_success_step_id = ] success_step_id ]
[ , [ @on_fail_action = ] fail_action ]
[ , [ @on_fail_step_id = ] fail_step_id ]
[ , [ @server = ] 'server' ]
[ , [ @database_name = ] 'database' ]
[ , [ @database_user_name = ] 'user' ]
[ , [ @retry_attempts = ] retry_attempts ]
[ , [ @retry_interval = ] retry_interval ]
[ , [ @os_run_priority = ] run_priority ]
[ , [ @output_file_name = ] 'file_name' ]
[ , [ @flags = ] flags ]
[ , { [ @proxy_id = ] proxy_id
| [ @proxy_name = ] 'proxy_name' } ]

Arguments
[ @job_id = ] job_id
The identification number of the job to which to add the step. job_id is uniqueidentifier, with a default of NULL.
[ @job_name = ] 'job_name'
The name of the job to which to add the step. job_name is sysname, with a default of NULL.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @step_id = ] step_id
The sequence identification number for the job step. Step identification numbers start at 1 and increment without
gaps. If a step is inserted in the existing sequence, the sequence numbers are adjusted automatically. A value is
provided if step_id is not specified. step_idis int, with a default of NULL.
[ @step_name = ] 'step_name'
The name of the step. step_nameis sysname, with no default.
[ @subsystem = ] 'subsystem'
The subsystem used by the SQL Server Agent service to execute command. subsystem is nvarchar(40), and can
be one of these values.

VALUE DESCRIPTION

'ACTIVESCRIPTING' Active Script

** Important *\* This feature will be removed in a future


version of Microsoft SQL Server. Avoid using this feature in
new development work, and plan to modify applications that
currently use this feature.

'CMDEXEC' Operating-system command or executable program

'DISTRIBUTION' Replication Distribution Agent job

'SNAPSHOT' Replication Snapshot Agent job

'LOGREADER' Replication Log Reader Agent job

'MERGE' Replication Merge Agent job

'QueueReader' Replication Queue Reader Agent job

'ANALYSISQUERY' Analysis Services query (MDX, DMX).

'ANALYSISCOMMAND' Analysis Services command (XMLA).

'Dts' Integration Services package execution

'PowerShell' PowerShell Script

'TSQL' (default) Transact-SQL statement

[ @command= ] 'command'
The commands to be executed by SQLServerAgent service through subsystem. command is nvarchar(max),
with a default of NULL. SQL Server Agent provides token substitution that gives you the same flexibility that
variables provide when you write software programs.

IMPORTANT
An escape macro must now accompany all tokens used in job steps, or else those job steps will fail. In addition, you must
now enclose token names in parentheses and place a dollar sign ( $ ) at the beginning of the token syntax. For example:
$(ESCAPE_ macro name (DATE))

For more information about these tokens and updating your job steps to use the new token syntax, see Use
Tokens in Job Steps.
IMPORTANT
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). Note that in this
release, use of tokens is extended to all alerting.
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.

[ @additional_parameters= ] 'parameters'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed. parameters is
ntext, with a default of NULL.
[ @cmdexec_success_code = ] code
The value returned by a CmdExec subsystem command to indicate that command executed successfully. codeis
int, with a default of 0.
[ @on_success_action= ] success_action
The action to perform if the step succeeds. success_actionis tinyint, and can be one of these values.

VALUE DESCRIPTION (ACTION)

1 (default) Quit with success

2 Quit with failure

3 Go to next step

4 Go to step on_success_step_id

[ @on_success_step_id = ] success_step_id
The ID of the step in this job to execute if the step succeeds and success_actionis 4. success_step_idis int, with a
default of 0.
[ @on_fail_action= ] fail_action
The action to perform if the step fails. fail_actionis tinyint, and can be one of these values.

VALUE DESCRIPTION (ACTION)

1 Quit with success

2 (default) Quit with failure

3 Go to next step

4 Go to step on_fail_step_id

[ @on_fail_step_id= ] fail_step_id
The ID of the step in this job to execute if the step fails and fail_actionis 4. fail_step_idis int, with a default of 0.
[ @server =] 'server'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed. serveris
nvarchar(30), with a default of NULL.
[ @database_name= ] 'database'
The name of the database in which to execute a Transact-SQL step. database is sysname, with a default of NULL,
in which case the master database is used. Names that are enclosed in brackets ([ ]) are not allowed. For an
ActiveX job step, the database is the name of the scripting language that the step uses.
[ @database_user_name= ] 'user'
The name of the user account to use when executing a Transact-SQL step. user is sysname, with a default of NULL.
When user is NULL, the step runs in the job owner's user context on database. SQL Server Agent will include this
parameter only if the job owner is a SQL Server sysadmin. If so, the given Transact-SQL step will be executed in
the context of the given SQL Server user name. If the job owner is not a SQL Server sysadmin, then the Transact-
SQL step will always be executed in the context of the login that owns this job, and the @database_user_name
parameter will be ignored.
[ @retry_attempts= ] retry_attempts
The number of retry attempts to use if this step fails. retry_attemptsis int, with a default of 0, which indicates no
retry attempts.
[ @retry_interval= ] retry_interval
The amount of time in minutes between retry attempts. retry_intervalis int, with a default of 0, which indicates a 0-
minute interval.
[ @os_run_priority = ] run_priority
Reserved.
[ @output_file_name= ] 'file_name'
The name of the file in which the output of this step is saved. file_nameis nvarchar(200), with a default of NULL.
file_namecan include one or more of the tokens listed under command. This parameter is valid only with
commands running on the Transact-SQL, CmdExec, PowerShell, Integration Services, or Analysis Services
subsystems.
[ @flags= ] flags
Is an option that controls behavior. flags is int, and can be one of these values.

VALUE DESCRIPTION

0 (default) Overwrite output file

2 Append to output file

4 Write Transact-SQL job step output to step history

8 Write log to table (overwrite existing history)

16 Write log to table (append to existing history)

32 Write all output to job history

64 Create a Windows event to use as a signal for the Cmd


jobstep to abort

[ @proxy_id = ] proxy_id
The id number of the proxy that the job step runs as. proxy_id is type int, with a default of NULL. If no proxy_id is
specified, no proxy_name is specified, and no user_name is specified, the job step runs as the service account for
SQL Server Agent.
[ @proxy_name = ] 'proxy_name'
The name of the proxy that the job step runs as. proxy_name is type sysname, with a default of NULL. If no
proxy_id is specified, no proxy_name is specified, and no user_name is specified, the job step runs as the service
account for SQL Server Agent.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_add_jobstep must be run from the msdb database.
SQL Server Management Studio provides an easy, graphical way to manage jobs, and is the recommended way to
create and manage the job infrastructure.
A job step must specify a proxy unless the creator of the job step is a member of the sysadmin fixed security role.
A proxy may be identified by proxy_name or proxy_id.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
The creator of the job step must have access to the proxy for the job step. Members of the sysadmin fixed
server role have access to all proxies. Other users must be explicitly granted access to a proxy.

Examples
The following example creates a job step that changes database access to read-only for the Sales database. In
addition, this example specifies 5 retry attempts, with each retry to occur after a 5 minute wait.

NOTE
This example assumes that the Weekly Sales Data Backup job already exists.
USE msdb;
GO
EXEC sp_add_jobstep
@job_name = N'Weekly Sales Data Backup',
@step_name = N'Set database to read only',
@subsystem = N'TSQL',
@command = N'ALTER DATABASE SALES SET READ_ONLY',
@retry_attempts = 5,
@retry_interval = 5 ;
GO

See Also
View or Modify Jobs
sp_add_job (Transact-SQL)
sp_add_schedule (Transact-SQL)
sp_delete_jobstep (Transact-SQL)
sp_help_job (Transact-SQL)
sp_help_jobstep (Transact-SQL)
sp_update_jobstep (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_add_notification (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sets up a notification for an alert.

Syntax
sp_add_notification [ @alert_name = ] 'alert' ,
[ @operator_name = ] 'operator' ,
[ @notification_method = ] notification_method

Arguments
[ @alert_name= ] 'alert'
The alert for this notification. alert is sysname, with no default.
[ @operator_name= ] 'operator'
The operator to be notified when the alert occurs. operator is sysname, with no default.
[ @notification_method= ] notification_method
The method by which the operator is notified. notification_method is tinyint, with no default. notification_method
can be one or more of these values combined with an OR logical operator.

VALUE DESCRIPTION

1 E-mail

2 Pager

4 net send

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_add_notification must be run from the msdb database.
SQL Server Management Studio provides an easy, graphical way to manage the entire alerting system. Using
Management Studio is the recommended way to configure your alert infrastructure.
To send a notification in response to an alert, you must first configure SQL Server Agent to send mail.
If a failure occurs when sending an e-mail message or pager notification, the failure is reported in the SQL Server
Agent service error log.

Permissions
Only members of the sysadmin fixed server role can execute sp_add_notification.

Examples
The following example adds an e-mail notification for the specified alert ( Test Alert ).

NOTE: This example assumes that Test Alert already exists and that François Ajenstat is a valid operator
name.

USE msdb ;
GO

EXEC dbo.sp_add_notification
@alert_name = N'Test Alert',
@operator_name = N'François Ajenstat',
@notification_method = 1 ;
GO

See also
sp_delete_notification (Transact-SQL)
sp_help_notification (Transact-SQL)
sp_update_notification (Transact-SQL)
sp_add_operator (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_add_operator (Transact-SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates an operator (notification recipient) for use with alerts and jobs.
Transact-SQL Syntax Conventions

Syntax
sp_add_operator [ @name = ] 'name'
[ , [ @enabled = ] enabled ]
[ , [ @email_address = ] 'email_address' ]
[ , [ @pager_address = ] 'pager_address' ]
[ , [ @weekday_pager_start_time = ] weekday_pager_start_time ]
[ , [ @weekday_pager_end_time = ] weekday_pager_end_time ]
[ , [ @saturday_pager_start_time = ] saturday_pager_start_time ]
[ , [ @saturday_pager_end_time = ] saturday_pager_end_time ]
[ , [ @sunday_pager_start_time = ] sunday_pager_start_time ]
[ , [ @sunday_pager_end_time = ] sunday_pager_end_time ]
[ , [ @pager_days = ] pager_days ]
[ , [ @netsend_address = ] 'netsend_address' ]
[ , [ @category_name = ] 'category' ]

Arguments
[ @name= ] 'name'
The name of an operator (notification recipient). This name must be unique and cannot contain the percent (%)
character. name is sysname, with no default.
[ @enabled= ] enabled
Indicates the current status of the operator. enabled is tinyint, with a default of 1 (enabled). If 0, the operator is
not enabled and does not receive notifications.
[ @email_address= ] 'email_address'
The e-mail address of the operator. This string is passed directly to the e-mail system. email_address is
nvarchar(100), with a default of NULL.
You can specify either a physical e-mail address or an alias for email_address. For example:
'jdoe' or 'jdoe@xyz.com'

NOTE
You must use the e-mail address for Database Mail.

[ @pager_address= ] 'pager_address'
The pager address of the operator. This string is passed directly to the e-mail system. pager_address is
narchar(100), with a default of NULL.
[ @weekday_pager_start_time= ] weekday_pager_start_time
The time after which SQL Server Agent sends pager notification to the specified operator on the weekdays, from
Monday through Friday. weekday_pager_start_timeis int, with a default of 090000, which indicates 9:00 A.M. on a
24-hour clock, and must be entered using the form HHMMSS.
[ @weekday_pager_end_time= ] weekday_pager_end_time
The time after which SQLServerAgent service no longer sends pager notification to the specified operator on the
weekdays, from Monday through Friday. weekday_pager_end_timeis int, with a default of 180000, which
indicates 6:00 P.M. on a 24-hour clock, and must be entered using the form HHMMSS.
[ @saturday_pager_start_time =] saturday_pager_start_time
The time after which SQLServerAgent service sends pager notification to the specified operator on Saturdays.
saturday_pager_start_time is int, with a default of 090000, which indicates 9:00 A.M. on a 24-hour clock, and must
be entered using the form HHMMSS.
[ @saturday_pager_end_time= ] saturday_pager_end_time
The time after which SQLServerAgent service no longer sends pager notification to the specified operator on
Saturdays. saturday_pager_end_timeis int, with a default of 180000, which indicates 6:00 P.M. on a 24-hour clock,
and must be entered using the form HHMMSS.
[ @sunday_pager_start_time= ] sunday_pager_start_time
The time after which SQLServerAgent service sends pager notification to the specified operator on Sundays.
sunday_pager_start_timeis int, with a default of 090000, which indicates 9:00 A.M. on a 24-hour clock, and must
be entered using the form HHMMSS.
[ @sunday_pager_end_time =] sunday_pager_end_time
The time after which SQLServerAgent service no longer sends pager notification to the specified operator on
Sundays. sunday_pager_end_timeis int, with a default of 180000, which indicates 6:00 P.M. on a 24-hour clock,
and must be entered using the form HHMMSS.
[ @pager_days= ] pager_days
Is a number that indicates the days that the operator is available for pages (subject to the specified start/end
times). pager_daysis tinyint, with a default of 0 indicating the operator is never available to receive a page. Valid
values are from 0 through 127. pager_daysis calculated by adding the individual values for the required days. For
example, from Monday through Friday is 2+4+8+16+32 = 62. The following table lists the value for each day of
the week.

VALUE DESCRIPTION

1 Sunday

2 Monday

4 Tuesday

8 Wednesday

16 Thursday

32 Friday

64 Saturday

[ @netsend_address= ] 'netsend_address'
The network address of the operator to whom the network message is sent. netsend_addressis nvarchar(100),
with a default of NULL.
[ @category_name= ] 'category'
The name of the category for this operator. category is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_add_operator must be run from the msdb database.
Paging is supported by the e-mail system, which must have an e-mail-to-pager capability if you want to use
paging.
SQL Server Management Studio provides an easy, graphical way to manage jobs, and is the recommended way to
create and manage the job infrastructure.

Permissions
Only members of the sysadmin fixed server role can execute sp_add_operator.

Examples
The following example sets up the operator information for danwi . The operator is enabled. SQL Server Agent
sends notifications by pager from Monday through Friday from 8 A.M. to 5 P.M.

USE msdb ;
GO

EXEC dbo.sp_add_operator
@name = N'Dan Wilson',
@enabled = 1,
@email_address = N'danwi',
@pager_address = N'5551290AW@pager.Adventure-Works.com',
@weekday_pager_start_time = 080000,
@weekday_pager_end_time = 170000,
@pager_days = 62 ;
GO

See Also
sp_delete_operator (Transact-SQL)
sp_help_operator (Transact-SQL)
sp_update_operator (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_add_proxy (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds the specified SQL Server Agent proxy.
Transact-SQL Syntax Conventions

Syntax
sp_add_proxy
[ @proxy_name = ] 'proxy_name' ,
[ @enabled = ] is_enabled ,
[ @description = ] 'description' ,
[ @credential_name = ] 'credential_name' ,
[ @credential_id = ] credential_id ,
[ @proxy_id = ] id OUTPUT

Arguments
[ @proxy_name= ] 'proxy_name'
The name of the proxy to create. The proxy_name is sysname, with a default of NULL. When the proxy_name is
NULL or an empty string, the name of the proxy defaults to the user_name supplied.
[ @enabled = ] is_enabled
Specifies whether the proxy is enabled. The is_enabled flag is tinyint, with a default of 1. When is_enabled is 0, the
proxy is not enabled, and cannot be used by a job step.
[ @description= ] 'description'
A description of the proxy. The description is nvarchar(512), with a default of NULL. The description allows you to
document the proxy, but is not otherwise used by SQL Server Agent. Therefore, this argument is optional.
[ @credential_name = ] 'credential_name'
The name of the credential for the proxy. The credential_name is sysname, with a default of NULL. Either
credential_name or credential_id must be specified.
[ @credential_id = ] credential_id
The identification number of the credential for the proxy. The credential_id is int, with a default of NULL. Either
credential_name or credential_id must be specified.
[ @proxy_id= ] id OUTPUT
The proxy identification number assigned to the proxy if created successfully.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None
Remarks
This stored procedure must be run in the msdb database.
A SQL Server Agent proxy manages security for job steps that involve subsystems other than the Transact-SQL
subsystem. Each proxy corresponds to a security credential. A proxy may have access to any number of
subsystems.

Permissions
Only members of the sysadmin fixed security role can execute this procedure.
Members of the sysadmin fixed security role can create job steps that use any proxy. Use the stored procedure
sp_grant_login_to_proxy (Transact-SQL) to grant other logins access to the proxy.

Examples
This example creates a proxy for the credential CatalogApplicationCredential . The code assumes that the
credential already exists. For more information about credentials, see CREATE CREDENTIAL (Transact-SQL).

USE msdb ;
GO

EXEC dbo.sp_add_proxy
@proxy_name = 'Catalog application proxy',
@enabled = 1,
@description = 'Maintenance tasks on catalog application.',
@credential_name = 'CatalogApplicationCredential' ;
GO

See Also
CREATE CREDENTIAL (Transact-SQL)
sp_grant_login_to_proxy (Transact-SQL)
sp_revoke_login_from_proxy (Transact-SQL)
sp_add_schedule (Transact-SQL)
11/17/2017 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a schedule that can be used by any number of jobs.
Transact-SQL Syntax Conventions

Syntax
sp_add_schedule [ @schedule_name = ] 'schedule_name'
[ , [ @enabled = ] enabled ]
[ , [ @freq_type = ] freq_type ]
[ , [ @freq_interval = ] freq_interval ]
[ , [ @freq_subday_type = ] freq_subday_type ]
[ , [ @freq_subday_interval = ] freq_subday_interval ]
[ , [ @freq_relative_interval = ] freq_relative_interval ]
[ , [ @freq_recurrence_factor = ] freq_recurrence_factor ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @active_start_time = ] active_start_time ]
[ , [ @active_end_time = ] active_end_time ]
[ , [ @owner_login_name = ] 'owner_login_name' ]
[ , [ @schedule_uid = ] schedule_uid OUTPUT ]
[ , [ @schedule_id = ] schedule_id OUTPUT ]
[ , [ @originating_server = ] server_name ] /* internal */

Arguments
[ @schedule_name = ] 'schedule_name'
The name of the schedule. schedule_nameis sysname, with no default.
[ @enabled = ] enabled
Indicates the current status of the schedule. enabledis tinyint, with a default of 1 (enabled). If 0, the schedule is
not enabled. When the schedule is not enabled, no jobs will run on this schedule.
[ @freq_type = ] freq_type
A value indicating when a job is to be executed. freq_typeis int, with a default of 0, and can be one of these
values.

VALUE DESCRIPTION

1 Once

4 Daily

8 Weekly

16 Monthly
VALUE DESCRIPTION

32 Monthly, relative to freq_interval

64 Run when SQLServerAgent service starts

128 Run when the computer is idle

[ @freq_interval = ] freq_interval
The days that a job is executed. freq_interval is int, with a default of 1, and depends on the value of freq_type.

VALUE OF FREQ_TYPE EFFECT ON FREQ_INTERVAL

1 (once) freq_interval is unused.

4 (daily) Every freq_interval days.

8 (weekly) freq_interval is one or more of the following (combined with


an OR logical operator):

1 = Sunday

2 = Monday

4 = Tuesday

8 = Wednesday

16 = Thursday

32 = Friday

64 = Saturday

16 (monthly) On the freq_interval day of the month.

32 (monthly relative) freq_interval is one of the following:

1 = Sunday

2 = Monday

3 = Tuesday

4 = Wednesday

5 = Thursday

6 = Friday

7 = Saturday

8 = Day

9 = Weekday

10 = Weekend day

64 (when SQLServerAgent service starts) freq_interval is unused.


VALUE OF FREQ_TYPE EFFECT ON FREQ_INTERVAL

128 freq_interval is unused.

[ @freq_subday_type = ] freq_subday_type
Specifies the units for freq_subday_interval. freq_subday_typeis int, with a default of 0, and can be one of these
values.

VALUE DESCRIPTION (UNIT)

0x1 At the specified time

0x2 Seconds

0x4 Minutes

0x8 Hours

[ @freq_subday_interval = ] freq_subday_interval
The number of freq_subday_type periods to occur between each execution of a job. freq_subday_intervalis int,
with a default of 0. Note: Interval should be longer than 10 seconds. freq_subday_interval is ignored in those
cases where freq_subday_type is equal to 1.
[ @freq_relative_interval = ] freq_relative_interval
A job's occurrence of freq_interval in each month, if freq_interval is 32 (monthly relative).
freq_relative_intervalis int, with a default of 0, and can be one of these values. freq_relative_interval is ignored
in those cases where freq_type is not equal to 32.

VALUE DESCRIPTION (UNIT)

1 First

2 Second

4 Third

8 Fourth

16 Last

[ @freq_recurrence_factor = ] freq_recurrence_factor
The number of weeks or months between the scheduled execution of a job. freq_recurrence_factor is used only
if freq_type is 8, 16, or 32. freq_recurrence_factoris int, with a default of 0.
[ @active_start_date = ] active_start_date
The date on which execution of a job can begin. active_start_dateis int, with a default of NULL, which indicates
today's date. The date is formatted as YYYYMMDD. If active_start_date is not NULL, the date must be greater
than or equal to 19900101.
After the schedule is created, review the start date and confirm that it is the correct date. For more information,
see the section "Scheduling Start Date" in Create and Attach Schedules to Jobs.
For weekly or monthly schedules, the Agent ignores if active_start_date is in the past, and instead uses the
current date. When a SQL Agent schedule is created using sp_add_schedule there is an option to specify the
parameter active_start_date that is the date that job execution will begin. If the schedule type is weekly or
monthly and the active_start_date parameter is set to a date in the past, the active_start_date parameter is
ignored and the current date will be used for active_start_date.
[ @active_end_date = ] active_end_date
The date on which execution of a job can stop. active_end_dateis int, with a default of 99991231, which
indicates December 31, 9999. Formatted as YYYYMMDD.
[ @active_start_time = ] active_start_time
The time on any day between active_start_date and active_end_date to begin execution of a job.
active_start_timeis int, with a default of 000000, which indicates 12:00:00 A.M. on a 24-hour clock, and must be
entered using the form HHMMSS.
[ @active_end_time = ] active_end_time
The time on any day between active_start_date and active_end_date to end execution of a job.
active_end_timeis int, with a default of 235959, which indicates 11:59:59 P.M. on a 24-hour clock, and must be
entered using the form HHMMSS.
[ @owner_login_name= ] 'owner_login_name'
The name of the server principal that owns the schedule. owner_login_name is sysname, with a default of
NULL, which indicates that the schedule is owned by the creator.
[ @schedule_uid= ] schedule_uidOUTPUT
A unique identifier for the schedule. schedule_uid is a variable of type uniqueidentifier.
[ @schedule_id= ] schedule_idOUTPUT
An identifier for the schedule. schedule_id is a variable of type int.
[ @originating_server= ] server_name
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
SQL Server Management Studio provides an easy, graphical way to manage jobs, and is the recommended way
to create and manage the job infrastructure.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Examples
A. Creating a schedule
The following example creates a schedule named RunOnce . The schedule runs one time, at 23:30 on the day
that the schedule is created.

USE msdb ;
GO

EXEC dbo.sp_add_schedule
@schedule_name = N'RunOnce',
@freq_type = 1,
@active_start_time = 233000 ;

GO

B. Creating a schedule, attaching the schedule to multiple jobs


The following example creates a schedule named NightlyJobs . Jobs that use this schedule execute every day
when the time on the server is 01:00 . The example attaches the schedule to the job BackupDatabase and the
job RunReports .

NOTE
This example assumes that the job BackupDatabase and the job RunReports already exist.

USE msdb ;
GO

EXEC sp_add_schedule
@schedule_name = N'NightlyJobs' ,
@freq_type = 4,
@freq_interval = 1,
@active_start_time = 010000 ;
GO

EXEC sp_attach_schedule
@job_name = N'BackupDatabase',
@schedule_name = N'NightlyJobs' ;
GO

EXEC sp_attach_schedule
@job_name = N'RunReports',
@schedule_name = N'NightlyJobs' ;
GO

See Also
Create and Attach Schedules to Jobs
Schedule a Job
Create a Schedule
SQL Server Agent Stored Procedures (Transact-SQL)
sp_add_jobschedule (Transact-SQL)
sp_update_schedule (Transact-SQL)
sp_delete_schedule (Transact-SQL)
sp_help_schedule (Transact-SQL)
sp_attach_schedule (Transact-SQL)
sp_add_targetservergroup (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds the specified server group.
Transact-SQL Syntax Conventions

Syntax
sp_add_targetservergroup [ @name = ] 'name'

Arguments
[ @name=] 'name'
The name of the server group to create. name is sysname, with no default. name cannot contain commas.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Target server groups provide an easy way to target a job at a collection of target servers. For more information,
see sp_apply_job_to_targets.

Permissions
Only members of the sysadmin fixed server role can execute this procedure.

Examples
The following example creates the target server group named Servers Processing Customer Orders .

USE msdb ;
GO

EXEC dbo.sp_add_targetservergroup
'Servers Processing Customer Orders' ;
GO

See Also
sp_apply_job_to_targets (Transact-SQL)
sp_delete_targetservergroup (Transact-SQL)
sp_help_targetservergroup (Transact-SQL)
sp_update_targetservergroup (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_add_targetsvrgrp_member (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adds the specified target server to the specified target server group.
Transact-SQL Syntax Conventions

Syntax
sp_add_targetsvrgrp_member [ @group_name = ] 'group_name' , [ @server_name = ] 'server_name'

Arguments
[ @group_name= ] 'group_name'
The name of the group. group_name is sysname, with no default.
[ @server_name= ] 'server_name'
The name of the server that should be added to the specified group. server_name is nvarchar(30), with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
A target server can be a member of more than one target server group.

Permissions
Only members of the sysadmin fixed server role can execute this procedure.

Examples
The following example adds the group Servers Maintaining Customer Information and adds the LONDON1 server to
that group.

USE msdb ;
GO

EXEC dbo.sp_add_targetsvrgrp_member
@group_name = N'Servers Maintaining Customer Information',
@server_name = N'LONDON1' ;
GO
See Also
sp_delete_targetsvrgrp_member (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_apply_job_to_targets (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Applies a job to one or more target servers or to the target servers belonging to one or more target server
groups.
Transact-SQL Syntax Conventions

Syntax
sp_apply_job_to_targets { [ @job_id = ] job_id | [ @job_name = ] 'job_name' }
[ , [ @target_server_groups = ] 'target_server_groups' ]
[ , [ @target_servers = ] 'target_servers' ]
[ , [ @operation = ] 'operation' ]

Arguments
[ @job_id =] job_id
The job identification number of the job to apply to the specified target servers or target server groups. job_id is
uniqueidentifier, with a default of NULL.
[ @job_name =] 'job_name'
The name of the job to apply to the specified the associated target servers or target server groups. job_name is
sysname, with a default of NULL.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @target_server_groups =] 'target_server_groups'
A comma-separated list of target server groups to which the specified job is to be applied. target_server_groups is
nvarchar(2048), with a default of NULL.
[ @target_servers= ] 'target_servers'
A comma-separated list of target servers to which the specified job is to be applied. target_serversis
nvarchar(2048), with a default of NULL.
[ @operation= ] 'operation'
Is whether the specified job should be applied to or removed from the specified target servers or target server
groups. operationis varchar(7), with a default of APPLY. Valid operations are APPLY and REMOVE.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_apply_job_to_targets provides an easy way to apply (or remove) a job from multiple target servers, and is an
alternative to calling sp_add_jobserver (or sp_delete_jobserver) once for each target server required.

Permissions
Only members of the sysadmin fixed server role can execute this procedure.

Examples
The following example applies the previously created Backup Customer Information job to all the target servers in
the Servers Maintaining Customer Information group.

USE msdb ;
GO

EXEC dbo.sp_apply_job_to_targets
@job_name = N'Backup Customer Information',
@target_server_groups = N'Servers Maintaining Customer Information',
@operation = N'APPLY' ;
GO

See Also
sp_add_jobserver (Transact-SQL)
sp_delete_jobserver (Transact-SQL)
sp_remove_job_from_targets (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_attach_schedule (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sets a schedule for a job.
Transact-SQL Syntax Conventions

Syntax
sp_attach_schedule
{ [ @job_id = ] job_id | [ @job_name = ] 'job_name' } ,
{ [ @schedule_id = ] schedule_id
| [ @schedule_name = ] 'schedule_name' }

Arguments
[ @job_id= ] job_id
The job identification number of the job to which the schedule is added. job_idis uniqueidentifier, with a default
of NULL.
[ @job_name = ] 'job_name'
The name of the job to which the schedule is added. job_nameis sysname, with a default of NULL.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @schedule_id = ] schedule_id
The schedule identification number of the schedule to set for the job. schedule_idis int, with a default of NULL.
[ @schedule_name = ] 'schedule_name'
The name of the schedule to set for the job. schedule_nameis sysname, with a default of NULL.

NOTE
Either schedule_id or schedule_name must be specified, but both cannot be specified.

Remarks
The schedule and the job must have the same owner.
A schedule can be set for more than one job. A job can be run on more than one schedule.
This stored procedure must be run from the msdb database.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
Note that the job owner can attach a job to a schedule and detach a job from a schedule without also
having to be the schedule owner. However, a schedule cannot be deleted if the detach would leave it with
no jobs, unless the caller is the schedule owner.
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
SQL Server checks if the user owns both the job and the schedule.

Examples
The following example creates a schedule named NightlyJobs . Jobs that use this schedule execute every day
when the time on the server is 01:00 . The example attaches the schedule to the job BackupDatabase and the job
RunReports .

NOTE
This example assumes that the job BackupDatabase and the job RunReports already exist.

USE msdb ;
GO

EXEC sp_add_schedule
@schedule_name = N'NightlyJobs' ,
@freq_type = 4,
@freq_interval = 1,
@active_start_time = 010000 ;
GO

EXEC sp_attach_schedule
@job_name = N'BackupDatabase',
@schedule_name = N'NightlyJobs' ;
GO

EXEC sp_attach_schedule
@job_name = N'RunReports',
@schedule_name = N'NightlyJobs' ;
GO

See Also
sp_add_schedule (Transact-SQL)
sp_detach_schedule (Transact-SQL)
sp_delete_schedule (Transact-SQL)
sp_cycle_agent_errorlog (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Closes the current SQL Server Agent error log file and cycles the SQL Server Agent error log extension numbers
just like a server restart. The new SQL Server Agent error log contains a line indicating that the new log has been
created.
Transact-SQL Syntax Conventions

Syntax
sp_cycle_agent_errorlog

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Every time SQL Server Agent is started, the current SQL Server Agent error log is renamed to SQLAgent.1;
SQLAgent.1 becomes SQLAgent.2, SQLAgent.2 becomes SQLAgent.3, and so on. sp_cycle_agent_errorlog
enables you to cycle the error log files without stopping and starting the server.
This stored procedure must be run from the msdb database.

Permissions
Execute permissions for sp_cycle_agent_errorlog are restricted to members of the sysadmin fixed server role.

Examples
The following example cycles the SQL Server Agent error log.

USE msdb ;
GO

EXEC dbo.sp_cycle_agent_errorlog ;
GO

See Also
sp_cycle_errorlog (Transact-SQL)
sp_cycle_errorlog (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Closes the current error log file and cycles the error log extension numbers just like a server restart. The new error
log contains version and copyright information and a line indicating that the new log has been created.
Transact-SQL Syntax Conventions

Syntax
sp_cycle_errorlog

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Every time SQL Server is started, the current error log is renamed to errorlog.1; errorlog.1 becomes errorlog.2,
errorlog.2 becomes errorlog.3, and so on. sp_cycle_errorlog enables you to cycle the error log files without
stopping and starting the server.

Permissions
Execute permissions for sp_cycle_errorlog are restricted to members of the sysadmin fixed server role.

Examples
The following example cycles the SQL Server error log.

EXEC sp_cycle_errorlog ;
GO

See Also
System Stored Procedures (Transact-SQL)
sp_cycle_agent_errorlog (Transact-SQL)
sp_delete_alert (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes an alert.
Transact-SQL Syntax Conventions

Syntax
sp_delete_alert [ @name = ] 'name'

Arguments
[ @name= ] 'name'
The name of the alert. name is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Removing an alert also removes any notifications associated with the alert.

Permissions
Only members of the sysadmin fixed server role can execute this procedure.

Examples
The following example removes an alert named Test Alert .

USE msdb ;
GO

EXEC dbo.sp_delete_alert
@name = N'Test Alert' ;
GO

See Also
sp_add_alert (Transact-SQL)
sp_help_alert (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_delete_category (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the specified category of jobs, alerts, or operators from the current server.
Transact-SQL Syntax Conventions

Syntax
sp_delete_category [ @class = ] 'class' , [ @name = ] 'name'

Arguments
[ @class =] 'class'
The class of the category. class is varchar(8), with no default, and must have one of these values.

VALUE DESCRIPTION

JOB Deletes a job category.

ALERT Deletes an alert category.

OPERATOR Deletes an operator category.

[ @name =] 'name'
The name of the category to be removed. name is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_delete_category must be run from the msdb database.
Deleting a category recategorizes any jobs, alerts, or operators in that category to the default category for the
class.

Permissions
Only members of the sysadmin fixed server role can run this procedure.
Examples
The following example deletes the job category named AdminJobs .

USE msdb ;
GO

EXEC dbo.sp_delete_category
@name = N'AdminJobs',
@class = N'JOB' ;
GO

See also
sp_add_category (Transact-SQL)
sp_help_category (Transact-SQL)
sp_update_category (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_delete_job (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes a job.
Transact-SQL Syntax Conventions

Syntax
sp_delete_job { [ @job_id = ] job_id | [ @job_name = ] 'job_name' } ,
[ , [ @originating_server = ] 'server' ]
[ , [ @delete_history = ] delete_history ]
[ , [ @delete_unused_schedule = ] delete_unused_schedule ]

Arguments
[ @job_id= ] job_id
Is the identification number of the job to be deleted. job_id is uniqueidentifier, with a default of NULL.
[ @job_name= ] 'job_name'
Is the name of the job to be deleted. job_name is sysname, with a default of NULL.

NOTE
Either job_id or job_namemust be specified; both cannot be specified.

[ @originating_server= ] 'server'
For internal use.
[ @delete_history= ] delete_history
Specifies whether to delete the history for the job. delete_history is bit, with a default of 1. When delete_history is
1, the job history for the job is deleted. When delete_history is 0, the job history is not deleted.
Note that when a job is deleted and the history is not deleted, historical information for the job will not display in
the SQL Server Agent graphical user interface job history, but the information will still reside in the sysjobhistory
table in the msdb database.
[ @delete_unused_schedule= ] delete_unused_schedule
Specifies whether to delete the schedules attached to this job if they are not attached to any other job.
delete_unused_schedule is bit, with a default of 1. When delete_unused_schedule is 1, schedules attached to this
job are deleted if no other jobs reference the schedule. When delete_unused_schedule is 0, the schedules are not
deleted.

Return Code Values


0 (success) or 1 (failure)
Result Sets
None

Remarks
The @originating_server argument is reserved for internal use.
The @delete_unused_schedule argument provides backward compatibility with previous versions of SQL
Server by automatically removing schedules that are not attached to any job. Notice that this parameter defaults
to the backward-compatible behavior. To retain schedules that are not attached to a job, you must provide the
value 0 as the @delete_unused_schedule argument.
SQL Server Management Studio provides an easy, graphical way to manage jobs, and is the recommended way to
create and manage the job infrastructure.
This stored procedure cannot delete maintenance plans, and cannot delete jobs that are part of maintenance
plans. Instead, use SQL Server Management Studio to delete maintenance plans.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of the sysadmin fixed server role can execute sp_delete_job to delete any job. A user that is not
a member of the sysadmin fixed server role can only delete jobs owned by that user.

Examples
The following example deletes the job NightlyBackups .

USE msdb ;
GO

EXEC sp_delete_job
@job_name = N'NightlyBackups' ;
GO

See Also
sp_add_job (Transact-SQL)
sp_help_job (Transact-SQL)
sp_update_job (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_delete_jobschedule (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes a schedule for a job.
sp_delete_jobschedule is provided for backward compatibility only.

Remarks
Job schedules can now be managed independently of jobs. To remove a schedule from a job, use
sp_detach_schedule. To delete a schedule, use sp_delete_schedule.

NOTE: sp_delete_jobschedule does not support schedules that are attached to multiple jobs. If an existing
script calls sp_delete_jobschedule to remove a schedule that is attached to more than one job, the procedure
returns an error.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of the sysadmin role can delete any job schedule. Users who are not members of the sysadmin
role can only delete job schedules that they own.

See Also
sp_delete_schedule (Transact-SQL)
sp_detach_schedule (Transact-SQL)
View or Modify Jobs
sp_add_schedule (Transact-SQL)
sp_help_jobschedule (Transact-SQL)
sp_update_jobschedule (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_delete_jobserver (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the specified target server.
Transact-SQL Syntax Conventions

Syntax
sp_delete_jobserver { [ @job_id = ] job_id | [ @job_name = ] 'job_name' } ,
[ @server_name = ] 'server'

Arguments
[ @job_id= ] job_id
The identification number of the job from which the specified target server will be removed. job_id is
uniqueidentifier, with a default of NULL.
[ @job_name= ] 'job_name'
The name of the job from which the specified target server will be removed. job_name is sysname, with a default
of NULL.

NOTE
Either job_id or job_name must be specified; both cannot be specified.

[ @server_name= ] 'server'
The name of the target server to remove from the specified job. server is nvarchar(30), with no default. server can
be (LOCAL)or the name of a remote target server.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Permissions
To run this stored procedure, users must be members of the sysadmin fixed server role.

Examples
The following example removes the server SEATTLE2 from processing the Weekly Sales Backups job.
NOTE
This example assumes that the Weekly Sales Backups job was created earlier.

USE msdb ;
GO

EXEC sp_delete_jobserver
@job_name = N'Weekly Sales Backups',
@server_name = N'SEATTLE2' ;
GO

See Also
sp_add_jobserver (Transact-SQL)
sp_help_jobserver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_delete_jobstep (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a job step from a job.
Transact-SQL Syntax Conventions

Syntax
sp_delete_jobstep { [ @job_id = ] job_id | [ @job_name = ] 'job_name' } ,
[ @step_id = ] step_id

Arguments
[ @job_id= ] job_id
The identification number of the job from which the step will be removed. job_idis uniqueidentifier, with a
default of NULL.
[ @job_name= ] 'job_name'
The name of the job from which the step will be removed. job_nameis sysname, with a default of NULL.

NOTE: Either job_id or job_name must be specified; both cannot be specified.

[ @step_id= ] step_id
The identification number of the step being removed. step_idis int, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Removing a job step automatically updates the other job steps that reference the deleted step.
For more information about the steps associated with a particular job, run sp_help_jobstep.

NOTE: Calling sp_delete_jobstep with a step_id value of zero deletes all job steps for the job.

Microsoft SQL Server Management Studio provides an easy, graphical way to manage jobs, and is the
recommended way to create and manage the job infrastructure.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Only members of sysadmin can delete a job step that is owned by another user.

Examples
The following example removes job step 1 from the job Weekly Sales Data Backup .

USE msdb ;
GO

EXEC dbo.sp_delete_jobstep
@job_name = N'Weekly Sales Data Backup',
@step_id = 1 ;
GO

See Also
View or Modify Jobs
sp_add_jobstep (Transact-SQL)
sp_update_jobstep (Transact-SQL)
sp_help_jobstep (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_delete_jobsteplog (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes all SQL Server Agent job step logs that are specified with the arguments. Use this stored procedure to
maintain the sysjobstepslogs table in the msdb database.
Transact-SQL Syntax Conventions

Syntax
sp_delete_jobsteplog { [ @job_id = ] 'job_id' | [ @job_name = ] 'job_name' }
[ , [ @step_id = ] step_id | [ @step_name = ] 'step_name' ]
[ , [ @older_than = ] 'date' ]
[ , [ @larger_than = ] 'size_in_bytes' ]

Arguments
[ @job_id =] 'job_id'
The job identification number for the job that contains the job step log to be removed. job_id is int, with a default
of NULL.
[ @job_name =] 'job_name'
The name of the job. job_name is sysname, with a default of NULL.

NOTE: Either job_id or job_name must be specified, but both cannot be specified.

[ @step_id =] step_id
The identification number of the step in the job for which the job step log is to be deleted. If not included, all job
step logs in the job are deleted unless @older_than or @larger_than are specified. step_id is int, with a default of
NULL.
[ @step_name =] 'step_name'
The name of the step in the job for which the job step log is to be deleted. step_name is sysname, with a default of
NULL.

NOTE: Either step_id or step_name can be specified, but both cannot be specified.

[ @older_than =] 'date'
The date and time of the oldest job step log you want to keep. All job step logs that are older than this date and
time are removed. date is datetime, with a default of NULL. Both @older_than and @larger_than can be
specified.
[ @larger_than =] 'size_in_bytes'
The size in bytes of the largest job step log you want to keep. All job step logs that are larger that this size are
removed. Both @larger_than and @older_than can be specified.
Return Code Values
0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_delete_jobsteplog is in the msdb database.
If no arguments except @job_id or @job_name are specified, all job step logs for the specified job are deleted.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Only members of sysadmin can delete a job step log that is owned by another user.

Examples
A. Removing all job step logs from a job
The following example removes all job step logs for the job Weekly Sales Data Backup .

USE msdb ;
GO

EXEC dbo.sp_delete_jobsteplog
@job_name = N'Weekly Sales Data Backup';
GO

B. Removing the job step log for a particular job step


The following example removes the job step log for step 2 in the job Weekly Sales Data Backup .

USE msdb ;
GO

EXEC dbo.sp_delete_jobsteplog
@job_name = N'Weekly Sales Data Backup',
@step_id = 2;
GO

C. Removing all job step logs based on age and size


The following example removes all job steps logs that are older than noon October 25, 2005 and larger than 100
megabytes (MB) from the job Weekly Sales Data Backup .
USE msdb ;
GO

EXEC dbo.sp_delete_jobsteplog
@job_name = N'Weekly Sales Data Backup',
@older_than = '10/25/2005 12:00:00',
@larger_than = 104857600;
GO

See Also
sp_help_jobsteplog (Transact-SQL)
SQL Server Agent Stored Procedures (Transact-SQL)
sp_delete_notification (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a SQL Server Agent notification definition for a specific alert and operator.
Transact-SQL Syntax Conventions

Syntax
sp_delete_notification
[ @alert_name = ] 'alert' ,
[ @operator_name = ] 'operator'

Arguments
[ @alert_name= ] 'alert'
The name of the alert. alert is sysname, with no default.
[ @operator_name= ] 'operator'
The name of the operator. operator is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Removing a notification removes only the notification; the alert and the operator are left intact.

Permissions
To run this stored procedure, users must be granted the sysadmin fixed server role.

Examples
The following example removes the notification sent to operator François Ajenstat when alert Test Alert
occurs.
USE msdb ;
GO

EXEC dbo.sp_delete_notification
@alert_name = 'Test Alert',
@operator_name = 'François Ajenstat' ;
GO

See Also
sp_add_alert (Transact-SQL)
sp_add_notification (Transact-SQL)
sp_add_operator (Transact-SQL)
sp_delete_alert (Transact-SQL)
sp_help_alert (Transact-SQL)
sp_help_notification (Transact-SQL)
sp_help_operator (Transact-SQL)
sp_update_notification (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_delete_operator (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes an operator.
Transact-SQL Syntax Conventions

Syntax
sp_delete_operator [ @name = ] 'name'
[ , [ @reassign_to_operator = ] 'reassign_operator' ]

Arguments
[ @name= ] 'name'
The name of the operator to delete. name is sysname, with no default.
[ @reassign_to_operator= ] 'reassign_operator'
The name of an operator to whom the specified operator's alerts can be reassigned. reassign_operator is
sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
When an operator is removed, all the notifications associated with the operator are also removed.

Permissions
Members of the sysadmin fixed server role can execute sp_delete_operator.

Examples
The following example deletes operator François Ajenstat .

USE msdb ;
GO

EXEC sp_delete_operator @name = 'François Ajenstat' ;


GO
See Also
sp_add_operator (Transact-SQL)
sp_help_operator (Transact-SQL)
sp_update_operator (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_delete_proxy (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the specified proxy.
Transact-SQL Syntax Conventions

Syntax
sp_delete_proxy [ @proxy_id = ] id , [ @proxy_name = ] 'proxy_name'

Arguments
[ @proxy_id= ] id
The proxy identification number of the proxy to remove. The proxy_id is int, with a default of NULL.
[ @proxy_name= ] 'proxy_name'
The name of the proxy to remove. The proxy_name is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
Either @proxy_name or @proxy_id must be specified. If both arguments are specified, the arguments must both
refer to the same proxy or the stored procedure fails.
If a job step refers to the proxy specified, the proxy cannot be deleted and the stored procedure fails.

Permissions
By default, only members of the sysadmin fixed server role can execute sp_delete_proxy.

Examples
The following example deletes the proxy Catalog application proxy .
USE msdb ;
GO

EXEC dbo.sp_delete_proxy
@proxy_name = N'Catalog application proxy' ;
GO

See Also
sp_add_proxy (Transact-SQL)
sp_delete_schedule (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes a schedule.
Transact-SQL Syntax Conventions

Syntax
sp_delete_schedule { [ @schedule_id = ] schedule_id | [ @schedule_name = ] 'schedule_name' } ,
[ @force_delete = ] force_delete

Arguments
[ @schedule_id= ] schedule_id
The schedule identification number of the schedule to delete. schedule_id is int, with a default of NULL.

NOTE: Either schedule_id or schedule_name must be specified, but both cannot be specified.

[ @schedule_name= ] 'schedule_name'
The name of the schedule to delete. schedule_name is sysname, with a default of NULL.

NOTE: Either schedule_id or schedule_name must be specified, but both cannot be specified.

[ @force_delete = ] force_delete
Specifies whether the procedure should fail if the schedule is attached to a job. Force_delete is bit, with a default
of 0. When force_delete is 0, the stored procedure fails if the schedule is attached to a job. When force_delete is 1,
the schedule is deleted regardless of whether the schedule is attached to a job.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
By default, a schedule cannot be deleted if the schedule is attached to a job. To delete a schedule that is attached
to a job, specify a value of 1 for force_delete. Deleting a schedule does not stop jobs that are currently running.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
Note that the job owner can attach a job to a schedule and detach a job from a schedule without also
having to be the schedule owner. However, a schedule cannot be deleted if the detach would leave it with
no jobs, unless the caller is the schedule owner.
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Only members of the sysadmin role can delete a job schedule that is owned by another user.

Examples
A. Deleting a schedule
The following example deletes the schedule NightlyJobs . If the schedule is attached to any job, the example does
not delete the schedule.

USE msdb ;
GO

EXEC dbo.sp_delete_schedule
@schedule_name = N'NightlyJobs' ;
GO

B. Deleting a schedule attached to a job


The following example deletes the schedule RunOnce , regardless of whether the schedule is attached to a job.

USE msdb ;
GO

EXEC dbo.sp_delete_schedule
@schedule_name = 'RunOnce',
@force_delete = 1;
GO

See Also
Implement Jobs
sp_add_schedule (Transact-SQL)
sp_delete_targetserver (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the specified server from the list of available target servers.
Transact-SQL Syntax Conventions

Syntax
sp_delete_targetserver [ @server_name = ] 'server'
[ , [ @clear_downloadlist = ] clear_downloadlist ]
[ , [ @post_defection = ] post_defection ]

Arguments
[ @server_name= ] 'server'
The name of the server to remove as an available target server. server is nvarchar(30), with no default.
[ @clear_downloadlist= ] clear_downloadlist
Specifies whether to clear the download list for the target server. clear_downloadlist is type bit, with a default of 1.
When clear_downloadlist is 1, the procedure clears the download list for the server before deleting the server.
When clear_downloadlist is 0, the download list is not cleared.
[ @post_defection= ] post_defection
Specifies whether to post a defect instruction to the target server. post_defection is type bit, with a default of 1.
When post_defection is 1, the procedure posts a defect instruction to the target server before deleting the server.
When post_defection is 0, the procedure does not post a defect instruction to the target server.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
The normal way to delete a target server is to call sp_msx_defect at the target server. Use
sp_delete_targetserver only when a manual defection is necessary.

Permissions
To run this stored procedure, users must be granted the sysadmin fixed server role.

Examples
The following example removes the server LONDON1 from the available job servers.

USE msdb ;
GO

EXEC dbo.sp_delete_targetserver
@server_name = N'LONDON1' ;
GO

See also
sp_help_targetserver (Transact-SQL)
sp_msx_defect (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_delete_targetservergroup (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes the specified target server group.
Transact-SQL Syntax Conventions

Syntax
sp_delete_targetservergroup [ @name = ] 'name'

Arguments
[ @name= ] 'name'
The name of the target server group to remove. name is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example removes the target server group Servers Processing Customer Orders .

USE msdb ;
GO

EXEC sp_delete_targetservergroup
@name = N'Servers Processing Customer Orders';
GO

See Also
sp_add_targetservergroup (Transact-SQL)
sp_help_targetservergroup (Transact-SQL)
sp_update_targetservergroup (Transact-SQL)
sp_delete_targetsvrgrp_member (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a target server from a target server group.
Transact-SQL Syntax Conventions

Syntax
sp_delete_targetsvrgrp_member [ @group_name = ] 'group_name' , [ server_name = ] 'server_name'

Arguments
[ @group_name= ] 'group_name'
The name of the group. group_name is sysname, with no default.
[ @server_name= ] 'server_name'
The name of the server to remove from the specified group. server_name is nvarchar(30), with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Permissions
To run this stored procedure, users must be granted the sysadmin fixed server role.

Examples
The following example removes the server LONDON1 from the Servers Maintaining Customer Information group.

USE msdb ;
GO

EXEC sp_delete_targetsvrgrp_member
@group_name = N'Servers Maintaining Customer Information',
@server_name = N'LONDON1';
GO

See Also
sp_add_targetsvrgrp_member (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_detach_schedule (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes an association between a schedule and a job.
Transact-SQL Syntax Conventions

Syntax
sp_detach_schedule
{ [ @job_id = ] job_id | [ @job_name = ] 'job_name' } ,
{ [ @schedule_id = ] schedule_id | [ @schedule_name = ] 'schedule_name' } ,
[ @delete_unused_schedule = ] delete_unused_schedule

Arguments
[ @job_id= ] job_id
The job identification number of the job to remove the schedule from. job_id is uniqueidentifier, with a default
of NULL.
[ @job_name= ] 'job_name'
The name of the job to remove the schedule from. job_name is sysname, with a default of NULL.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @schedule_id= ] schedule_id
The schedule identification number of the schedule to remove from the job. schedule_id is int, with a default of
NULL.
[ @schedule_name= ] 'schedule_name'
The name of the schedule to remove from the job. schedule_name is sysname, with a default of NULL.

NOTE
Either schedule_id or schedule_name must be specified, but both cannot be specified.

[ @delete_unused_schedule= ] delete_unused_schedule
Specifies whether to delete unused job schedules. delete_unused_schedule is bit, with a default of 0, which means
that all schedules will be kept, even if no jobs reference them. If set to 1, unused job schedules are deleted if no
jobs reference them.

Return Code Values


0 (success) or 1 (failure)
Result Sets
None

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
Note that the job owner can attach a job to a schedule and detach a job from a schedule without also
having to be the schedule owner. However, a schedule cannot be deleted if the detach would leave it with
no jobs unless the caller is the schedule owner.
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
SQL Server checks to determine whether the user owns the schedule. Only members of the sysadmin fixed
server role can detach schedules from jobs owned by another user.

Examples
The following example removes an association between a 'NightlyJobs' schedule and a 'BackupDatabase' job.

USE msdb ;
GO

EXEC dbo.sp_detach_schedule
@job_name = 'BackupDatabase',
@schedule_name = 'NightlyJobs' ;
GO

See Also
sp_add_schedule (Transact-SQL)
sp_attach_schedule (Transact-SQL)
sp_delete_schedule (Transact-SQL)
sp_enum_login_for_proxy (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Lists associations between security principals and proxies.
Transact-SQL Syntax Conventions

Syntax
sp_enum_login_for_proxy
[ @name = ] 'name'
[ @proxy_id = ] id,
[ @proxy_name = ] 'proxy_name'

Arguments
[ @name= ] 'name'
The name of a SQL Server principal, login, server role, or msdb database role to list proxies for. The name is
nvarchar(256), with a default of NULL.
[ @proxy_id= ] id
The proxy identification number of the proxy to list information for. The proxy_id is int, with a default of NULL.
Either the id or the proxy_name may be specified.
[ @proxy_name= ] 'proxy_name'
The name of the proxy to list information for. The proxy_name is sysname, with a default of NULL. Either the id or
the proxy_name may be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

proxy_id int Proxy identification number.

proxy_name sysname The name of the proxy.

name sysname Name of the security principal for the


association.
COLUMN NAME DATA TYPE DESCRIPTION

flags int Type of the security principal.

0 = SQL Server login

1 = Fixed system role

2 = Database role in msdb

Remarks
When no parameters are provided, sp_enum_login_for_proxy lists information about all logins in the instance for
every proxy.
When a proxy id or proxy name is provided, sp_enum_login_for_proxy lists logins that have access to the proxy.
When a login name is provided, sp_enum_login_for_proxy lists the proxies that the login has access to.
When both proxy information and a login name are provided, the result set returns a row if the login specified has
access to the proxy specified.
This stored procedure is located in msdb.

Permissions
Execution permissions for this procedure default to members of the sysadmin fixed server role.

Examples
A. Listing all associations
The following example lists all permissions established between logins and proxies in the current instance.

USE msdb ;
GO

EXEC dbo.sp_enum_login_for_proxy ;
GO

B. Listing proxies for a specific login


The following example lists the proxies that the login terrid has access to.

USE msdb ;
GO

EXEC dbo.sp_enum_login_for_proxy
@name = 'terrid' ;
GO

See Also
sp_help_proxy (Transact-SQL)
sp_grant_login_to_proxy (Transact-SQL)
sp_revoke_login_from_proxy (Transact-SQL)
sp_enum_proxy_for_subsystem (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Lists permissions for SQL Server Agent proxies to access subsystems.
Transact-SQL Syntax Conventions

Syntax
sp_enum_proxy_for_subsystem
[ @proxy_id = ] proxy_id,
[ @proxy_name = ] 'proxy_name',
[ @subsystem_id = ] subsystem_id,
[ @subsystem_name = ] 'subsystem_name'

Arguments
[ @proxy_id = ] proxy_id
The identification number of the proxy to list information for. The proxy_id is int, with a default of NULL. Either the
id or the proxy_name may be specified.
[ @proxy_name = ] 'proxy_name'
The name of the proxy to list information for. The proxy_name is sysname, with a default of NULL. Either the id or
the proxy_name may be specified.
[ @subsystem_id = ] subsystem_id
The identification number of the subsystem to list information for. The subsystem_id is int, with a default of NULL.
Either the subsystem_id or the subsystem_name may be specified.
[ @subsystem_name = ] 'subsystem_name'
The name of the subsystem to list information for. The subsystem_name is sysname, with a default of NULL. Either
the subsystem_id or the subsystem_name may be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

subsystem_id int Subsystem identification number.

subsystem_name sysname The name of the subsystem.

proxy_id int Proxy identification number.


COLUMN NAME DATA TYPE DESCRIPTION

proxy_name sysname The name of the proxy.

Remarks
When no parameters are provided, sp_enum_proxy_for_subsystem lists information about all proxies in the
instance for every subsystem.
When a proxy id or proxy name is provided, sp_enum_proxy_for_subsystem lists subsystems that the proxy has
access to. When a subsystem id or subsystem name is provided, sp_enum_proxy_for_subsystem lists proxies
that have access to that subsystem.
When both proxy information and subsystem information is provided, the result set returns a row if the proxy
specified has access to the subsystem specified.
This stored procedure is located in msdb.

Permissions
Execution permissions for this procedure default to members of the sysadmin fixed server role.

Examples
A. Listing all associations
The following example lists all permissions established between proxies and subsystems for the current instance.

USE msdb ;
GO

EXEC dbo.sp_enum_proxy_for_subsystem ;
GO

B. Determining if a proxy has access to a specific subsystem


The following example returns a row if the proxy Catalog application proxy has access to the ActiveScripting
subsystem. Otherwise, the example returns an empty result set.

USE msdb ;
GO

EXEC dbo.sp_enum_proxy_for_subsystem
@subsystem_name = 'ActiveScripting',
@proxy_name = 'Catalog application proxy' ;
GO

See Also
sp_grant_proxy_to_subsystem (Transact-SQL)
sp_enum_sqlagent_subsystems (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Lists the SQL Server Agent subsystems.
Transact-SQL Syntax Conventions

Syntax
sp_enum_sqlagent_subsystems

Arguments
None

Return Code Values


0 (success) or 1 (Failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

subsystem nvarchar(40) Name of the subsystem.

description nvarchar(512) Description of the subsystem.

subsystem_dll nvarchar(510) DLL module that contains the


subsystem.

agent_exe nvarchar(510) Executable module that is used by the


subsystem.

start_entry_point nvarchar(30) Procedure that SQL Server Agent calls


during job step execution.

event_entry_point nvarchar(30) Procedure that SQL Server Agent calls


during job step execution.

stop_entry_point nvarchar(30) Procedure that SQL Server Agent calls


during job step execution.

max_worker_threads int Maximum number of threads SQL


Server Agent will start for this
subsystem.
COLUMN NAME DATA TYPE DESCRIPTION

subsystem_id int Identifier for the subsystem.

Remarks
This procedure lists the subsystems available in the instance.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted the SQLAgentOperatorRole fixed database role in the msdb database.
For details about SQLAgentOperatorRole, see SQL Server Agent Fixed Database Roles.

See Also
Implement SQL Server Agent Security
sp_add_jobstep (Transact-SQL)
sp_grant_proxy_to_subsystem (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Grants a proxy access to a subsystem.
Transact-SQL Syntax Conventions

Syntax
sp_grant_proxy_to_subsystem
{ [ @proxy_id = ] proxy_id | [ @proxy_name = ] 'proxy_name' },
{ [ @subsystem_id = ] subsystem_id | [ @subsystem_name = ] 'subsystem_name' }

Arguments
[ @proxy_id = ] id
The proxy identification number of the proxy to grant access for. The proxy_id is int, with a default of NULL. Either
proxy_id or proxy_name must be specified, but both cannot be specified.
[ @proxy_name = ] 'proxy_name'
The name of the proxy to grant access for. The proxy_name is sysname, with a default of NULL. Either proxy_id or
proxy_name must be specified, but both cannot be specified.
[ @subsystem_id = ] id
The id number of the subsystem to grant access to. The subsystem_id is int, with a default of NULL. Either
subsystem_id or subsystem_name must be specified, but both cannot be specified. The following table lists the
values for each subsystem.

VALUE DESCRIPTION

2 Microsoft ActiveX Script

** Important *\* The ActiveX Scripting subsystem will be


removed from SQL Server Agent in a future version of
Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that
currently use this feature.

3 Operating System (CmdExec)

4 Replication Snapshot Agent

5 Replication Log Reader Agent

6 Replication Distribution Agent

7 Replication Merge Agent


VALUE DESCRIPTION

8 Replication Queue Reader Agent

9 Analysis Services Query

10 Analysis Services Command

11 SSIS package execution

12 PowerShell Script

[ @subsystem_name = ] 'subsystem_name'
The name of the subsystem to grant access to. The subsystem_name is sysname, with a default of NULL. Either
subsystem_id or subsystem_name must be specified, but both cannot be specified. The following table lists the
values for each subsystem.

VALUE DESCRIPTION

ActiveScripting ActiveX Script

CmdExec Operating System (CmdExec)

Snapshot Replication Snapshot Agent

LogReader Replication Log Reader Agent

Distribution Replication Distribution Agent

Merge Replication Merge Agent

QueueReader Replication Queue Reader Agent

ANALYSISQUERY Analysis Services Query

ANALYSISCOMMAND Analysis Services Command

Dts SSIS package execution

PowerShell PowerShell Script

Remarks
Granting a proxy access to a subsystem does not change the permissions for the principal specified in the proxy.

Permissions
Only members of the sysadmin fixed server role can execute sp_grant_proxy_to_subsystem.

Examples
A. Granting access to a subsystem by ID
The following example grants the proxy Catalog application proxy access to the ActiveX Scripting subsystem.

USE msdb ;
GO

EXEC dbo.sp_grant_proxy_to_subsystem
@proxy_name = 'Catalog application proxy',
@subsystem_id = 2;
GO

B. Granting access to a subsystem by name.


The following example grants the proxy Catalog application proxy access to the SSIS package execution
subsystem.

USE msdb ;
GO

EXEC dbo.sp_grant_proxy_to_subsystem
@proxy_name = N'Catalog application proxy',
@subsystem_name = N'Dts' ;
GO

See Also
Implement SQL Server Agent Security
sp_revoke_proxy_from_subsystem (Transact-SQL)
sp_add_proxy (Transact-SQL)
sp_delete_proxy (Transact-SQL)
sp_update_proxy (Transact-SQL)
sp_grant_login_to_proxy (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Grants a security principal access to a proxy.
Transact-SQL Syntax Conventions

Syntax
sp_grant_login_to_proxy
{ [ @login_name = ] 'login_name'
| [ @fixed_server_role = ] 'fixed_server_role'
| [ @msdb_role = ] 'msdb_role' } ,
{ [ @proxy_id = ] id | [ @proxy_name = ] 'proxy_name' }

Arguments
[ @login_name = ] 'login_name'
The login name to grant access to. The login_name is nvarchar(256), with a default of NULL. One of
@login_name, @fixed_server_role, or @msdb_role must be specified, or the stored procedure fails.
[ @fixed_server_role= ] 'fixed_server_role'
The fixed server role to grant access to. The fixed_server_role is nvarchar(256), with a default of NULL. One of
@login_name, @fixed_server_role, or @msdb_role must be specified, or the stored procedure fails.
[ @msdb_role= ] 'msdb_role'
The database role in the msdb database to grant access to. The msdb_role is nvarchar(256), with a default of
NULL. One of @login_name, @fixed_server_role, or @msdb_role must be specified, or the stored procedure
fails.
[ @proxy_id= ] id
The identifier for the proxy to grant access for. The id is int, with a default of NULL. One of @proxy_id or
@proxy_name must be specified, or the stored procedure fails.
[ @proxy_name= ] 'proxy_name'
The name of the proxy to grant access for. The proxy_name is nvarchar(256), with a default of NULL. One of
@proxy_id or @proxy_name must be specified, or the stored procedure fails.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_grant_login_to_proxy must be run from the msdb database.

Permissions
Only members of the sysadmin fixed server role may execute sp_grant_login_to_proxy.

Examples
The following example allows the login adventure-works\terrid to use the proxy Catalog application proxy .

USE msdb ;
GO

EXEC dbo.sp_grant_login_to_proxy
@login_name = N'adventure-works\terrid',
@proxy_name = N'Catalog application proxy' ;
GO

See Also
CREATE LOGIN (Transact-SQL)
sp_add_proxy (Transact-SQL)
sp_revoke_login_from_proxy (Transact-SQL)
sp_help_alert (Transact-SQL)
11/27/2017 • 6 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports information about the alerts defined for the server.
Transact-SQL Syntax Conventions

Syntax
sp_help_alert [ [ @alert_name = ] 'alert_name' ]
[ , [ @order_by = ] 'order_by' ]
[ , [ @alert_id = ] alert_id ]
[ , [ @category_name = ] 'category' ]
[ , [ @legacy_format = ] legacy_format ]

Arguments
[ @alert_name =] 'alert_name'
The alert name. alert_name is nvarchar(128). If alert_name is not specified, information about all alerts is
returned.
[ @order_by =] 'order_by'
The sorting order to use for producing the results. order_byis sysname, with a default of N 'name'.
[ @alert_id =] alert_id
The identification number of the alert to report information about. alert_idis int, with a default of NULL.
[ @category_name =] 'category'
The category for the alert. category is sysname, with a default of NULL.
[ @legacy_format=] legacy_format
Is whether to produce a legacy result set. legacy_format is bit, with a default of 0. When legacy_format is 1,
sp_help_alert returns the result set returned by sp_help_alert in Microsoft SQL Server 2000.

Return Code Values


0 (success) or 1 (failure)

Result Sets
When @legacy_format is 0, sp_help_alert produces the following result set.

COLUMN NAME DATA TYPE DESCRIPTION

id int System-assigned unique integer


identifier.
COLUMN NAME DATA TYPE DESCRIPTION

name sysname Alert name (for example, Demo: Full


msdb log).

event_source nvarchar(100) Source of the event. It will always be


MSSQLServer for Microsoft SQL
Server version 7.0

event_category_id int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.

event_id int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.

message_id int Message error number that defines the


alert. (Usually corresponds to an error
number in the sysmessages table). If
severity is used to define the alert,
message_id is 0 or NULL.

severity int Severity level (from 9 through 25, 110,


120, 130, or 140) that defines the alert.

enabled tinyint Status of whether the alert is currently


enabled (1) or not (0). A nonenabled
alert is not sent.

delay_between_responses int Wait period, in seconds, between


responses to the alert.

last_occurrence_date int Data the alert last occurred.

last_occurrence_time int Time the alert last occurred.

last_response_date int Date the alert was last responded to by


the SQLServerAgent service.

last_response_time int Time the alert was last responded to by


the SQLServerAgent service.

notification_message nvarchar(512) Optional additional message sent to


the operator as part of the e-mail or
pager notification.

include_event_description tinyint Is whether the description of the SQL


Server error from the Microsoft
Windows application log should be
included as part of the notification
message.

database_name sysname Database in which the error must occur


for the alert to fire. If the database
name is NULL, the alert fires regardless
of where the error occurred.
COLUMN NAME DATA TYPE DESCRIPTION

event_description_keyword nvarchar(100) Description of the SQL Server error in


the Windows application log that must
be like the supplied sequence of
characters.

occurrence_count int Number of times the alert occurred.

count_reset_date int Date the occurrence_count was last


reset.

count_reset_time int Time the occurrence_count was last


reset.

job_id uniqueidentifier Identification number of the job to be


executed in response to an alert.

job_name sysname Name of the job to be executed in


response to an alert.

has_notification int Nonzero if one or more operators are


notified for this alert. The value is one
or more of the following values (ORed
together):

1=has e-mail notification

2=has pager notification

4=has net send notification.

flags int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.

performance_condition nvarchar(512) If type is 2, this column shows the


definition of the performance condition;
otherwise, the column is NULL.

category_name sysname Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed. Will
always be '[Uncategorized]' for SQL
Server 7.0.

wmi_namespace sysname If type is 3, this column shows the


namespace for the WMI event.

wmi_query nvarchar(512) If type is 3, this column shows the


query for the WMI event.
COLUMN NAME DATA TYPE DESCRIPTION

type int Type of the event:

1 = SQL Server event alert

2 = SQL Server performance alert

3 = WMI event alert

When @legacy_format is 1, sp_help_alert produces the following result set.

COLUMN NAME DATA TYPE DESCRIPTION

id int System-assigned unique integer


identifier.

name sysname Alert name (for example, Demo: Full


msdb log).

event_source nvarchar(100) Source of the event. It will always be


MSSQLServer for SQL Server version
7.0

event_category_id int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.

event_id int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.

message_id int Message error number that defines the


alert. (Usually corresponds to an error
number in the sysmessages table). If
severity is used to define the alert,
message_id is 0 or NULL.

severity int Severity level (from 9 through 25, 110,


120, 130, or 140) that defines the alert.

enabled tinyint Status of whether the alert is currently


enabled (1) or not (0). A nonenabled
alert is not sent.

delay_between_responses int Wait period, in seconds, between


responses to the alert.

last_occurrence_date int Data the alert last occurred.

last_occurrence_time int Time the alert last occurred.

last_response_date int Date the alert was last responded to by


the SQLServerAgent service.

last_response_time int Time the alert was last responded to by


the SQLServerAgent service.
COLUMN NAME DATA TYPE DESCRIPTION

notification_message nvarchar(512) Optional additional message sent to


the operator as part of the e-mail or
pager notification.

include_event_description tinyint Is whether the description of the SQL


Server error from the Windows
application log should be included as
part of the notification message.

database_name sysname Database in which the error must occur


for the alert to fire. If the database
name is NULL, the alert fires regardless
of where the error occurred.

event_description_keyword nvarchar(100) Description of the SQL Server error in


the Windows application log that must
be like the supplied sequence of
characters.

occurrence_count int Number of times the alert occurred.

count_reset_date int Date the occurrence_count was last


reset.

count_reset_time int Time the occurrence_count was last


reset.

job_id uniqueidentifier Job identification number.

job_name sysname An on-demand job to be executed in


response to an alert.

has_notification int Nonzero if one or more operators are


notified for this alert. The value is one
or more of the following values (joined
together with OR):

1=has e-mail notification

2=has pager notification

4=has net send notification.

flags int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed..

performance_condition nvarchar(512) If type is 2, this column shows the


definition of the performance condition.
If type is 3, this column shows the
query for the WMI event. Otherwise,
the column is NULL.
COLUMN NAME DATA TYPE DESCRIPTION

category_name sysname Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed. Will
always be '[Uncategorized]' for SQL
Server 7.0.

type int Type of alert:

1 = SQL Server event alert

2 = SQL Server performance alert

3 = WMI event alert

Remarks
sp_help_alert must be run from the msdb database.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted the SQLAgentOperatorRole fixed database role in the msdb database.
For details about SQLAgentOperatorRole, see SQL Server Agent Fixed Database Roles.

Examples
The following example reports information about the Demo: Sev. 25 Errors alert.

USE msdb ;
GO

EXEC sp_help_alert @alert_name = 'Demo: Sev. 25 Errors';


GO

See Also
sp_add_alert (Transact-SQL)
sp_update_alert (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_category (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Provides information about the specified classes of jobs, alerts, or operators.
Transact-SQL Syntax Conventions

Syntax
sp_help_category [ [ @class = ] 'class' ]
[ , [ @type = ] 'type' ]
[ , [ @name = ] 'name' ]
[ , [ @suffix = ] suffix ]

Arguments
[ @class=] 'class'
The class about which information is requested. class is varchar(8), with a default value of JOB. class can be one of
these values.

VALUE DESCRIPTION

JOB Provides information about a job category.

ALERT Provides information about an alert category.

OPERATOR Provides information about an operator category.

[ @type= ] 'type'
The type of category for which information is requested. type is varchar(12), with a default of NULL, and can be
one of these values.

VALUE DESCRIPTION

LOCAL Local job category.

MULTI -SERVER Multiserver job category.

NONE Category for a class other than JOB.

[ @name= ] 'name'
The name of the category for which information is requested. name is sysname, with a default of NULL.
[ @suffix= ] suffix
Specifies whether the category_type column in the result set is an ID or a name. suffix is bit, with a default of 0. 1
shows the category_type as a name, and 0 shows it as an ID.
Return Code Values
0 (success) or 1 (failure)

Result Sets
When @suffix is 0, sp_help_category returns the following result set:

COLUMN NAME DATA TYPE DESCRIPTION

category_id int Category ID

category_type tinyint Type of category:

1 = Local

2 = Multiserver

3 = None

name sysname Category name

When @suffix is 1, sp_help_category returns the following result set:

COLUMN NAME DATA TYPE DESCRIPTION

category_id int Category ID

category_type sysname Type of category. One of LOCAL,


MULTI-SERVER, or NONE

name sysname Category name

Remarks
sp_help_category must be run from the msdb database.
If no parameters are specified, the result set provides information about all of the job categories.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.

Examples
A. Returning local job information
The following example returns information about jobs that are administered locally.
USE msdb ;
GO

EXEC dbo.sp_help_category
@type = N'LOCAL' ;
GO

B. Returning alert information


The following example returns information about the Replication alert category.

USE msdb ;
GO

EXEC dbo.sp_help_category
@class = N'ALERT',
@name = N'Replication' ;
GO

See Also
sp_add_category (Transact-SQL)
sp_delete_category (Transact-SQL)
sp_update_category (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_downloadlist (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Lists all rows in the sysdownloadlist system table for the supplied job, or all rows if no job is specified.
Transact-SQL Syntax Conventions

Syntax
sp_help_downloadlist { [ @job_id = ] job_id | [ @job_name = ] 'job_name' }
[ , [ @operation = ] 'operation' ]
[ , [ @object_type = ] 'object_type' ]
[ , [ @object_name = ] 'object_name' ]
[ , [ @target_server = ] 'target_server' ]
[ , [ @has_error = ] has_error ]
[ , [ @status = ] status ]
[ , [ @date_posted = ] date_posted ]

Arguments
[ @job_id= ] job_id
The job identification number for which to return information. job_id is uniqueidentifier, with a default of NULL.
[ @job_name= ] 'job_name'
The name of the job. job_name is sysname, with a default of NULL.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @operation= ] 'operation'
The valid operation for the specified job. operation is varchar(64), with a default of NULL, and can be one of these
values.

VALUE DESCRIPTION

DEFECT Server operation that requests the target server to defect


from the Master SQLServerAgent service.

DELETE Job operation that removes an entire job.

INSERT Job operation that inserts an entire job or refreshes an


existing job. This operation includes all job steps and
schedules, if applicable.
VALUE DESCRIPTION

RE-ENLIST Server operation that causes the target server to resend its
enlistment information, including the polling interval and time
zone to the multiserver domain. The target server also
redownloads the MSXOperator details.

SET-POLL Server operation that sets the interval, in seconds, for target
servers to poll the multiserver domain. If specified, value is
interpreted as the required interval value, and can be a value
from 10 to 28,800.

START Job operation that requests the start of job execution.

STOP Job operation that requests the stop of job execution.

SYNC-TIME Server operation that causes the target server to synchronize


its system clock with the multiserver domain. Because this is a
costly operation, perform this operation on a limited,
infrequent basis.

UPDATE Job operation that updates only the sysjobs information for a
job, not the job steps or schedules. Is automatically called by
sp_update_job.

[ @object_type= ] 'object_type'
The type of object for the specified job. object_type is varchar(64), with a default of NULL. object_type can be
either JOB or SERVER. For more information about valid object_typevalues, see sp_add_category (Transact-SQL).
[ @object_name= ] 'object_name'
The name of the object. object_name is sysname, with a default of NULL. If object_type is JOB, object_nameis the
job name. If object_typeis SERVER, object_nameis the server name.
[ @target_server= ] 'target_server'
The name of the target server. target_server is nvarchar(128), with a default of NULL.
[ @has_error= ] has_error
Is whether the job should acknowledge errors. has_error is tinyint, with a default of NULL, which indicates no
errors should be acknowledged. 1 indicates that all errors should be acknowledged.
[ @status= ] status
The status for the job. status is tinyint, with a default value of NULL.
[ @date_posted= ] date_posted
The date and time for which all entries made on or after the specified date and time should be included in the
result set. date_posted is datetime, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION
COLUMN NAME DATA TYPE DESCRIPTION

instance_id int Unique integer identification number of


the instruction.

source_server nvarchar(30) Computer name of the server the


instruction came from. In Microsoft SQL
Server version 7.0, this is always the
computer name of the master (MSX)
server.

operation_code nvarchar(4000) Operation code for the instruction.

object_name sysname Object affected by the instruction.

object_id uniqueidentifier Identification number of the object


affected by the instruction (job_id for a
job object, or 0x00 for a server object)
or a data value specific to the
operation_code.

target_server nvarchar(30) Target server that this instruction is to


be downloaded by.

error_message nvarchar(1024) Error message (if any) from the target


server if it encountered a problem while
processing this instruction.

Note: Any error message blocks all


further downloads by the target server.

date_posted datetime Date the instruction was posted to the


table.

date_downloaded datetime Date the instruction was downloaded


by the target server.

status tinyint Status of the job:

0 = Not yet downloaded

1 = Successfully downloaded.

Permissions
Permissions to execute this procedure default to members of the sysadmin fixed server role.

Examples
The following example lists rows in the sysdownloadlist for the NightlyBackups job.
USE msdb ;
GO

EXEC dbo.sp_help_downloadlist
@job_name = N'NightlyBackups',
@operation = N'UPDATE',
@object_type = N'JOB',
@object_name = N'NightlyBackups',
@target_server = N'SEATTLE2',
@has_error = 1,
@status = NULL,
@date_posted = NULL ;
GO

See Also
System Stored Procedures (Transact-SQL)
sp_help_job (Transact-SQL)
11/17/2017 • 8 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about jobs that are used by SQL Server Agent to perform automated activities in SQL Server.
Transact-SQL Syntax Conventions

Syntax
sp_help_job { [ @job_id = ] job_id
[ @job_name = ] 'job_name' }
[ , [ @job_aspect = ] 'job_aspect' ]
[ , [ @job_type = ] 'job_type' ]
[ , [ @owner_login_name = ] 'login_name' ]
[ , [ @subsystem = ] 'subsystem' ]
[ , [ @category_name = ] 'category' ]
[ , [ @enabled = ] enabled ]
[ , [ @execution_status = ] status ]
[ , [ @date_comparator = ] 'date_comparison' ]
[ , [ @date_created = ] date_created ]
[ , [ @date_last_modified = ] date_modified ]
[ , [ @description = ] 'description_pattern' ]

Arguments
[ @job_id =] job_id
The job identification number. job_id is uniqueidentifier, with a default of NULL.
[ @job_name =] 'job_name'
The name of the job. job_name is sysname, with a default of NULL.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @job_aspect =] 'job_aspect'
The job attribute to display. job_aspect is varchar(9), with a default of NULL, and can be one of these values.

VALUE DESCRIPTION

ALL Job aspect information

JOB Job information

SCHEDULES Schedule information

STEPS Job step information


VALUE DESCRIPTION

TARGETS Target information

[ @job_type =] 'job_type'
The type of jobs to include in the report. job_type is varchar(12), with a default of NULL. job_type can be LOCAL
or MULTI-SERVER.
[ @owner_login_name =] 'login_name'
The login name of the owner of the job. login_name is sysname, with a default of NULL.
[ @subsystem =] 'subsystem'
The name of the subsystem. subsystem is nvarchar(40), with a default of NULL.
[ @category_name =] 'category'
The name of the category. category is sysname, with a default of NULL.
[ @enabled =] enabled
A number indicating whether information is shown for enabled jobs or disabled jobs. enabled is tinyint, with a
default of NULL. 1 indicates enabled jobs, and 0 indicates disabled jobs.
[ @execution_status =] status
The execution status for the jobs. status is int, with a default of NULL, and can be one of these values.

VALUE DESCRIPTION

0 Returns only those jobs that are not idle or suspended.

1 Executing.

2 Waiting for thread.

3 Between retries.

4 Idle.

5 Suspended.

7 Performing completion actions.

[ @date_comparator =] 'date_comparison'
The comparison operator to use in comparisons of date_created and date_modified. date_comparison is
char(1),and can be =, <, or >.
[ @date_created =] date_created
The date the job was created. date_createdis datetime, with a default of NULL.
[ @date_last_modified =] date_modified
The date the job was last modified. date_modified is datetime, with a default of NULL.
[ @description =] 'description_pattern'
The description of the job. description_pattern is nvarchar(512), with a default of NULL. description_pattern can
include the SQL Server wildcard characters for pattern matching.

Return Code Values


0 (success) or 1 (failure)

Result Sets
If no arguments are specified, sp_help_job returns this result set.

COLUMN NAME DATA TYPE DESCRIPTION

job_id uniqueidentifier Unique ID of the job.

originating_server nvarchar(30) Name of the server from which the job


came.

name sysname Name of the job.

enabled tinyint Indicates whether the job is enabled to


be executed.

description nvarchar(512) Description for the job.

start_step_id int ID of the step in the job where


execution should begin.

category sysname Job category.

owner sysname Job owner.

notify_level_eventlog int Bitmask indicating under what


circumstances a notification event
should be logged to the Microsoft
Windows application log. Can be one of
these values:

0 = Never

1 = When a job succeeds

2 = When the job fails

3 = Whenever the job completes


(regardless of the job outcome)

notify_level_email int Bitmask indicating under what


circumstances a notification e-mail
should be sent when a job completes.
Possible values are the same as for
notify_level_eventlog.

notify_level_netsend int Bitmask indicating under what


circumstances a network message
should be sent when a job completes.
Possible values are the same as for
notify_level_eventlog.
COLUMN NAME DATA TYPE DESCRIPTION

notify_level_page int Bitmask indicating under what


circumstances a page should be sent
when a job completes. Possible values
are the same as for
notify_level_eventlog.

notify_email_operator sysname E-mail name of the operator to notify.

notify_netsend_operator sysname Name of the computer or user used


when sending network messages.

notify_page_operator sysname Name of the computer or user used


when sending a page.

delete_level int Bitmask indicating under what


circumstances the job should be
deleted when a job completes. Possible
values are the same as for
notify_level_eventlog.

date_created datetime Date the job was created.

date_modified datetime Date the job was last modified.

version_number int Version of the job (automatically


updated each time the job is modified).

last_run_date int Date the job last started execution.

last_run_time int Time the job last started execution.

last_run_outcome int Outcome of the job the last time it ran:

0 = Failed

1 = Succeeded

3 = Canceled

5 = Unknown

next_run_date int Date the job is scheduled to run next.

next_run_time int Time the job is scheduled to run next.

next_run_schedule_id int Identification number of the next run


schedule.

current_execution_status int Current execution status.

current_execution_step sysname Current execution step in the job.


COLUMN NAME DATA TYPE DESCRIPTION

current_retry_attempt int If the job is running and the step has


been retried, this is the current retry
attempt.

has_step int Number of job steps the job has.

has_schedule int Number of job schedules the job has.

has_target int Number of target servers the job has.

type int Type of the job.

1 = Local job.

2 = Multiserver job.

0 = Job has no target servers.

If job_id or job_name is specified, sp_help_job returns these additional result sets for job steps, job schedules,
and job target servers.
This is the result set for job steps.

COLUMN NAME DATA TYPE DESCRIPTION

step_id int Unique (for this job) identifier for the


step.

step_name sysname Name of the step.

subsystem nvarchar(40) Subsystem in which to execute the step


command.

command nvarchar(3200) Command to execute.

flags nvarchar(4000) Bitmask of values that control step


behavior.

cmdexec_success_code int For a CmdExec step, this is the process


exit code of a successful command.

on_success_action nvarchar(4000) What to do if the step succeeds:

1 = Quit with success.

2 = Quit with failure.

3 = Go to next step.

4 = Go to step.

on_success_step_id int If on_success_action is 4, this indicates


the next step to execute.
COLUMN NAME DATA TYPE DESCRIPTION

on_fail_action nvarchar(4000) Action to take if the step fails. Values


are the same as for on_success_action.

on_fail_step_id int If on_fail_action is 4, this indicates the


next step to execute.

server sysname Reserved.

database_name sysname For a Transact-SQL step, this is the


database in which the command will
executes.

database_user_name sysname For a Transact-SQL step, this is the


database user context in which the
command executes.

retry_attempts int Maximum number of times the


command should be retried (if it is
unsuccessful) before the step is
deemed to have failed.

retry_interval int Interval (in minutes) between any retry


attempts.

os_run_priority varchar(4000) Reserved.

output_file_name varchar(200) File to which command output should


be written ( Transact-SQL and
CmdExec steps only).

last_run_outcome int Outcome of the step the last time it


ran:

0 = Failed

1 = Succeeded

3 = Canceled

5 = Unknown

last_run_duration int Duration (in seconds) of the step the


last time it ran.

last_run_retries int Number of times the command was


retried the last time the step ran.

last_run_date int Date the step last started execution.

last_run_time int Time the step last started execution.

proxy_id int Proxy for the job step.

This is the result set for job schedules.


COLUMN NAME DATA TYPE DESCRIPTION

schedule_id int Identifier of the schedule (unique


across all jobs).

schedule_name sysname Name of the schedule (unique for this


job only).

enabled int Whether the schedule is active (1) or


not (0).

freq_type int Value indicating when the job is to be


executed:

1 = Once

4 = Daily

8 = Weekly

16 = Monthly

32 = Monthly, relative to the


freq_interval

64 = Run when SQLServerAgent


service starts.

freq_interval int Days when the job is executed. The


value depends on the value of
freq_type. For more information, see
sp_add_schedule (Transact-SQL)

freq_subday_type Int Units for freq_subday_interval. For


more information, see sp_add_schedule
(Transact-SQL)

freq_subday_interval int Number of freq_subday_type periods


to occur between each execution of the
job. For more information, see
sp_add_schedule (Transact-SQL)

freq_relative_interval int Scheduled job's occurrence of the


freq_interval in each month. For more
information, see sp_add_schedule
(Transact-SQL)

freq_recurrence_factor int Number of months between the


scheduled execution of the job.

active_start_date int Date to begin execution of the job.

active_end_date int Date to end execution of the job.

active_start_time int Time to begin the execution of the job


on active_start_date.
COLUMN NAME DATA TYPE DESCRIPTION

active_end_time int Time to end execution of the job on


active_end_date.

date_created datetime Date the schedule is created.

schedule_description nvarchar(4000) An English description of the schedule


(if requested).

next_run_date int Date the schedule will next cause the


job to run.

next_run_time int Time the schedule will next cause the


job to run.

schedule_uid uniqueidentifier Identifier for the schedule.

job_count int Returns the number of jobs that


reference this schedule.

This is the result set for job target servers.

COLUMN NAME DATA TYPE DESCRIPTION

server_id int Identifier of the target server.

server_name nvarchar(30) Computer name of the target server.

enlist_date datetime Date the target server enlisted into the


master server.

last_poll_date datetime Date the target server last polled the


master server.

last_run_date int Date the job last started execution on


this target server.

last_run_time int Time the job last started execution on


this target server.

last_run_duration int Duration of the job the last time it ran


on this target server.

last_run_outcome tinyint Outcome of the job the last time it ran


on this server:

0 = Failed

1 = Succeeded

3 = Canceled

5 = Unknown
COLUMN NAME DATA TYPE DESCRIPTION

last_outcome_message nvarchar(1024) Outcome message from the job the


last time it ran on this target server.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of SQLAgentUserRole can only view jobs that they own. Members of sysadmin,
SQLAgentReaderRole, and SQLAgentOperatorRole can view all local and multiserver jobs.

Examples
A. List information for all jobs
The following example executes the sp_help_job procedure with no parameters to return the information for all
of the jobs currently defined in the msdb database.

USE msdb ;
GO

EXEC dbo.sp_help_job ;
GO

B. Listing information for jobs matching a specific criteria


The following example lists job information for the multiserver jobs owned by françoisa where the job is
enabled and executing.

USE msdb ;
GO

EXEC dbo.sp_help_job
@job_type = N'MULTI-SERVER',
@owner_login_name = N'françoisa',
@enabled = 1,
@execution_status = 1 ;
GO

C. Listing all aspects of information for a job


The following example lists all aspects of the information for the job NightlyBackups .
USE msdb ;
GO

EXEC dbo.sp_help_job
@job_name = N'NightlyBackups',
@job_aspect = N'ALL' ;
GO

See Also
sp_add_job (Transact-SQL)
sp_delete_job (Transact-SQL)
sp_update_job (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_jobactivity (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Lists information about the runtime state of SQL Server Agent jobs.
Transact-SQL Syntax Conventions

Syntax
sp_help_jobactivity { [ @job_id = ] job_id | [ @job_name = ] 'job_name' }
[ , [ @session_id = ] session_id ]

Arguments
[ @job_id =] job_id
The job identification number. job_idis uniqueidentifier, with a default of NULL.
[ @job_name =] 'job_name'
The name of the job. job_nameis sysname, with a default of NULL.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @session_id = ] session_id
The session id to report information about. session_id is int, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Returns the following result set:

COLUMN NAME DATA TYPE DESCRIPTION

session_id int Agent session identification number.

job_id uniqueidentifier Identifier for the job.

job_name sysname Name of the job.

run_requested_date datetime When that the job was requested to


run.
COLUMN NAME DATA TYPE DESCRIPTION

run_requested_source sysname The source of the request to run the


job. One of:

1 = Run on a schedule

2 = Run in response to an alert

3 = Run on startup

4 = Run by user

6 = Run on CPU idle schedule

queued_date datetime When the request was queued. NULL if


the job was run directly.

start_execution_date datetime When the job was assigned to a


runnable thread.

last_executed_step_id int The step ID of the most recently run job


step.

last_exectued_step_date datetime The time that the most recently run job
step started to run.

stop_execution_date datetime The time that the job stopped running.

next_scheduled_run_date datetime When the job is next scheduled to run.

job_history_id int Identifier for the job history in the job


history table.

message nvarchar(1024) Message produced during the last run


of the job.

run_status int Status returned from the last run of the


job:

0 = Error failed

1 = Succeeded

3 = Canceled

5 = Status unknown

operator_id_emailed int ID number of the operator notified via


email at completion of the job.

operator_id_netsent int ID number of the operator notified via


net send at completion of the job.

operator_id_paged int ID number of the operator notified via


pager at completion of the job.
Remarks
This procedure provides a snapshot of the current state of the jobs. The results returned represent information at
the time that the request is processed.
SQL Server Agent creates a session id each time that the Agent service starts. The session id is stored in the table
msdb.dbo.syssessions.
When no session_id is provided, lists information about the most recent session.
When no job_name or job_id is provided, lists information for all jobs.

Permissions
By default, members of the sysadmin fixed server role can run this stored procedure. Other users must be granted
one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Only members of sysadmin can view the activity for jobs owned by other users.

Examples
The following example lists activity for all jobs that the current user has permission to view.

USE msdb ;
GO

EXEC dbo.sp_help_jobactivity ;
GO

See Also
SQL Server Agent Stored Procedures (Transact-SQL)
sp_help_jobcount (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Provides the number of jobs that a schedule is attached to.
Transact-SQL Syntax Conventions

Syntax
sp_help_jobcount
[ @schedule_name = ] 'schedule_name' ,
[ @schedule_id = ] schedule_id

Arguments
[ @schedule_id= ] schedule_id
The identifier of the schedule to list. schedule_id is int, with no default. Either schedule_id or schedule_name may
be specified.
[ @schedule_name= ] 'schedule_name'
The name of the schedule to list. schedule_name is sysname, with no default. Either schedule_id or schedule_name
may be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Returns the following result set:

COLUMN NAME DATA TYPE DESCRIPTION

JobCount int Number of jobs for the specified


schedule.

Remarks
This procedure lists the number of jobs attached to the specified schedule.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Only members of sysadmin can view counts for jobs that are owned by others.

Examples
The following example lists the number of jobs attached to the NightlyJobs schedule.

USE msdb ;
GO

EXEC sp_help_jobcount
@schedule_name = N'NightlyJobs' ;
GO

See Also
SQL Server Agent Stored Procedures (Transact-SQL)
sp_add_schedule (Transact-SQL)
sp_attach_schedule (Transact-SQL)
sp_delete_schedule (Transact-SQL)
sp_detach_schedule (Transact-SQL)
sp_help_jobhistory (Transact-SQL)
11/17/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Provides information about the jobs for servers in the multiserver administration domain.
Transact-SQL Syntax Conventions

Syntax
sp_help_jobhistory [ [ @job_id = ] job_id ]
[ , [ @job_name = ] 'job_name' ]
[ , [ @step_id = ] step_id ]
[ , [ @sql_message_id = ] sql_message_id ]
[ , [ @sql_severity = ] sql_severity ]
[ , [ @start_run_date = ] start_run_date ]
[ , [ @end_run_date = ] end_run_date ]
[ , [ @start_run_time = ] start_run_time ]
[ , [ @end_run_time = ] end_run_time ]
[ , [ @minimum_run_duration = ] minimum_run_duration ]
[ , [ @run_status = ] run_status ]
[ , [ @minimum_retries = ] minimum_retries ]
[ , [ @oldest_first = ] oldest_first ]
[ , [ @server = ] 'server' ]
[ , [ @mode = ] 'mode' ]

Arguments
[ @job_id= ] job_id
The job identification number. job_id is uniqueidentifier, with a default of NULL.
[ @job_name= ] 'job_name'
The name of the job. job_name is sysname, with a default of NULL.
[ @step_id= ] step_id
The step identification number. step_id is int, with a default of NULL.
[ @sql_message_id= ] sql_message_id
The identification number of the error message returned by Microsoft SQL Server when executing the job.
sql_message_id is int, with a default of NULL.
[ @sql_severity= ] sql_severity
The severity level of the error message returned by SQL Server when executing the job. sql_severity is int, with a
default of NULL.
[ @start_run_date= ] start_run_date
The date the job was started. start_run_dateis int, with a default of NULL. start_run_date must be entered in the
form YYYYMMDD, where YYYY is a four-character year, MM is a two-character month name, and DD is a two-
character day name.
[ @end_run_date= ] end_run_date
The date the job was completed. end_run_date is int, with a default of NULL. end_run_datemust be entered in the
form YYYYMMDD, where YYYY is a four-digit year, MM is a two-character month name, and DD is a two-character
day name.
[ @start_run_time= ] start_run_time
The time the job was started. start_run_time is int, with a default of NULL. start_run_timemust be entered in the
form HHMMSS, where HH is a two-character hour of the day, MM is a two-character minute of the day, and SS is a
two-character second of the day.
[ @end_run_time= ] end_run_time
The time the job completed its execution. end_run_time is int, with a default of NULL. end_run_timemust be
entered in the form HHMMSS, where HH is a two-character hour of the day, MM is a two-character minute of the
day, and SS is a two-character second of the day.
[ @minimum_run_duration= ] minimum_run_duration
The minimum length of time for the completion of the job. minimum_run_duration is int, with a default of NULL.
minimum_run_durationmust be entered in the form HHMMSS, where HH is a two-character hour of the day, MM
is a two-character minute of the day, and SS is a two-character second of the day.
[ @run_status= ] run_status
The execution status of the job. run_status is int, with a default of NULL, and can be one of these values.

VALUE DESCRIPTION

0 Failed

1 Succeeded

2 Retry (step only)

3 Canceled

4 In-progress message

5 Unknown

[ @minimum_retries= ] minimum_retries
The minimum number of times a job should retry running. minimum_retries is int, with a default of NULL.
[ @oldest_first= ] oldest_first
Is whether to present the output with the oldest jobs first. oldest_first is int, with a default of 0, which presents the
newest jobs first. 1 presents the oldest jobs first.
[ @server= ] 'server'
The name of the server on which the job was performed. server is nvarchar(30), with a default of NULL.
[ @mode= ] 'mode'
Is whether SQL Server prints all columns in the result set (FULL) or a summary of the columns. mode is
varchar(7), with a default of SUMMARY.

Return Code Values


0 (success) or 1 (failure)

Result Sets
The actual column list depends on the value of mode. The most comprehensive set of columns is shown below and
is returned when mode is FULL.

COLUMN NAME DATA TYPE DESCRIPTION

instance_id int History entry identification number.

job_id uniqueidentifier Job identification number.

job_name sysname Job name.

step_id int Step identification number (will be 0 for


a job history).

step_name sysname Step name (will be NULL for a job


history).

sql_message_id int For a Transact-SQL step, the most


recent Transact-SQL error number
encountered while running the
command.

sql_severity int For a Transact-SQL step, the highest


Transact-SQL error severity
encountered while running the
command.

message nvarchar(1024) Job or step history message.

run_status int Outcome of the job or step.

run_date int Date the job or step began executing.

run_time int Time the job or step began executing.

run_duration int Elapsed time in the execution of the job


or step in HHMMSS format.

operator_emailed nvarchar(20) Operator who was e-mailed regarding


this job (is NULL for step history).

operator_netsent nvarchar(20) Operator who was sent a network


message regarding this job (is NULL for
step history).

operator_paged nvarchar(20) Operator who was paged regarding this


job (is NULL for step history).

retries_attempted int Number of times the step was retried


(always 0 for a job history).

server nvarchar(30) Server the step or job executes on. Is


always (local).

Remarks
sp_help_jobhistory returns a report with the history of the specified scheduled jobs. If no parameters are
specified, the report contains the history for all scheduled jobs.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of the SQLAgentUserRole database role can only view the history for jobs that they own.

Examples
A. Listing all job information for a job
The following example lists all job information for the NightlyBackups job.

USE msdb ;
GO

EXEC dbo.sp_help_jobhistory
@job_name = N'NightlyBackups' ;
GO

B. Listing information for jobs that match certain conditions


The following example prints all columns and all job information for any failed jobs and failed job steps with an
error message of 50100 (a user-defined error message) and a severity of 20 .

USE msdb
GO

EXEC dbo.sp_help_jobhistory
@sql_message_id = 50100,
@sql_severity = 20,
@run_status = 0,
@mode = N'FULL' ;
GO

See Also
sp_purge_jobhistory (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_jobs_in_schedule (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns information about the jobs that a particular schedule is attached to.
Transact-SQL Syntax Conventions

Syntax
sp_help_jobs_in_schedule
[ @schedule_name = ] 'schedule_name' ,
[ @schedule_id = ] schedule_id

Arguments
[ @schedule_id = ] schedule_id
The identifier of the schedule to list information for. schedule_id is int, with no default. Either schedule_id or
schedule_name may be specified.
[ @schedule_name = ] 'schedule_name'
The name of the schedule to list information for. schedule_name is sysname, with no default. Either schedule_id or
schedule_name may be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Returns the following result set:

COLUMN NAME DATA TYPE DESCRIPTION

job_id uniqueidentifier Unique ID of the job.

originating_server nvarchar(30) Name of the server from which the job


came.

name sysname Name of the job.

enabled tinyint Indicates whether the job is enabled to


be executed.

description nvarchar(512) Description for the job.

start_step_id int ID of the step in the job where


execution should begin.
COLUMN NAME DATA TYPE DESCRIPTION

category sysname Job category.

owner sysname Job owner.

notify_level_eventlog int Bitmask indicating under what


circumstances a notification event
should be logged to the Microsoft
Windows application log. Can be one of
these values:

0 = Never

1 = When a job succeeds

2 = When the job fails

3 = Whenever the job completes


(regardless of the job outcome)

notify_level_email int Bitmask indicating under what


circumstances a notification e-mail
should be sent when a job completes.
Possible values are the same as for
notify_level_eventlog.

notify_level_netsend int Bitmask indicating under what


circumstances a network message
should be sent when a job completes.
Possible values are the same as for
notify_level_eventlog.

notify_level_page int Bitmask indicating under what


circumstances a page should be sent
when a job completes. Possible values
are the same as for
notify_level_eventlog.

notify_email_operator sysname E-mail name of the operator to notify.

notify_netsend_operator sysname Name of the computer or user used


when sending network messages.

notify_page_operator sysname Name of the computer or user used


when sending a page.

delete_level int Bitmask indicating under what


circumstances the job should be deleted
when a job completes. Possible values
are the same as for
notify_level_eventlog.

date_created datetime Date the job was created.

date_modified datetime Date the job was last modified.


COLUMN NAME DATA TYPE DESCRIPTION

version_number int Version of the job (automatically


updated each time the job is modified).

last_run_date int Date the job last started execution.

last_run_time int Time the job last started execution.

last_run_outcome int Outcome of the job the last time it ran:

0 = Failed

1 = Succeeded

3 = Canceled

5 = Unknown

next_run_date int Date the job is scheduled to run next.

next_run_time int Time the job is scheduled to run next.

next_run_schedule_id int Identification number of the next run


schedule.

current_execution_status int Current execution status.

current_execution_step sysname Current execution step in the job.

current_retry_attempt int If the job is running and the step has


been retried, this is the current retry
attempt.

has_step int Number of job steps the job has.

has_schedule int Number of job schedules the job has.

has_target int Number of target servers the job has.

type int Type of the job:

1 = Local job.

2 = Multiserver job.

0 = Job has no target servers.

Remarks
This procedure lists information about jobs attached to the specified schedule.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of SQLAgentUserRole can only view the status of jobs that they own.

Examples
The following example lists the jobs attached to the NightlyJobs schedule.

USE msdb ;
GO

EXEC sp_help_jobs_in_schedule
@schedule_name = N'NightlyJobs' ;
GO

See Also
SQL Server Agent Stored Procedures (Transact-SQL)
sp_add_schedule (Transact-SQL)
sp_attach_schedule (Transact-SQL)
sp_delete_schedule (Transact-SQL)
sp_detach_schedule (Transact-SQL)
sp_help_jobschedule (Transact-SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about the scheduling of jobs used by SQL Server Management Studio to perform automated
activities.
Transact-SQL Syntax Conventions

Syntax
sp_help_jobschedule { [ @job_id = ] job_id | [ @job_name = ] 'job_name' }
[ , [ @schedule_name = ] 'schedule_name' ]
[ , [ @schedule_id = ] schedule_id ]
[ , [ @include_description = ] include_description ]

Arguments
[ @job_id= ] job_id
The job identification number. job_idis uniqueidentifier, with a default of NULL.
[ @job_name= ] 'job_name'
The name of the job. job_nameis sysname, with a default of NULL.

NOTE: Either job_id or job_name must be specified, but both cannot be specified.

[ @schedule_name= ] 'schedule_name'
The name of the schedule item for the job. schedule_nameis sysname, with a default of NULL.
[ @schedule_id= ] schedule_id
The identification number of the schedule item for the job. schedule_idis int, with a default of NULL.
[ @include_description= ] include_description
Specifies whether to include the description of the schedule in the result set. include_description is bit, with a
default of 0. When include_description is 0, the description of the schedule is not included in the result set. When
include_description is 1, the description of the schedule is included in the result set.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

schedule_id int Schedule identifier number.

schedule_name sysname Name of the schedule.


COLUMN NAME DATA TYPE DESCRIPTION

enabled int Whether the schedule enabled (1) or


not enabled (0).

freq_type int Value indicating when the job is to be


executed.

1 = Once

4 = Daily

8 = Weekly

16 = Monthly

32 = Monthly, relative to the


freq_interval

64 = Run when SQLServerAgent


service starts.

freq_interval int Days when the job is executed. The


value depends on the value of
freq_type. For more information, see
sp_add_schedule (Transact-SQL).

freq_subday_type int Units for freq_subday_interval. For


more information, see sp_add_schedule
(Transact-SQL).

freq_subday_interval int Number of freq_subday_type periods


to occur between each execution of the
job. For more information, see
sp_add_schedule (Transact-SQL).

freq_relative_interval int Scheduled job's occurrence of the


freq_interval in each month. For more
information, see sp_add_schedule
(Transact-SQL).

freq_recurrence_factor int Number of months between the


scheduled execution of the job.

active_start_date int Date the schedule is activated.

active_end_date int End date of the schedule.

active_start_time int Time of the day the schedule starts.

active_end_time int Time of the day schedule ends.

date_created datetime Date the schedule is created.


COLUMN NAME DATA TYPE DESCRIPTION

schedule_description nvarchar(4000) An English description of the schedule


that is derived from values in
msdb.dbo.sysschedules. When
include_description is 0, this column
contains text stating that the
description was not requested.

next_run_date int Date the schedule will next cause the


job to run.

next_run_time int Time the schedule will next cause the


job to run.

schedule_uid uniqueidentifier Identifier for the schedule.

job_count int Count of jobs returned.

NOTE: sp_help_jobschedule returns values from the dbo.sysjobschedules and dbo.sysschedules system
tables in msdb. sysjobschedules updates every 20 minutes. This might affect the values that are returned by
this stored procedure.

Remarks
The parameters of sp_help_jobschedule can be used only in certain combinations. If schedule_id is specified,
neither job_id nor job_name can be specified. Otherwise, the job_id or job_name parameters can be used with
schedule_name.

Permissions
Requires membership in the sysadmin fixed server role. Other users must be granted one of the following SQL
Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of SQLAgentUserRole can only view properties of job schedules that they own.

Examples
A. Returning the job schedule for a specific job
The following example returns the scheduling information for a job named BackupDatabase .

USE msdb ;
GO

EXEC dbo.sp_help_jobschedule
@job_name = N'BackupDatabase' ;
GO
B. Returning the job schedule for a specific schedule
The following example returns the information for the schedule named NightlyJobs and the job named
RunReports .

USE msdb ;
GO

EXEC dbo.sp_help_jobschedule
@job_name = N'RunReports',
@schedule_name = N'NightlyJobs' ;
GO

C. Returning the job schedule and schedule description for a specific schedule
The following example returns the information for the schedule named NightlyJobs and the job named
RunReports . The result set returned includes a description of the schedule.

USE msdb ;
GO

EXEC dbo.sp_help_jobschedule
@job_name = N'RunReports',
@schedule_name = N'NightlyJobs',
@include_description = 1 ;
GO

See Also
sp_add_schedule (Transact-SQL)
sp_delete_schedule (Transact-SQL)
sp_update_schedule (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_jobserver (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about the server for a given job.
Transact-SQL Syntax Conventions

Syntax
sp_help_jobserver
{ [ @job_id = ] job_id
| [ @job_name = ] 'job_name' }
[ , [ @show_last_run_details = ] show_last_run_details ]

Arguments
[ @job_id= ] job_id
The job identification number for which to return information. job_id is uniqueidentifier, with a default of NULL.
[ @job_name= ] 'job_name'
The job name for which to return information. job_name is sysname, with a default of NULL.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @show_last_run_details= ] show_last_run_details
Is whether the last-run execution information is part of the result set. show_last_run_details is tinyint, with a
default of 0. 0 does not include last-run information, and 1 does.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

server_id int Identification number of the target


server.

server_name nvarchar(30) Computer name of the target server.

enlist_date datetime Date the target server enlisted into the


master server.
COLUMN NAME DATA TYPE DESCRIPTION

last_poll_date datetime Date the target server last polled the


master server.

If sp_help_jobserver is executed with show_last_run_details set to 1, the result set has these additional columns.

COLUMN NAME DATA TYPE DESCRIPTION

last_run_date int Date the job last started execution on


this target server.

last_run_time int Time the job last started execution on


this server.

last_run_duration int Duration of the job the last time it ran


on this target server (in seconds).

last_outcome_message nvarchar(1024) Describes the last outcome of the job.

last_run_outcome int Outcome of the job the last time it ran


on this server:

0 = Failed

1 = Succeeded

3 = Canceled

5 = Unknown

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of SQLAgentUserRole can only view information for jobs that they own.

Examples
The following example returns information, including last-run information, about the NightlyBackups job.

USE msdb ;
GO

EXEC dbo.sp_help_jobserver
@job_name = N'NightlyBackups',
@show_last_run_details = 1 ;
GO
See Also
sp_add_jobserver (Transact-SQL)
sp_delete_jobserver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_jobstep (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information for the steps in a job used by SQL Server Agent service to perform automated activities.
Transact-SQL Syntax Conventions

Syntax
sp_help_jobstep { [ @job_id = ] 'job_id' | [ @job_name = ] 'job_name' }
[ , [ @step_id = ] step_id ]
[ , [ @step_name = ] 'step_name' ]
[ , [ @suffix = ] suffix ]

Arguments
[ @job_id =] 'job_id'
The job identification number for which to return job information. job_id is uniqueidentifier, with a default of
NULL.
[ @job_name =] 'job_name'
The name of the job. job_name is sysname, with a default NULL.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @step_id =] step_id
The identification number of the step in the job. If not included, all steps in the job are included. step_id is int, with
a default of NULL.
[ @step_name =] 'step_name'
The name of the step in the job. step_name is sysname, with a default of NULL.
[ @suffix =] suffix
A flag indicating whether a text description is appended to the flags column in the output. suffixis bit, with the
default of 0. If suffix is 1, a description is appended.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

step_id int Unique identifier for the step.

step_name sysname Name of the step in the job.

subsystem nvarchar(40) Subsystem in which to execute the step


command.

command nvarchar(max) Command executed in the step.

flags int A bitmask of values that control step


behavior.

cmdexec_success_code int For a CmdExec step, this is the process


exit code of a successful command.

on_success_action tinyint Action to take if the step succeeds:

1 = Quit the job reporting success.

2 = Quit the job reporting failure.

3 = Go to the next step.

4 = Go to step.

on_success_step_id int If on_success_action is 4, this indicates


the next step to execute.

on_fail_action tinyint What to do if the step fails. Values are


same as on_success_action.

on_fail_step_id int If on_fail_action is 4, this indicates the


next step to execute.

server sysname Reserved.

database_name sysname For a Transact-SQL step, this is the


database in which the command
executes.

database_user_name sysname For a Transact-SQL step, this is the


database user context in which the
command executes.

retry_attempts int Maximum number of times the


command should be retried (if it is
unsuccessful).

retry_interval int Interval (in minutes) for any retry


attempts.

os_run_priority int Reserved.


COLUMN NAME DATA TYPE DESCRIPTION

output_file_name nvarchar(200) File to which command output should


be written ( Transact-SQL, CmdExec,
and PowerShell steps only).

last_run_outcome int Outcome of the step the last time it


ran:

0 = Failed

1 = Succeeded

2 = Retry

3 = Canceled

5 = Unknown

last_run_duration int Duration (in seconds) of the step the


last time it ran.

last_run_retries int Number of times the command was


retried the last time the step ran.

last_run_date int Date the step last started execution.

last_run_time int Time the step last started execution.

proxy_id int Proxy for the job step.

Remarks
sp_help_jobstep is in the msdb database.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of SQLAgentUserRole can only view job steps for jobs that they own.

Examples
A. Return information for all steps in a specific job
The following example returns all the job steps for the job named Weekly Sales Data Backup .
USE msdb ;
GO

EXEC dbo.sp_help_jobstep
@job_name = N'Weekly Sales Data Backup' ;
GO

B. Return information about a specific job step


The following example returns information about the first job step for the job named Weekly Sales Data Backup .

USE msdb ;
GO

EXEC dbo.sp_help_jobstep
@job_name = N'Weekly Sales Data Backup',
@step_id = 1 ;
GO

See Also
sp_add_jobstep (Transact-SQL)
sp_delete_jobstep (Transact-SQL)
sp_help_job (Transact-SQL)
sp_update_jobstep (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_jobsteplog (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns metadata about a specific SQL Server Agent job step log. sp_help_jobsteplog does not return the actual
log.
Transact-SQL Syntax Conventions

Syntax
sp_help_jobsteplog { [ @job_id = ] 'job_id' | [ @job_name = ] 'job_name' }
[ , [ @step_id = ] step_id ]
[ , [ @step_name = ] 'step_name' ]

Arguments
[ @job_id =] 'job_id'
The job identification number for which to return job step log information. job_id is int, with a default of NULL.
[ @job_name =] 'job_name'
The name of the job. job_name is sysname, with a default NULL.

NOTE
Either job_id or job_name must be specified, but both cannot be specified.

[ @step_id =] step_id
The identification number of the step in the job. If not included, all steps in the job are included. step_id is int, with
a default of NULL.
[ @step_name =] 'step_name'
The name of the step in the job. step_name is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

job_id uniqueidentifier Unique identifier of the job.

job_name sysname Name of the job.


COLUMN NAME DATA TYPE DESCRIPTION

step_id int Identifier for the step within the job. For
example, if the step is the first step in
the job, its step_id is 1.

step_name sysname Name of the step in the job.

step_uid uniqueidentifier Unique identifier of the step (system


generated) in the job.

date_created datetime Date that the step was created.

date_modified datetime Date that the step was last modified.

log_size float Size of the job step log in megabytes


(MB).

log nvarchar(max) Job step log output.

Remarks
sp_help_jobsteplog is in the msdb database.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of SQLAgentUserRole can only view job step log metadata for job steps that they own.

Examples
A. Returns job step log information for all steps in a specific job
The following example returns all the job step log information for the job named Weekly Sales Data Backup .

USE msdb ;
GO

EXEC dbo.sp_help_jobsteplog
@job_name = N'Weekly Sales Data Backup' ;
GO

B. Return job step log information about a specific job step


The following example returns job step log information about the first job step for the job named
Weekly Sales Data Backup .
USE msdb ;
GO

EXEC dbo.sp_help_jobsteplog
@job_name = N'Weekly Sales Data Backup',
@step_id = 1 ;
GO

See Also
sp_add_jobstep (Transact-SQL)
sp_delete_jobstep (Transact-SQL)
sp_help_jobstep (Transact-SQL)
sp_delete_jobstep (Transact-SQL)
sp_delete_jobsteplog (Transact-SQL)
SQL Server Agent Stored Procedures (Transact-SQL)
sp_help_notification (Transact-SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports a list of alerts for a given operator or a list of operators for a given alert.
Transact-SQL Syntax Conventions

Syntax
sp_help_notification
[ @object_type = ] 'object_type' ,
[ @name = ] 'name' ,
[ @enum_type = ] 'enum_type' ,
[ @notification_method = ] notification_method
[ , [ @target_name = ] 'target_name' ]

Arguments
[ @object_type =] 'object_type'
The type of information to be returned. object_typeis char(9), with no default. object_type can be ALERTS, which
lists the alerts assigned to the supplied operator name, or OPERATORS, which lists the operators responsible for
the supplied alert name.
[ @name =] 'name'
An operator name (if object_type is OPERATORS) or an alert name (if object_type is ALERTS). name is sysname,
with no default.
[ @enum_type =] 'enum_type'
The object_typeinformation that is returned. enum_type is ACTUAL in most cases. enum_typeis char(10), with no
default, and can be one of these values.

VALUE DESCRIPTION

ACTUAL Lists only the object_types associated with name.

ALL Lists all theobject_types including those that are not


associated with name.

TARGET Lists only the object_types matching the supplied


target_name, regardless of association withname.

[ @notification_method =] notification_method
A numeric value that determines the notification method columns to return. notification_method is tinyint, and
can be one of the following values.
VALUE DESCRIPTION

1 E-mail: returns only the use_email column.

2 Pager: returns only the use_pager column.

4 NetSend: returns only the use_netsend column.

7 All: returns all columns.

[ @target_name =] 'target_name'
An alert name to search for (if object_type is ALERTS) or an operator name to search for (if object_type is
OPERATORS). target_name is needed only if enum_type is TARGET. target_name is sysname, with a default of
NULL.

Return Code Valves


0 (success) or 1 (failure)

Result Sets
If object_type is ALERTS, the result set lists all the alerts for a given operator.

COLUMN NAME DATA TYPE DESCRIPTION

alert_id int Alert identifier number.

alert_name sysname Alert name.

use_email int E-mail is used to notify the operator:

1 = Yes

0 = No

use_pager int Pager is used to notify operator:

1 = Yes

0 = No

use_netsend int Network pop-up is used to notify the


operator:

1 = Yes

0 = No

has_email int Number of e-mail notifications sent for


this alert.

has_pager int Number of pager notifications sent for


this alert.
COLUMN NAME DATA TYPE DESCRIPTION

has_netsend int Number of net send notifications sent


for this alert.

If object_type is OPERATORS, the result set lists all the operators for a given alert.

COLUMN NAME DATA TYPE DESCRIPTION

operator_id int Operator identification number.

operator_name sysname Operator name.

use_email int E-mail is used to send notification of


the operator:

1 = Yes

0 = No

use_pager int Pager is used to send notification of the


operator:

1 = Yes

0 = No

use_netsend int Is a network pop-up used to notify the


operator:

1 = Yes

0 = No

has_email int Operator has an e-mail address:

1 = Yes

0 = No

has_pager int Operator has a pager address:

1 = Yes

0 = No

has_netsend int Operator has net send notification


configured.

1 = Yes

0 = No

Remarks
This stored procedure must be run from the msdb database.
Permissions
To execute this stored procedure, a user must be a member of the sysadmin fixed server role.

Examples
A. Listing alerts for a specific operator
The following example returns all alerts for which the operator François Ajenstat receives any kind of
notification.

USE msdb ;
GO

EXEC dbo.sp_help_notification
@object_type = N'ALERTS',
@name = N'François Ajenstat',
@enum_type = N'ACTUAL',
@notification_method = 7 ;
GO

B. Listing operators for a specific alert


The following example returns all operators who receive any kind of notification for the Test Alert alert.

USE msdb ;
GO

EXEC sp_help_notification
@object_type = N'OPERATORS',
@name = N'Test Alert',
@enum_type = N'ACTUAL',
@notification_method = 7 ;
GO

See Also
sp_add_notification (Transact-SQL)
sp_delete_notification (Transact-SQL)
sp_update_notification (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_operator (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reports information about the operators defined for the server.
Transact-SQL Syntax Conventions

Syntax
sp_help_operator
{ [ @operator_name = ] 'operator_name'
| [ @operator_id = ] operator_id }

Arguments
[ @operator_name= ] 'operator_name'
The operator name. operator_name is sysname. If operator_name is not specified, information about all
operators is returned.
[ @operator_id= ] operator_id
The identification number of the operator for which information is requested. operator_idis int, with a default of
NULL.

NOTE
Either operator_id or operator_name must be specified, but both cannot be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

id int Operator identification number.

name sysname Operator Name.

enabled tinyint Operator is available to receive any


notifications:

1 = Yes

0 = No
COLUMN NAME DATA TYPE DESCRIPTION

email_address nvarchar(100) Operator e-mail address.

last_email_date int Date the operator was last notified by


e-mail.

last_email_time int Time the operator was last notified by


e-mail.

pager_address nvarchar(100) Operator pager address.

last_pager_date int Date the operator was last notified by


pager.

last_pager_time int Time the operator was last notified by


pager.

weekday_pager_start_time int The start of the time period during


which the operator is available to
receive pager notifications on a
weekday.

weekday_pager_end_time int The end of the time period during


which the operator is available to
receive pager notifications on a
weekday.

saturday_pager_start_time int The start of the time period during


which the operator is available to
receive pager notifications on
Saturdays.

saturday_pager_end_time int The end of the time period during


which the operator is available to
receive pager notifications on
Saturdays.

sunday_pager_start_time int The start of the time period during


which the operator is available to
receive pager notifications on Sundays.

sunday_pager_end_time int The end of the time period during


which the operator is available to
receive pager notifications on Sundays.

pager_days tinyint A bitmask (1 = Sunday, 64 = Saturday)


of days-of-the week indicating when
the operator is available to receive
pager notifications.

netsend_address nvarchar(100) Operator address for network pop-up


notifications.

last_netsend_date int Date the operator was last notified by


network pop-up.
COLUMN NAME DATA TYPE DESCRIPTION

last_netsend_time int Time the operator was last notified by


network pop-up.

category_name sysname Name of the operator category to


which this operator belongs.

Remarks
sp_help_operator must be run from the msdb database.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.

Examples
The following example reports information about operator François Ajenstat .

USE msdb ;
GO

EXEC dbo.sp_help_operator
@operator_name = N'François Ajenstat' ;
GO

See also
sp_add_operator (Transact-SQL)
sp_delete_operator (Transact-SQL)
sp_update_operator (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_proxy (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Lists information for one or more proxies.
Transact-SQL Syntax Conventions

Syntax
sp_help_proxy
[ @proxy_id = ] id,
[ @proxy_name = ] 'proxy_name' ,
[ @subsystem_name = ] 'subsystem_name' ,
[ @name = ] 'name'

Arguments
[ @proxy_id = ] id
The proxy identification number of the proxy to list information for. The proxy_id is int, with a default of NULL.
Either the id or the proxy_name may be specified.
[ @proxy_name = ] 'proxy_name'
The name of the proxy to list information for. The proxy_name is sysname, with a default of NULL. Either the id or
the proxy_name may be specified.
[ @subsystem_name = ] 'subsystem_name'
The name of the subsystem to list proxies for. The subsystem_name is sysname, with a default of NULL. When
subsystem_name is specified, name must also be specified.
The following table lists the values for each subsystem.

VALUE DESCRIPTION

ActiveScripting ActiveX Script

CmdExec Operating System (CmdExec)

Snapshot Replication Snapshot Agent

LogReader Replication Log Reader Agent

Distribution Replication Distribution Agent

Merge Replication Merge Agent

QueueReader Replication Queue Reader Agent


VALUE DESCRIPTION

ANALYSISQUERY Analysis Services Command

ANALYSISCOMMAND Analysis Services Query

Dts SSIS package execution

PowerShell PowerShell Script

[ @name = ] 'name'
The name of a SQL Server login to list proxies for. The name is nvarchar(256), with a default of NULL. When
name is specified, subsystem_name must also be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

proxy_id int Proxy identification number.

name sysname The name of the proxy.

credential_identity sysname The Microsoft Windows domain name


and user name for the credential
associated with the proxy.

enabled tinyint Whether this proxy is enabled. { 0 = not


enabled, 1 = enabled }

description nvarchar(1024) The description for this proxy.

user_sid varbinary(85) The Windows security id of the


Windows user for this proxy.

credential_id int The identifier for the credential


associated with this proxy.

credential_identity_exists int Whether the credential_identity exists. {


0 = does not exist, 1 = exists }

Remarks
When no parameters are provided, sp_help_proxy lists information for all proxies in the instance.
To determine which proxies a login can use for a given subsystem, specify name and subsystem_name. When
these arguments are provided, sp_help_proxy lists proxies that the login specified may access and that may be
used for the specified subsystem.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted the SQLAgentOperatorRole fixed database role in the msdb database.
For details about SQLAgentOperatorRole, see SQL Server Agent Fixed Database Roles.

NOTE
The credential_identity and user_sid columns are only returned in the result set when members of sysadmin execute this
stored procedure.

Examples
A. Listing information for all proxies
The following example lists information for all proxies in the instance.

USE msdb ;
GO

EXEC dbo.sp_help_proxy ;
GO

B. Listing information for a specific proxy


The following example lists information for the proxy named Catalog application proxy .

USE msdb ;
GO

EXEC dbo.sp_help_proxy
@proxy_name = N'Catalog application proxy' ;
GO

See Also
SQL Server Agent Stored Procedures (Transact-SQL)
sp_add_proxy (Transact-SQL)
sp_delete_proxy (Transact-SQL)
sp_help_schedule (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Lists information about schedules.
Transact-SQL Syntax Conventions

Syntax
sp_help_schedule
[ @schedule_id = ] id ,
[ @schedule_name = ] 'schedule_name'
[ , [ @attached_schedules_only = ] attached_schedules_only ]
[ , [ @include_description = ] include_description ]

Arguments
[ @schedule_id = ] id
The identifier of the schedule to list. schedule_name is int, with no default. Either schedule_id or schedule_name
may be specified.
[ @schedule_name = ] 'schedule_name'
The name of the schedule to list. schedule_name is sysname, with no default. Either schedule_id or schedule_name
may be specified.
[ @attached_schedules_only = ] attached_schedules_only ]
Specifies whether to show only schedules that a job is attached to. attached_schedules_only is bit, with a default of
0. When attached_schedules_only is 0, all schedules are shown. When attached_schedules_only is 1, the result set
contains only schedules that are attached to a job.
[ @include_description = ] include_description
Specifies whether to include descriptions in the result set. include_description is bit, with a default of 0. When
include_description is 0, the schedule_description column of the result set contains a placeholder. When
include_description is 1, the description of the schedule is included in the result set.

Return Code Values


0 (success) or 1 (failure)

Result Sets
This procedure returns the following result set:

COLUMN NAME DATA TYPE DESCRIPTION

schedule_id int Schedule identifier number.


COLUMN NAME DATA TYPE DESCRIPTION

schedule_uid uniqueidentifier Identifier for the schedule.

schedule_name sysname Name of the schedule.

enabled int Whether the schedule enabled (1) or


not enabled (0).

freq_type int Value indicating when the job is to be


executed.

1 = Once

4 = Daily

8 = Weekly

16 = Monthly

32 = Monthly, relative to the


freq_interval

64 = Run when SQLServerAgent service


starts.

freq_interval int Days when the job is executed. The


value depends on the value of
freq_type. For more information, see
sp_add_schedule (Transact-SQL).

freq_subday_type int Units for freq_subday_interval. For


more information, see sp_add_schedule
(Transact-SQL).

freq_subday_interval int Number of freq_subday_type periods


to occur between each execution of the
job. For more information, see
sp_add_schedule (Transact-SQL).

freq_relative_interval int Scheduled job's occurrence of the


freq_interval in each month. For more
information, see sp_add_schedule
(Transact-SQL).

freq_recurrence_factor int Number of months between the


scheduled execution of the job.

active_start_date int Date the schedule is activated.

active_end_date int End date of the schedule.

active_start_time int Time of the day the schedule starts.

active_end_time int Time of the day schedule ends.

date_created datetime Date the schedule is created.


COLUMN NAME DATA TYPE DESCRIPTION

schedule_description nvarchar(4000) An English description of the schedule


(if requested).

job_count int Returns how many jobs reference this


schedule.

Remarks
When no parameters are provided, sp_help_schedule lists information for all schedules in the instance.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of SQLAgentUserRole can only view the schedules that they own.

Examples
A. Listing information for all schedules in the instance
The following example lists information for all schedules in the instance.

USE msdb ;
GO

EXEC dbo.sp_help_schedule ;
GO

B. Listing information for a specific schedule


The following example lists information for the schedule named NightlyJobs .

USE msdb ;
GO

EXEC dbo.sp_help_schedule
@schedule_name = N'NightlyJobs' ;
GO

See Also
sp_add_schedule (Transact-SQL)
sp_attach_schedule (Transact-SQL)
sp_delete_schedule (Transact-SQL)
sp_detach_schedule (Transact-SQL)
sp_help_targetserver (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Lists all target servers.
Transact-SQL Syntax Conventions

Syntax
sp_help_targetserver
[ [ @server_name = ] 'server_name' ]

Arguments
[ @server_name= ] 'server_name'
The name of the server for which to return information. server_name is nvarchar(30), with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
If server_name is not specified, sp_help_targetserver returns this result set.

COLUMN NAME DATA TYPE DESCRIPTION

server_id int Server identification number.

server_name nvarchar(30) Server name.

location nvarchar(200) Location of the specified server.

time_zone_adjustment int Time zone adjustment, in hours, from


Greenwich mean time (GMT).

enlist_date datetime Date of the specified server's


enlistment.

last_poll_date datetime Date the server was last polled for jobs.

status int Status of the specified server.

unread_instructions int Whether the server has unread


instructions. If all rows have been
downloaded, this column is 0.
COLUMN NAME DATA TYPE DESCRIPTION

local_time datetime Local date and time on the target


server, which is based on the local time
on the target server as of the last poll
of the master server.

enlisted_by_nt_user nvarchar(100) Microsoft Windows user that enlisted


the target server.

poll_interval int Frequency in seconds with which the


target server polls the Master
SQLServerAgent service in order to
download jobs and upload job status.

Permissions
To execute this stored procedure, a user must be a member of the sysadmin fixed server role.

Examples
A. Listing information for all registered target servers
The following example lists information for all registered target servers.

USE msdb ;
GO

EXEC dbo.sp_help_targetserver ;
GO

B. Listing information for a specific target server


The following example lists information for the target server SEATTLE2 .

USE msdb ;
GO

EXEC dbo.sp_help_targetserver N'SEATTLE2' ;


GO

See Also
sp_add_targetservergroup (Transact-SQL)
sp_delete_targetserver (Transact-SQL)
sp_delete_targetservergroup (Transact-SQL)
sp_update_targetservergroup (Transact-SQL)
dbo.sysdownloadlist (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_targetservergroup (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Lists all target servers in the specified group. If no group is specified, SQL Server returns information about all
target server groups.
Transact-SQL Syntax Conventions

Syntax
sp_help_targetservergroup
[ [ @name = ] 'name' ]

Argument
[ @name= ] 'name'
Is the name of the target server group for which to return information. name is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

servergroup_id int Identification number of the server


group

name sysname Name of the server group

Permissions
Permissions to execute this procedure default to the sysadmin fixed server role.

Examples
A. Listing information for all target server groups
This example lists information for all target server groups.

USE msdb ;
GO

EXEC dbo.sp_help_targetservergroup ;
GO
B. Listing information for a specific target server group
This example lists information for the Servers Maintaining Customer Information target server group.

USE msdb ;
GO

EXEC dbo.sp_help_targetservergroup
N'Servers Maintaining Customer Information' ;
GO

See Also
sp_add_targetservergroup (Transact-SQL)
sp_delete_targetservergroup (Transact-SQL)
sp_update_targetservergroup (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_manage_jobs_by_login (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes or reassigns jobs that belong to the specified login.
Transact-SQL Syntax Conventions

Syntax
sp_manage_jobs_by_login
[ @action = ] 'action'
[, [@current_owner_login_name = ] 'current_owner_login_name']
[, [@new_owner_login_name = ] 'new_owner_login_name']

Arguments
[ @action= ] 'action'
The action to take for the specified login. action is varchar(10), with no default. When actionis DELETE,
sp_manage_jobs_by_login deletes all jobs owned by current_owner_login_name. When action is REASSIGN, all
jobs are assigned to new_owner_login_name.
[ @current_owner_login_name= ] 'current_owner_login_name'
The login name of the current job owner. current_owner_login_name is sysname, with no default.
[ @new_owner_login_name= ] 'new_owner_login_name'
The login name of the new job owner. Use this parameter only if action is REASSIGN. new_owner_login_name is
sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Permissions
To run this stored procedure, users must be granted the sysadmin fixed server role.

Examples
The following example reassigns all jobs from danw to françoisa .
USE msdb ;
GO

EXEC dbo.sp_manage_jobs_by_login
@action = N'REASSIGN',
@current_owner_login_name = N'danw',
@new_owner_login_name = N'françoisa' ;
GO

See Also
sp_delete_job (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_msx_defect (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the current server from multiserver operations.
Cau t i on

sp_msx_defect edits the registry. Manual editing of the registry is not recommended because inappropriate or
incorrect changes can cause serious configuration problems for your system. Therefore, only experienced users
should use the Registry Editor program to edit the registry. For more information, see the documentation for
Microsoft Windows.
Transact-SQL Syntax Conventions

Syntax
sp_msx_defect [@forced_defection =] forced_defection

Arguments
[ @forced_defection =] forced_defection
Specifies whether or not to force the defection to occur if the Master SQLServerAgent has been permanently lost
due to an irreversibly corrupt msdb database, or no msdb database backup. forced_defectionis bit, with a default
of 0, which indicates that no forced defection should occur. A value of 1 forces defection.
After forcing a defection by executing sp_msx_defect, a member of the sysadmin fixed server role at the Master
SQLServerAgent must run the following command to complete the defection:

EXECUTE msdb.dbo.sp_delete_targetserver @server_name = 'tsx-server', @post_defection = 0;

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
When sp_msx_defect properly completes, a message is returned.

Permissions
To execute this stored procedure, a user must be a member of the sysadmin fixed server role.

See Also
sp_msx_enlist (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_msx_enlist (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds the current server to the list of available servers on the master server.
Cau t i on

The sp_msx_enlist stored procedure edits the registry. Manual editing of the registry is not recommended
because inappropriate or incorrect changes can cause serious configuration problems for your system. Therefore,
only experienced users should use the Registry Editor program to edit the registry. For more information, see the
Microsoft Windows documentation.
Transact-SQL Syntax Conventions

Syntax
sp_msx_enlist [@msx_server_name =] 'msx_server'
[, [@location =] 'location']

Arguments
[ @msx_server_name =] 'msx_server'
The name of the multiserver administration (master) server. msx_server is sysname, with no default.
[ @location =] 'location'
The location of the target server to add. location is nvarchar(100), with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Permissions
Permissions to execute this procedure default to members of the sysadmin fixed server role.

Examples
The following example enlists the current server into the AdventureWorks1 master server. The location for the
current server is Building 21, Room 309, Rack 5 .
USE msdb ;
GO

EXEC dbo.sp_msx_enlist N'AdventureWorks1',


N'Building 21, Room 309, Rack 5' ;
GO

See Also
sp_msx_defect (Transact-SQL)
System Stored Procedures (Transact-SQL)
xp_cmdshell (Transact-SQL)
sp_msx_get_account (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Lists information on the credential that the target server uses to log in to the master server.
Transact-SQL Syntax Conventions

Syntax
sp_msx_get_account

Return Code Values


0 (success) or 1 (failure)

Result Sets
Returns the following result set:

COLUMN NAME TYPE DESCRIPTION

msx_connection int Master server connection number.

msx_credential_id int ID of the credential used for this master


server connection.

msx_credential_name sysname Name of the credential used for this


master server connection.

msx_login_name nvarchar(4000) Domain name and user name of the


Windows user for the credential.

Remarks
Returns an empty result set if there is no credential specified for this target server. To set the credential, use
sp_msx_set_account.

Permissions
Requires membership in the sysadmin fixed server role.

Examples
The following example lists information for the credential that this target server uses to log in to the master server.
USE msdb ;
GO

EXECUTE dbo.sp_msx_get_account ;
GO

Here is a sample result set:


msx_connection msx_credential_id msx_credential_name msx_login_name

-------------- ----------------- -------------------- ------------------------------

1 65538 MsxAccount AdventureWorks2012\MsxAccount

See Also
SQL Server Agent Stored Procedures (Transact-SQL)
CREATE CREDENTIAL (Transact-SQL)
sp_msx_set_account (Transact-SQL)
sp_msx_set_account (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sets the SQL Server Agent master server account name and password on the target server.
Transact-SQL Syntax Conventions

Syntax
sp_msx_set_account [ @credential_name = ] 'credential_name' | [ @credential_id = ] credential_id

Arguments
[ @credential_name= ] 'credential_name'
The name of the credential to use to log in to the master server. The name provided must be the name of an
existing credential. Either credential_name or credential_id must be specified.
[ @credential_id= ] credential_id
The identifier for the credential to use to log in to the master server. The identifier must be an identifier for an
existing credential. Either credential_name or credential_id must be specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Remarks
SQL Server uses credentials to store the user name and password information that a target server uses to log in to
a master server. This procedure sets the credential that SQL Server Agent for this target server uses to log in to the
master server.
The credential specified must be an existing credential. For more information about creating a credential, see
CREATE CREDENTIAL (Transact-SQL).

Permissions
Execute permissions for sp_msx_set_account default to members of the sysadmin fixed server role.

Examples
The following example sets this server to use the credential MsxAccount to log in to the master server.
USE msdb ;
GO

EXECUTE dbo.sp_msx_set_account @credential_name = MsxAccount ;


GO

See Also
SQL Server Agent Stored Procedures (Transact-SQL)
CREATE CREDENTIAL (Transact-SQL)
sp_msx_get_account (Transact-SQL)
sp_notify_operator (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Sends an e-mail message to an operator using Database Mail.
Transact-SQL Syntax Conventions

Syntax
sp_notify_operator
[ @profile_name = ] 'profilename' ,
[ @id = ] id ,
[ @name = ] 'name' ,
[ @subject = ] 'subject' ,
[ @body = ] 'message' ,
[ @file_attachments = ] 'attachment'
[ @mail_database = ] 'mail_host_database'

Arguments
[ @profile_name= ] 'profilename'
The name of the Database Mail profile to use to send the message. profilename is nvarchar(128). If profilename is
not specified, the default Database Mail profile is used.
[ @id= ] id
The identifier for the operator to send the message to. id is int, with a default of NULL. One of id or name must be
specified.
[ @name= ] 'name'
The name of the operator to send the message to. name is nvarchar(128), with a default of NULL. One of id or
name must be specified.

NOTE: An e-mail address must be defined for the operator before they can receive messages.

[ @subject= ] 'subject'
The subject for the e-mail message. subject is nvarchar(256) with no default.
[ @body= ] 'message'
The body of the e-mail message. message is nvarchar(max) with no default.
[ @file_attachments= ] 'attachment'
The name of a file to attach to the e-mail message. attachment is nvarchar(512), with no default.
[ @mail_database= ] 'mail_host_database'
Specifies the name of the mail host database. mail_host_database is nvarchar(128). If no mail_host_database is
specified, the msdb database is used by default.

Return Code Values


0 (success) or 1 (failure)

Remarks
Sends the message specified to the e-mail address of the operator specified. If the operator has no e-mail address
configured, returns an error.
Database Mail and a mail host database must be configured before a notification can be sent to an operator.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.

Examples
The following example sends a notification e-mail to the operator François Ajenstat using the
AdventureWorks Administrator Database Mail profile. The subject of the e-mail is Test Notification . The e-mail
message contains the sentence, "This is a test of notification via e-mail."

USE msdb ;
GO

EXEC dbo.sp_notify_operator
@profile_name = N'AdventureWorks Administrator',
@name = N'François Ajenstat',
@subject = N'Test Notification',
@body = N'This is a test of notification via e-mail.' ;
GO

See also
SQL Server Agent Stored Procedures (Transact-SQL)
sp_add_operator (Transact-SQL)
sp_help_operator (Transact-SQL)
sp_delete_operator (Transact-SQL)
sp_post_msx_operation (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Inserts operations (rows) into the sysdownloadlist system table for target servers to download and execute.
Transact-SQL Syntax Conventions

Syntax
sp_post_msx_operation
[ @operation = ] 'operation'
[ , [ @object_type = ] 'object' ]
{ , [ @job_id = ] job_id }
[ , [ @specific_target_server = ] 'target_server' ]
[ , [ @value = ] value ]
[ , [ @schedule_uid = ] schedule_uid ]

Arguments
[ @operation =] 'operation'
The type of operation for the posted operation. operationis varchar(64), with no default. Valid operations depend
upon object_type.

OBJECT TYPE OPERATION

JOB INSERT

UPDATE

DELETE

START

STOP

SERVER RE-ENLIST

DEFECT

SYNC-TIME

SET-POLL

SCHEDULE INSERT

UPDATE

DELETE

[ @object_type =] 'object'
The type of object for which to post an operation. Valid types are JOB, SERVER, and SCHEDULE. object is
varchar(64), with a default of JOB.
[ @job_id =] job_id
The job identification number of the job to which the operation applies. job_id is uniqueidentifier, with no default.
0x00 indicates ALL jobs. If object is SERVER, then job_idis not required.
[ @specific_target_server =] 'target_server'
The name of the target server for which the specified operation applies. If job_id is specified, but target_server is
not specified, the operations are posted for all job servers of the job. target_server is nvarchar(30), with a default
of NULL.
[ @value =] value
The polling interval, in seconds. value is int, with a default of NULL. Specify this parameter only if operation is SET-
POLL.
[ @schedule_uid= ] schedule_uid
The unique identifier for the schedule to which the operation applies. schedule_uid is uniqueidentifier, with no
default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_post_msx_operation must be run from the msdb database.
sp_post_msx_operation can always be called safely because it first determines if the current server is a
multiserver Microsoft SQL Server Agent and, if so, whether objectis a multiserver job.
After an operation has been posted, it appears in the sysdownloadlist table. After a job has been created and
posted, subsequent changes to that job must also be communicated to the target servers (TSX). This is also
accomplished using the download list.
We highly recommend that the download list be managed by using the SQL Server Management Studio. For more
information, see View or Modify Jobs.

Permissions
To run this stored procedure, users must be granted the sysadmin fixed server role.

See Also
sp_add_jobserver (Transact-SQL)
sp_delete_job (Transact-SQL)
sp_delete_jobserver (Transact-SQL)
sp_delete_targetserver (Transact-SQL)
sp_resync_targetserver (Transact-SQL)
sp_start_job (Transact-SQL)
sp_stop_job (Transact-SQL)
sp_update_job (Transact-SQL)
sp_update_operator (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_purge_jobhistory (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the history records for a job.
Transact-SQL Syntax Conventions

Syntax
sp_purge_jobhistory
{ [ @job_name = ] 'job_name' |
| [ @job_id = ] job_id }
[ , [ @oldest_date = ] oldest_date ]

Arguments
[ @job_name= ] 'job_name'
The name of the job for which to delete the history records. job_nameis sysname, with a default of NULL. Either
job_id or job_name must be specified, but both cannot be specified.

NOTE
Members of the sysadmin fixed server role or members of the SQLAgentOperatorRole fixed database role can execute
sp_purge_jobhistory without specifying a job_name or job_id. When sysadmin users do not specify these arguments, the
job history for all local and multiserver jobs is deleted within the time specified by oldest_date. When
SQLAgentOperatorRole users do not specify these arguments, the job history for all local jobs is deleted within the time
specified by oldest_date.

[ @job_id= ] job_id
The job identification number of the job for the records to be deleted. job_idis uniqueidentifier, with a default of
NULL. Either job_id or job_name must be specified, but both cannot be specified. See the note in the description of
@job_name for information about how sysadmin or SQLAgentOperatorRole users can use this argument.
[ @oldest_date = ] oldest_date
The oldest record to retain in the history. oldest_date is datetime, with a default of NULL. When oldest_date is
specified, sp_purge_jobhistory only removes records that are older than the value specified.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
When sp_purge_jobhistory completes successfully, a message is returned.

Permissions
By default, only members of the sysadmin fixed server role or the SQLAgentOperatorRole fixed database role
can execute this stored procedure. Members of sysadmin can purge the job history for all local and multiserver
jobs. Members of SQLAgentOperatorRole can purge the job history for all local jobs only.
Other users, including members of SQLAgentUserRole and members of SQLAgentReaderRole, must explicitly
be granted the EXECUTE permission on sp_purge_jobhistory. After being granted EXECUTE permission on this
stored procedure, these users can only purge the history for jobs that they own.
The SQLAgentUserRole, SQLAgentReaderRole, and SQLAgentOperatorRole fixed database roles are in the
msdb database. For details about their permissions, see SQL Server Agent Fixed Database Roles.

Examples
A. Remove history for a specific job
The following example removes the history for a job named NightlyBackups .

USE msdb ;
GO

EXEC dbo.sp_purge_jobhistory
@job_name = N'NightlyBackups' ;
GO

B. Remove history for all jobs

NOTE
Only members of the sysadmin fixed server role and members of the SQLAgentOperatorRole can remove history for all
jobs. When sysadmin users execute this stored procedure with no parameters, the job history for all local and multiserver
jobs is purged. When SQLAgentOperatorRole users execute this stored procedure with no parameters, only the job history
for all local jobs is purged.

The following example executes the procedure with no parameters to remove all history records.

USE msdb ;
GO

EXEC dbo.sp_purge_jobhistory ;
GO

See Also
sp_help_job (Transact-SQL)
sp_help_jobhistory (Transact-SQL)
System Stored Procedures (Transact-SQL)
GRANT Object Permissions (Transact-SQL)
sp_remove_job_from_targets (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the specified job from the given target servers or target server groups.
Transact-SQL Syntax Conventions

Syntax
sp_remove_job_from_targets [ @job_id = ] job_id
| [ @job_name = ] 'job_name'
[ , [ @target_server_groups = ] 'target_server_groups' ]
[ , [ @target_servers = ] 'target_servers' ]

Arguments
[ @job_id =] job_id
The job identification number of the job from which to remove the specified target servers or target server groups.
Either job_id or job_name must be specified, but both cannot be specified. job_id is uniqueidentifier, with a
default of NULL.
[ @job_name =] 'job_name'
The name of the job from which to remove the specified target servers or target server groups. Either job_id or
job_name must be specified, but both cannot be specified. job_name is sysname, with a default of NULL.
[ @target_server_groups =] 'target_server_groups'
A comma-separated list of target server groups to be removed from the specified job. target_server_groups is
nvarchar(1024), with a default of NULL.
[ @target_servers =] 'target_servers'
A comma-separated list of target servers to be removed from the specified job. target_servers is nvarchar(1024),
with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Permissions
Permissions to execute this procedure default to members of the sysadmin fixed server role.

Examples
The following example removes the previously created Weekly Sales Backups job from the
Servers Processing Customer Orders target server group, and from the SEATTLE1 and SEATTLE2 servers.
USE msdb ;
GO

EXEC dbo.sp_remove_job_from_targets
@job_name = N'Weekly Sales Backups',
@target_server_groups = N'Servers Processing Customer Orders',
@target_servers = N'SEATTLE2,SEATTLE1' ;
GO

See Also
sp_apply_job_to_targets (Transact-SQL)
sp_delete_jobserver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_resync_targetserver (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Resynchronizes all multiserver jobs in the specified target server.
Transact-SQL Syntax Conventions

Syntax
sp_resync_targetserver
[ @server_name = ] 'server'

Arguments
[ @server_name =] 'server'
The name of the server to resynchronize. server is sysname, with no default. If ALL is specified, all target servers
are resynchronized.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Reports the result of sp_post_msx_operation actions.

Remarks
sp_resync_targetserver deletes the current set of instructions for the target server and posts a new set for the
target server to download. The new set consists of an instruction to delete all multiserver jobs, followed by an
insert for each job currently targeted at the server.

Permissions
Permissions to execute this procedure default to members of the sysadmin fixed server role.

Examples
The following example resynchronizes the SEATTLE1 target server.

USE msdb ;
GO

EXEC dbo.sp_resync_targetserver
N'SEATTLE1' ;
GO
See Also
sp_help_downloadlist (Transact-SQL)
sp_post_msx_operation (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_revoke_login_from_proxy (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes access to a proxy for a security principal.
Transact-SQL Syntax Conventions

Syntax
sp_revoke_login_from_proxy
[ @name = ] 'name' ,
[ @proxy_id = ] id ,
[ @proxy_name = ] 'proxy_name'

Arguments
[ @name= ] 'name'
The name of the SQL Server login, server role, or msdb database role to remove access for. name is
nvarchar(256) with no default.
[ @proxy_id= ] id
The id of the proxy to remove access for. Either id or proxy_name must be specified, but both cannot be specified.
The id is int, with a default of NULL.
[ @proxy_name= ] 'proxy_name'
The name of the proxy to remove access for. Either id or proxy_name must be specified, but both cannot be
specified. The proxy_name is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
Jobs that are owned by the login that references this proxy will fail to run.

Permissions
To execute this stored procedure, a user must be a member of the sysadmin fixed server role.

Examples
The following example revokes access for the login terrid to access the proxy Catalog application proxy .
USE msdb ;
GO

EXEC dbo.sp_revoke_login_from_proxy
@name = N'terrid',
@proxy_name = N'Catalog application proxy' ;
GO

See Also
SQL Server Agent Stored Procedures (Transact-SQL)
sp_grant_login_to_proxy (Transact-SQL)
sp_help_proxy (Transact-SQL)
sp_revoke_proxy_from_subsystem (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Revokes access to a subsystem from a proxy.
Transact-SQL Syntax Conventions

Syntax
sp_revoke_proxy_from_subsystem
[ @proxy_id = ] proxy_id,
[ @proxy_name = ] 'proxy_name',
[ @subsystem_id = ] subsystem_id,
[ @subsystem_name = ] 'subsystem_name'

Arguments
[ @proxy_id = ] id
The proxy identification number of the proxy to revoke access from. The proxy_id is int, with a default of NULL.
Either proxy_id or proxy_name must be specified, but both cannot be specified.
[ @proxy_name = ] 'proxy_name'
The name of the proxy to revoke access from. The proxy_name is sysname, with a default of NULL. Either proxy_id
or proxy_name must be specified, but both cannot be specified.
[ @subsystem_id = ] id
The id number of the subsystem to revoke access to. The subsystem_id is int, with a default of NULL. Either
subsystem_id or subsystem_name must be specified, but both cannot be specified. The following table lists the
values for each subsystem.

VALUE DESCRIPTION

2 ActiveX Script

** Important *\* The ActiveX Scripting subsystem will be


removed from SQL Server Agent in a future version of
Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that
currently use this feature.

3 Operating System (CmdExec)

4 Replication Snapshot Agent

5 Replication Log Reader Agent

6 Replication Distribution Agent


VALUE DESCRIPTION

7 Replication Merge Agent

8 Replication Queue Reader Agent

9 Analysis Services Command

10 Analysis Services Query

11 SSIS package execution

12 PowerShell Script

[ @subsystem_name= ] 'subsystem_name'
The name of the subsystem to revoke access to. The subsystem_name is sysname, with a default of NULL. Either
subsystem_id or subsystem_name must be specified, but both cannot be specified. The following table lists the
values for each subsystem.

VALUE DESCRIPTION

ActiveScripting ActiveX Script

CmdExec Operating System (CmdExec)

Snapshot Replication Snapshot Agent

LogReader Replication Log Reader Agent

Distribution Replication Distribution Agent

Merge Replication Merge Agent

QueueReader Replication Queue Reader Agent

ANALYSISQUERY Analysis Services Command

ANALYSISCOMMAND Analysis Services Query

Dts SSIS package execution

PowerShell PowerShell Script

Remarks
Revoking access to a subsystem does not change the permissions for the principal specified in the proxy.

NOTE
To determine which job steps reference a proxy, right-click the Proxies node under SQL Server Agent in Microsoft SQL
Server Management Studio, and then click Properties. In the Proxy Account Properties dialog box, select the References
page to view all job steps that reference this proxy.
Permissions
Only members of the sysadmin fixed server role can execute sp_revoke_proxy_from_subsystem.

Examples
The following example revokes access to the SSIS subsystem for the proxy Catalog application proxy .

USE msdb ;
GO

EXEC dbo.sp_revoke_proxy_from_subsystem
@proxy_name = 'Catalog application proxy',
@subsystem_name = N'Dts';

See Also
SQL Server Agent Stored Procedures (Transact-SQL)
Implement SQL Server Agent Security
sp_grant_proxy_to_subsystem (Transact-SQL)
sp_start_job (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Instructs SQL Server Agent to execute a job immediately.
Transact-SQL Syntax Conventions

Syntax
sp_start_job
{ [@job_name =] 'job_name'
| [@job_id =] job_id }
[ , [@error_flag =] error_flag]
[ , [@server_name =] 'server_name']
[ , [@step_name =] 'step_name']
[ , [@output_flag =] output_flag]

Arguments
[ @job_name= ] 'job_name'
The name of the job to start. Either job_id or job_name must be specified, but both cannot be specified. job_name
is sysname, with a default of NULL.
[ @job_id= ] job_id
The identification number of the job to start. Either job_id or job_name must be specified, but both cannot be
specified. job_id is uniqueidentifier, with a default of NULL.
[ @error_flag= ] error_flag
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @server_name= ] 'server_name'
The target server on which to start the job. server_name is nvarchar(128), with a default of NULL. server_name
must be one of the target servers to which the job is currently targeted.
[ @step_name= ] 'step_name'
The name of the step at which to begin execution of the job. Applies only to local jobs. step_name is sysname, with
a default of NULL
[ @output_flag= ] output_flag
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None
Remarks
This stored procedure is in the msdb database.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of SQLAgentUserRole and SQLAgentReaderRole can only start jobs that they own. Members
of SQLAgentOperatorRole can start all local jobs including those that are owned by other users. Members
of sysadmin can start all local and multiserver jobs.

Examples
The following example starts a job named Weekly Sales Data Backup .

USE msdb ;
GO

EXEC dbo.sp_start_job N'Weekly Sales Data Backup' ;


GO

See Also
sp_delete_job (Transact-SQL)
sp_help_job (Transact-SQL)
sp_stop_job (Transact-SQL)
sp_update_job (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_stop_job (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Instructs SQL Server Agent to stop the execution of a job.
Transact-SQL Syntax Conventions

Syntax
sp_stop_job
[@job_name =] 'job_name'
| [@job_id =] job_id
| [@originating_server =] 'master_server'
| [@server_name =] 'target_server'

Arguments
[ @job_name =] 'job_name'
The name of the job to stop. job_name is sysname, with a default of NULL.
[ @job_id =] job_id
The identification number of the job to stop. job_id is uniqueidentifier, with a default of NULL.
[ @originating_server =] 'master_server'
The name of the master server. If specified, all multiserver jobs are stopped. master_server is nvarchar(128), with
a default of NULL. Specify this parameter only when calling sp_stop_job at a target server.

NOTE
Only one of the first three parameters can be specified.

[ @server_name =] 'target_server'
The name of the specific target server on which to stop a multiserver job. target_server is nvarchar(128), with a
default of NULL. Specify this parameter only when calling sp_stop_job at a master server for a multiserver job.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_stop_job sends a stop signal to the database. Some processes can be stopped immediately and some must
reach a stable point (or an entry point to the code path) before they can stop. Some long-running Transact-SQL
statements such as BACKUP, RESTORE, and some DBCC commands can take a long time to finish. When these are
running, it may take a while before the job is canceled. Stopping a job causes a "Job Canceled" entry to be
recorded in the job history.
If a job is currently executing a step of type CmdExec or PowerShell, the process being run (for example,
MyProgram.exe) is forced to end prematurely. Premature ending can result in unpredictable behavior such as files
in use by the process being held open. Consequently, sp_stop_job should be used only in extreme circumstances
if the job contains steps of type CmdExec or PowerShell.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Members of SQLAgentUserRole and SQLAgentReaderRole can only stop jobs that they own. Members
of SQLAgentOperatorRole can stop all local jobs including those that are owned by other users. Members
of sysadmin can stop all local and multiserver jobs.

Examples
The following example stops a job named Weekly Sales Data Backup .

USE msdb ;
GO

EXEC dbo.sp_stop_job
N'Weekly Sales Data Backup' ;
GO

See Also
sp_delete_job (Transact-SQL)
sp_help_job (Transact-SQL)
sp_start_job (Transact-SQL)
sp_update_job (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_update_alert (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates the settings of an existing alert.
Transact-SQL Syntax Conventions

Syntax
sp_update_alert
[ @name =] 'name'
[ , [ @new_name =] 'new_name']
[ , [ @enabled =] enabled]
[ , [ @message_id =] message_id]
[ , [ @severity =] severity]
[ , [ @delay_between_responses =] delay_between_responses]
[ , [ @notification_message =] 'notification_message']
[ , [ @include_event_description_in =] include_event_description_in]
[ , [ @database_name =] 'database']
[ , [ @event_description_keyword =] 'event_description_keyword']
[ , [ @job_id =] job_id | [@job_name =] 'job_name']
[ , [ @occurrence_count = ] occurrence_count]
[ , [ @count_reset_date =] count_reset_date]
[ , [ @count_reset_time =] count_reset_time]
[ , [ @last_occurrence_date =] last_occurrence_date]
[ , [ @last_occurrence_time =] last_occurrence_time]
[ , [ @last_response_date =] last_response_date]
[ , [ @last_response_time =] last_response _time]
[ , [ @raise_snmp_trap =] raise_snmp_trap]
[ , [ @performance_condition =] 'performance_condition' ]
[ , [ @category_name =] 'category']
[ , [ @wmi_namespace = ] 'wmi_namespace' ]
[ , [ @wmi_query = ] 'wmi_query' ]

Arguments
[ @name =] 'name'
The name of the alert that is to be updated. name is sysname, with no default.
[ @new_name =] 'new_name'
A new name for the alert. The name must be unique. new_name is sysname, with a default of NULL.
[ @enabled =] enabled
Specifies whether the alert is enabled (1) or not enabled (0). enabled is tinyint, with a default of NULL. An alert
must be enabled to fire.
[ @message_id =] message_id
A new message or error number for the alert definition. Typically, message_id corresponds to an error number in
the sysmessages table. message_id is int, with a default of NULL. A message ID can be used only if the severity
level setting for the alert is 0.
[ @severity =] severity
A new severity level (from 1 through 25) for the alert definition. Any Microsoft SQL Server message sent to the
Windows application log with the specified severity will activate the alert. severity is int, with a default of NULL. A
severity level can be used only if the message ID setting for the alert is 0.
[ @delay_between_responses =] delay_between_responses
The new waiting period, in seconds, between responses to the alert. delay_between_responses is int, with a default
of NULL.
[ @notification_message =] 'notification_message'
The revised text of an additional message sent to the operator as part of the e-mail, net send, or pager
notification. notification_message is nvarchar(512), with a default of NULL.
[ @include_event_description_in =] include_event_description_in
Specifies whether the description of the SQL Server error from the Windows application log should be included in
the notification message. include_event_description_in is tinyint, with a default of NULL, and can be one or more
of these values.

VALUE DESCRIPTION

0 None

1 E-mail

2 Pager

4 net send

7 All

[ @database_name =] 'database'
The name of the database in which the error must occur for the alert to fire. database is sysname. Names that are
enclosed in brackets ([ ]) are not allowed. The default value is NULL.
[ @event_description_keyword =] 'event_description_keyword'
A sequence of characters that must be found in the description of the error in the error message log. Transact-SQL
LIKE expression pattern-matching characters can be used. event_description_keyword is nvarchar(100), with a
default of NULL. This parameter is useful for filtering object names (for example, %customer_table%).
[ @job_id =] job_id
The job identification number. job_id is uniqueidentifier, with a default of NULL. If job_id is specified, job_name
must be omitted.
[ @job_name =] 'job_name'
The name of the job that executes in response to this alert. job_name is sysname, with a default of NULL. If
job_name is specified, job_id must be omitted.
[ @occurrence_count = ] occurrence_count
Resets the number of times the alert has occurred. occurrence_count is int, with a default of NULL, and can be set
only to 0.
[ @count_reset_date =] count_reset_date
Resets the date the occurrence count was last reset. count_reset_date is int, with a default of NULL.
[ @count_reset_time =] count_reset_time
Resets the time the occurrence count was last reset. count_reset_time is int, with a default of NULL.
[ @last_occurrence_date =] last_occurrence_date
Resets the date the alert last occurred. last_occurrence_date is int, with a default of NULL, and can be set only to 0.
[ @last_occurrence_time =] last_occurrence_time
Resets the time the alert last occurred. last_occurrence_time is int, with a default of NULL, and can be set only to 0.
[ @last_response_date =] last_response_date
Resets the date the alert was last responded to by the SQLServerAgent service. last_response_date is int, with a
default of NULL, and can be set only to 0.
[ @last_response_time =] last_response_time
Resets the time the alert was last responded to by the SQLServerAgent service. last_response_time is int, with a
default of NULL, and can be set only to 0.
[ @raise_snmp_trap =] raise_snmp_trap
Reserved.
[ @performance_condition =] 'performance_condition'
A value expressed in the format 'itemcomparatorvalue'. performance_condition is nvarchar(512), with a default
of NULL, and consists of these elements.

FORMAT ELEMENT DESCRIPTION

Item A performance object, performance counter, or named


instance of the counter

Comparator One of these operators: >, <, =

Value Numeric value of the counter

[ @category_name =] 'category'
The name of the alert category. category is sysname with a default of NULL.
[ @wmi_namespace= ] 'wmi_namespace'
The WMI namespace to query for events. wmi_namespace is sysname, with a default of NULL.
[ @wmi_query= ] 'wmi_query'
The query that specifies the WMI event for the alert. wmi_query is nvarchar(512), with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
Only sysmessages written to the Microsoft Windows application log can fire an alert.
sp_update_alert changes only those alert settings for which parameter values are supplied. If a parameter is
omitted, the current setting is retained.

Permissions
To run this stored procedure, users must be a member of the sysadmin fixed server role.

Examples
The following example changes the enabled setting of Test Alert to 0 .
USE msdb ;
GO

EXEC dbo.sp_update_alert
@name = N'Test Alert',
@enabled = 0 ;
GO

See Also
sp_add_alert (Transact-SQL)
sp_help_alert (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_update_category (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the name of a category.
Transact-SQL Syntax Conventions

Syntax
sp_update_category
[@class =] 'class' ,
[@name =] 'old_name' ,
[@new_name =] 'new_name'

Arguments
[ @class =] 'class'
The class of the category to update. classis varchar(8), with no default, and can be one of these values.

VALUE DESCRIPTION

ALERT Updates an alert category.

JOB Updates a job category.

OPERATOR Updates an operator category.

[ @name =] 'old_name'
The current name of the category. old_nameis sysname, with no default.
[ @new_name =] 'new_name'
The new name for the category. new_nameis sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_update_category must be run from the msdb database.

Permissions
To run this stored procedure, users must be granted the sysadmin fixed server role.

Examples
The following example renames a job category from AdminJobs to Administrative Jobs .

USE msdb ;
GO

EXEC dbo.sp_update_category
@class = N'JOB',
@name = N'AdminJobs',
@new_name = N'Administrative Jobs' ;
GO

See Also
sp_add_category (Transact-SQL)
sp_delete_category (Transact-SQL)
sp_help_category (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_update_job (Transact-SQL)
11/17/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the attributes of a job.
Transact-SQL Syntax Conventions

Syntax
sp_update_job [ @job_id =] job_id | [@job_name =] 'job_name'
[, [@new_name =] 'new_name' ]
[, [@enabled =] enabled ]
[, [@description =] 'description' ]
[, [@start_step_id =] step_id ]
[, [@category_name =] 'category' ]
[, [@owner_login_name =] 'login' ]
[, [@notify_level_eventlog =] eventlog_level ]
[, [@notify_level_email =] email_level ]
[, [@notify_level_netsend =] netsend_level ]
[, [@notify_level_page =] page_level ]
[, [@notify_email_operator_name =] 'operator_name' ]
[, [@notify_netsend_operator_name =] 'netsend_operator' ]
[, [@notify_page_operator_name =] 'page_operator' ]
[, [@delete_level =] delete_level ]
[, [@automatic_post =] automatic_post ]

Arguments
[ @job_id =] job_id
The identification number of the job to be updated. job_idis uniqueidentifier.
[ @job_name =] 'job_name'
The name of the job. job_nameis nvarchar(128).

NOTE: Either job_id or job_name must be specified but both cannot be specified.

[ @new_name =] 'new_name'
The new name for the job. new_nameis nvarchar(128).
[ @enabled =] enabled
Specifies whether the job is enabled (1) or not enabled (0). enabledis tinyint.
[ @description =] 'description'
The description of the job. description is nvarchar(512).
[ @start_step_id =] step_id
The identification number of the first step to execute for the job. step_idis int.
[ @category_name =] 'category'
The category of the job. categoryis nvarchar(128).
[ @owner_login_name =] 'login'
The name of the login that owns the job. loginis nvarchar(128) Only members of the sysadmin fixed server role
can change job ownership.
[ @notify_level_eventlog =] eventlog_level
Specifies when to place an entry in the Microsoft Windows application log for this job. eventlog_levelis int, and
can be one of these values.

VALUE DESCRIPTION (ACTION)

0 Never

1 On success

2 On failure

3 Always

[ @notify_level_email =] email_level
Specifies when to send an e-mail upon the completion of this job. email_levelis int. email_leveluses the same
values as eventlog_level.
[ @notify_level_netsend =] netsend_level
Specifies when to send a network message upon the completion of this job. netsend_levelis int. netsend_leveluses
the same values as eventlog_level.
[ @notify_level_page =] page_level
Specifies when to send a page upon the completion of this job. page_levelis int. page_leveluses the same values
as eventlog_level.
[ @notify_email_operator_name =] 'operator_name'
The name of the operator to whom the e-mail is sent when email_level is reached. email_name is nvarchar(128).
[ @notify_netsend_operator_name =] 'netsend_operator'
The name of the operator to whom the network message is sent. netsend_operator is nvarchar(128).
[ @notify_page_operator_name =] 'page_operator'
The name of the operator to whom a page is sent. page_operator is nvarchar(128).
[ @delete_level =] delete_level
Specifies when to delete the job. delete_valueis int. delete_leveluses the same values as eventlog_level.
[ @automatic_post =] automatic_post
Reserved.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_update_job must be run from the msdb database.
sp_update_job changes only those settings for which parameter values are supplied. If a parameter is omitted,
the current setting is retained.
Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Only members of sysadmin can use this stored procedure to edit the attributes of jobs that are owned by
other users.

Examples
The following example changes the name, description, and enabled status of the job NightlyBackups .

USE msdb ;
GO

EXEC dbo.sp_update_job
@job_name = N'NightlyBackups',
@new_name = N'NightlyBackups -- Disabled',
@description = N'Nightly backups disabled during server migration.',
@enabled = 0 ;
GO

See Also
sp_add_job (Transact-SQL)
sp_delete_job (Transact-SQL)
sp_help_job (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_update_jobschedule (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the schedule settings for the specified job.
sp_update_jobschedule is provided for backward compatibility only.

IMPORTANT
For more information about syntax used in earlier versions of Microsoft SQL Server, see the Transact-SQL Referencefor
Microsoft SQL Server 2000.

Remarks
Job schedules can now be managed independently of jobs. To update a schedule, use sp_update_schedule.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Only members of sysadmin can use this stored procedure to update job schedules that are owned by other
users.

See Also
SQL Server Agent Stored Procedures (Transact-SQL)
sp_update_schedule (Transact-SQL)
sp_update_jobstep (Transact-SQL)
11/27/2017 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the setting for a step in a job that is used to perform automated activities.
Transact-SQL Syntax Conventions

Syntax
sp_update_jobstep
{ [@job_id =] job_id
| [@job_name =] 'job_name' } ,
[@step_id =] step_id
[ , [@step_name =] 'step_name' ]
[ , [@subsystem =] 'subsystem' ]
[ , [@command =] 'command' ]
[ , [@additional_parameters =] 'parameters' ]
[ , [@cmdexec_success_code =] success_code ]
[ , [@on_success_action =] success_action ]
[ , [@on_success_step_id =] success_step_id ]
[ , [@on_fail_action =] fail_action ]
[ , [@on_fail_step_id =] fail_step_id ]
[ , [@server =] 'server' ]
[ , [@database_name =] 'database' ]
[ , [@database_user_name =] 'user' ]
[ , [@retry_attempts =] retry_attempts ]
[ , [@retry_interval =] retry_interval ]
[ , [@os_run_priority =] run_priority ]
[ , [@output_file_name =] 'file_name' ]
[ , [@flags =] flags ]
[ , { [ @proxy_id = ] proxy_id
| [ @proxy_name = ] 'proxy_name' }

Arguments
[ @job_id =] job_id
The identification number of the job to which the step belongs. job_idis uniqueidentifier, with a default of NULL.
Either job_id or job_name must be specified but both cannot be specified.
[ @job_name =] 'job_name'
The name of the job to which the step belongs. job_nameis sysname, with a default of NULL. Either job_id or
job_name must be specified but both cannot be specified.
[ @step_id =] step_id
The identification number for the job step to be modified. This number cannot be changed. step_idis int, with no
default.
[ @step_name =] 'step_name'
Is a new name for the step. step_nameis sysname, with a default of NULL.
[ @subsystem =] 'subsystem'
The subsystem used by Microsoft SQL Server Agent to execute command. subsystem is nvarchar(40), with a
default of NULL.
[ @command =] 'command'
The command(s) to be executed through subsystem. command is nvarchar(max), with a default of NULL.
[ @additional_parameters =] 'parameters'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @cmdexec_success_code =] success_code
The value returned by a CmdExec subsystem command to indicate that command executed successfully.
success_code is int, with a default of NULL.
[ @on_success_action =] success_action
The action to perform if the step succeeds.success_action is tinyint, with a default of NULL, and can be one of
these values.

VALUE DESCRIPTION (ACTION)

1 Quit with success.

2 Quit with failure.

3 Go to next step.

4 Go to step success_step_id.

[ @on_success_step_id =] success_step_id
The identification number of the step in this job to execute if step succeeds and success_action is 4. success_step_id
is int, with a default of NULL.
[ @on_fail_action =] fail_action
The action to perform if the step fails. fail_action is tinyint, with a default of NULL and can have one of these
values.

VALUE DESCRIPTION (ACTION)

1 Quit with success.

2 Quit with failure.

3 Go to next step.

4 Go to step fail_step_id.

[ @on_fail_step_id =] fail_step_id
The identification number of the step in this job to execute if the step fails and fail_action is 4. fail_step_id is int,
with a default of NULL.
[ @server =] 'server'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed. server is
nvarchar(128), with a default of NULL.
[ @database_name =] 'database'
The name of the database in which to execute a Transact-SQL step. databaseis sysname. Names that are enclosed
in brackets ([ ]) are not allowed. The default value is NULL.
[ @database_user_name =] 'user'
The name of the user account to use when executing a Transact-SQL step. useris sysname, with a default of NULL.
[ @retry_attempts =] retry_attempts
The number of retry attempts to use if this step fails. retry_attemptsis int, with a default of NULL.
[ @retry_interval =] retry_interval
The amount of time in minutes between retry attempts. retry_interval is int, with a default of NULL.
[ @os_run_priority =] run_priority
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @output_file_name =] 'file_name'
The name of the file in which the output of this step is saved. file_name is nvarchar(200), with a default of NULL.
This parameter is only valid with commands running in Transact-SQL or CmdExec subsystems.
To set output_file_name back to NULL, you must set output_file_name to an empty string (' ') or to a string of
blank characters, but you cannot use the CHAR(32) function. For example, set this argument to an empty string as
follows:
@output_file_name = ' '
[ @flags =] flags
An option that controls behavior. flags is int, and can be one of these values.

VALUE DESCRIPTION

0 (default) Overwrite output file.

2 Append to output file

4 Write Transact-SQL job step output to step history

8 Write log to table (overwrite existing history)

16 Write log to table (append to existing history)

[ @proxy_id= ] proxy_id
The ID number of the proxy that the job step runs as. proxy_id is type int, with a default of NULL. If no proxy_id is
specified, no proxy_name is specified, and no user_name is specified, the job step runs as the service account for
SQL Server Agent.
[ @proxy_name= ] 'proxy_name'
The name of the proxy that the job step runs as. proxy_name is type sysname, with a default of NULL. If no
proxy_id is specified, no proxy_name is specified, and no user_name is specified, the job step runs as the service
account for SQL Server Agent.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_update_jobstep must be run from the msdb database.
Updating a job step increments the job version number.
Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Only members of sysadmin can update a job step owned by another user.
If the job step requires access to a proxy, the creator of the job step must have access to the proxy for the
job step. All subsystems, except Transact-SQL, require a proxy account. Members of sysadmin have access
to all proxies, and can use the SQL Server Agent service account for the proxy.

Examples
The following example changes the number of retry attempts for the first step of the Weekly Sales Data Backup
job. After running this example, the number of retry attempts is 10 .

USE msdb ;
GO

EXEC dbo.sp_update_jobstep
@job_name = N'Weekly Sales Data Backup',
@step_id = 1,
@retry_attempts = 10 ;
GO

See Also
View or Modify Jobs
sp_delete_jobstep (Transact-SQL)
sp_help_jobstep (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_update_notification (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates the notification method of an alert notification.
Transact-SQL Syntax Conventions

Syntax
sp_update_notification
[@alert_name =] 'alert' ,
[@operator_name =] 'operator' ,
[@notification_method =] notification

Arguments
[ @alert_name =] 'alert'
The name of the alert associated with this notification. alert is sysname, with no default.
[ @operator_name =] 'operator'
The operator who will be notified when the alert occurs. operator is sysname, with no default.
[ @notification_method =] notification
The method by which the operator is notified. notificationis tinyint, with no default, and can be one or more of
these values.

VALUE DESCRIPTION

1 E-mail

2 Pager

4 net send

7 All methods

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_update_notification must be run from the msdb database.
You can update a notification for an operator who does not have the necessary address information using the
specified notification_method. If a failure occurs when sending an e-mail message or pager notification, the failure
is reported in the Microsoft SQL Server Agent error log.
Permissions
To run this stored procedure, users must be granted the sysadmin fixed server role.

Examples
The following example modifies the notification method for notifications sent to François Ajenstat for the alert
Test Alert .

USE msdb ;
GO

EXEC dbo.sp_update_notification
@alert_name = N'Test Alert',
@operator_name = N'François Ajenstat',
@notification_method = 7;
GO

See Also
sp_add_notification (Transact-SQL)
sp_delete_notification (Transact-SQL)
sp_help_notification (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_update_operator (Transact-SQL)
11/17/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates information about an operator (notification recipient) for use with alerts and jobs.
Transact-SQL Syntax Conventions

Syntax
sp_update_operator
[ @name =] 'name'
[ , [ @new_name = ] 'new_name' ]
[ , [ @enabled = ] enabled]
[ , [ @email_address = ] 'email_address' ]
[ , [ @pager_address = ] 'pager_number']
[ , [ @weekday_pager_start_time = ] weekday_pager_start_time ]
[ , [ @weekday_pager_end_time = ] weekday_pager_end_time ]
[ , [ @saturday_pager_start_time = ] saturday_pager_start_time ]
[ , [ @saturday_pager_end_time = ] saturday_pager_end_time ]
[ , [ @sunday_pager_start_time = ] sunday_pager_start_time ]
[ , [ @sunday_pager_end_time = ] sunday_pager_end_time ]
[ , [ @pager_days = ] pager_days ]
[ , [ @netsend_address = ] 'netsend_address' ]
[ , [ @category_name = ] 'category' ]

Arguments
[ @name=] 'name'
The name of the operator to modify. name is sysname, with no default.
[ @new_name=] 'new_name'
The new name for the operator. This name must be unique. new_name is sysname, with a default of NULL.
[ @enabled=] enabled
A number indicating the operator's current status (1 if currently enabled, 0 if not). enabled is tinyint, with a
default of NULL. If not enabled, an operator will not receive alert notifications.
[ @email_address=] 'email_address'
The e-mail address of the operator. This string is passed directly to the e-mail system. email_address is
nvarchar(100), with a default of NULL.
[ @pager_address=] 'pager_number'
The pager address of the operator. This string is passed directly to the e-mail system. pager_number is
nvarchar(100), with a default of NULL.
[ @weekday_pager_start_time=] weekday_pager_start_time
Specifies the time after which a pager notification can be sent to this operator, from Monday through Friday.
weekday_pager_start_timeis int, with a default of NULL, and must be entered in the form HHMMSS for use with a
24-hour clock.
[ @weekday_pager_end_time=] weekday_pager_end_time
Specifies the time after which a pager notification cannot be sent to the specified operator, from Monday through
Friday. weekday_pager_end_timeis int, with a default of NULL, and must be entered in the form HHMMSS for use
with a 24-hour clock.
[ @saturday_pager_start_time=] saturday_pager_start_time
Specifies the time after which a pager notification can be sent to the specified operator on Saturdays.
saturday_pager_start_timeis int, with a default of NULL, and must be entered in the form HHMMSS for use with a
24-hour clock.
[ @saturday_pager_end_time=] saturday_pager_end_time
Specifies the time after which a pager notification cannot be sent to the specified operator on Saturdays.
saturday_pager_end_timeis int, with a default of NULL, and must be entered in the form HHMMSS for use with a
24-hour clock.
[ @sunday_pager_start_time=] sunday_pager_start_time
Specifies the time after which a pager notification can be sent to the specified operator on Sundays.
sunday_pager_start_timeis int, with a default of NULL, and must be entered in the form HHMMSS for use with a
24-hour clock.
[ @sunday_pager_end_time=] sunday_pager_end_time
Specifies the time after which a pager notification cannot be sent to the specified operator on Sundays.
sunday_pager_end_timeis int, with a default of NULL, and must be entered in the form HHMMSS for use with a
24-hour clock.
[ @pager_days=] pager_days
Specifies the days that the operator is available to receive pages (subject to the specified start/end times).
pager_daysis tinyint, with a default of NULL, and must be a value from 0 through 127. pager_days is calculated
by adding the individual values for the required days. For example, from Monday through Friday is
2+4+8+16+32 = 64.

VALUE DESCRIPTION

1 Sunday

2 Monday

4 Tuesday

8 Wednesday

16 Thursday

32 Friday

64 Saturday

[ @netsend_address=] 'netsend_address'
The network address of the operator to whom the network message is sent. netsend_addressis nvarchar(100),
with a default of NULL.
[ @category_name=] 'category'
The name of the category for this alert. category is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_update_operator must be run from the msdb database.

Permissions
Permissions to execute this procedure default to members of the sysadmin fixed server role.

Examples
The following example updates the operator status to enabled, and sets the days (from Monday through Friday,
from 8 A.M. through 5 P.M.) when the operator can be paged.

USE msdb ;
GO

EXEC dbo.sp_update_operator
@name = N'François Ajenstat',
@enabled = 1,
@email_address = N'françoisa',
@pager_address = N'5551290AW@pager.Adventure-Works.com',
@weekday_pager_start_time = 080000,
@weekday_pager_end_time = 170000,
@pager_days = 64 ;
GO

See Also
sp_add_operator (Transact-SQL)
sp_delete_operator (Transact-SQL)
sp_help_operator (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_update_proxy (Transact-SQL)
11/27/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the properties of an existing proxy.
Transact-SQL Syntax Conventions

Syntax
sp_update_proxy
[ @proxy_id = ] id,
[ @proxy_name = ] 'proxy_name',
[ @credential_name = ] 'credential_name' ,
[ @credential_id = ] credential_id ,
[ @new_name = ] 'new_name' ,
[ @enabled = ] is_enabled ,
[ @description = ] 'description'

Arguments
[ @proxy_id= ] id
The proxy identification number of the proxy to change. The proxy_id is int, with a default of NULL.
[ @proxy_name= ] 'proxy_name'
The name of the proxy to change. The proxy_name is sysname, with a default of NULL.
[ @credential_name = ] 'credential_name'
The name of the new credential for the proxy. The credential_name is sysname, with a default of NULL. Either
credential_name or credential_id may be specified.
[ @credential_id = ] credential_id
The identification number of the new credential for the proxy. The credential_id is int, with a default of NULL.
Either credential_name or credential_id may be specified.
[ @new_name= ] 'new_name'
The new name of the proxy. The new_name is sysname, with a default of NULL. When provided, the procedure
changes the name of the proxy to new_name. When this argument is NULL, the name of the proxy remains
unchanged.
[ @enabled = ] is_enabled
Is whether the proxy is enabled. The is_enabled flag is tinyint, with a default of NULL. When is_enabled is 0, the
proxy is not enabled, and cannot be used by a job step. When this argument is NULL, the status of the proxy
remains unchanged.
[ @description= ] 'description'
The new description of the proxy. The description is nvarchar(512), with a default of NULL. When this argument is
NULL, the description of the proxy remains unchanged.

Return Code Values


0 (success) or 1 (failure)

Remarks
Either @proxy_name or @proxy_id must be specified. If both arguments are specified, the arguments must both
refer to the same proxy or the stored procedure fails.
Either @credential_name or @credential_id must be specified to change the credential for the proxy. If both
arguments are specified, the arguments must refer to the same credential or the stored procedure fails.
This procedure changes the proxy, but does not change access to the proxy. To change access to a proxy, use
sp_grant_login_to_proxy and sp_revoke_login_from_proxy.

Permissions
Only members of the sysadmin fixed security role can execute this procedure.

Examples
The following example sets the enabled value for the proxy Catalog application proxy to 0 .

USE msdb ;
GO

EXEC dbo.sp_update_proxy
@proxy_name = 'Catalog application proxy',
@enabled = 0;
GO

See Also
SQL Server Agent Stored Procedures (Transact-SQL)
Implement SQL Server Agent Security
sp_add_proxy (Transact-SQL)
sp_delete_proxy (Transact-SQL)
sp_grant_login_to_proxy (Transact-SQL)
sp_revoke_login_from_proxy (Transact-SQL)
sp_update_schedule (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the settings for a SQL Server Agent schedule.
Transact-SQL Syntax Conventions

Syntax
sp_update_schedule
{ [ @schedule_id = ] schedule_id
| [ @name = ] 'schedule_name' }
[ , [ @new_name = ] new_name ]
[ , [ @enabled = ] enabled ]
[ , [ @freq_type = ] freq_type ]
[ , [ @freq_interval = ] freq_interval ]
[ , [ @freq_subday_type = ] freq_subday_type ]
[ , [ @freq_subday_interval = ] freq_subday_interval ]
[ , [ @freq_relative_interval = ] freq_relative_interval ]
[ , [ @freq_recurrence_factor = ] freq_recurrence_factor ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @active_start_time = ] active_start_time ]
[ , [ @active_end_time = ] active_end_time ]
[ , [ @owner_login_name = ] 'owner_login_name' ]
[ , [ @automatic_post =] automatic_post ]

Arguments
[ @schedule_id = ] schedule_id
The identifier of the schedule to modify. schedule_id is int, with no default. Either schedule_id or schedule_name
must be specified.
[ @name = ] 'schedule_name'
The name of the schedule to modify. schedule_nameis sysname, with no default. Either schedule_id or
schedule_name must be specified.
[ @new_name= ] new_name
The new name for the schedule. new_name is sysname, with a default of NULL. When new_name is NULL, the
name of the schedule is unchanged.
[ @enabled = ] enabled
Indicates the current status of the schedule. enabledis tinyint, with a default of 1 (enabled). If 0, the schedule is
not enabled. When the schedule is not enabled, no jobs will run on this schedule.
[ @freq_type = ] freq_type
A value indicating when a job is to be executed. freq_typeis int, with a default of 0, and can be one of these values.
VALUE DESCRIPTION

1 Once

4 Daily

8 Weekly

16 Monthly

32 Monthly, relative to freq interval

64 Run when SQLServerAgent service starts

128 Run when the computer is idle

[ @freq_interval = ] freq_interval
The days that a job is executed. freq_interval is int, with a default of 0, and depends on the value of freq_type.

VALUE OF FREQ_TYPE EFFECT ON FREQ_INTERVAL

1 (once) freq_interval is unused.

4 (daily) Every freq_interval days.

8 (weekly) freq_interval is one or more of the following (combined with


an OR logical operator):

1 = Sunday

2 = Monday

4 = Tuesday

8 = Wednesday

16 = Thursday

32 = Friday

64 = Saturday

16 (monthly) On the freq_interval day of the month.


VALUE OF FREQ_TYPE EFFECT ON FREQ_INTERVAL

32 (monthly relative) freq_interval is one of the following:

1 = Sunday

2 = Monday

3 = Tuesday

4 = Wednesday

5 = Thursday

6 = Friday

7 = Saturday

8 = Day

9 = Weekday

10 = Weekend day

64 (when SQLServerAgent service starts) freq_interval is unused.

128 freq_interval is unused.

[ @freq_subday_type = ] freq_subday_type
Specifies the units for freq_subday_interval. freq_subday_typeis int, with a default of 0, and can be one of these
values.

VALUE DESCRIPTION (UNIT)

0x1 At the specified time

0x2 Seconds

0x4 Minutes

0x8 Hours

[ @freq_subday_interval = ] freq_subday_interval
The number of freq_subday_type periods to occur between each execution of a job. freq_subday_intervalis int,
with a default of 0.
[ @freq_relative_interval = ] freq_relative_interval
A job's occurrence of freq_interval in each month, if freq_interval is 32 (monthly relative). freq_relative_intervalis
int, with a default of 0, and can be one of these values.

VALUE DESCRIPTION (UNIT)

1 First

2 Second
VALUE DESCRIPTION (UNIT)

4 Third

8 Fourth

16 Last

[ @freq_recurrence_factor = ] freq_recurrence_factor
The number of weeks or months between the scheduled execution of a job. freq_recurrence_factor is used only if
freq_type is 8, 16, or 32. freq_recurrence_factoris int, with a default of 0.
[ @active_start_date = ] active_start_date
The date on which execution of a job can begin. active_start_dateis int, with a default of NULL, which indicates
today's date. The date is formatted as YYYYMMDD. If active_start_date is not NULL, the date must be greater than
or equal to 19900101.
After the schedule is created, review the start date and confirm that it is the correct date. For more information,
see the section "Scheduling Start Date" in Create and Attach Schedules to Jobs.
[ @active_end_date = ] active_end_date
The date on which execution of a job can stop. active_end_dateis int, with a default of 99991231, which indicates
December 31, 9999. Formatted as YYYYMMDD.
[ @active_start_time = ] active_start_time
The time on any day between active_start_date and active_end_date to begin execution of a job.
active_start_timeis int, with a default of 000000, which indicates 12:00:00 A.M. on a 24-hour clock, and must be
entered using the form HHMMSS.
[ @active_end_time = ] active_end_time
The time on any day between active_start_date and active_end_date to end execution of a job. active_end_timeis
int, with a default of 235959, which indicates 11:59:59 P.M. on a 24-hour clock, and must be entered using the
form HHMMSS.
[ @owner_login_name= ] 'owner_login_name']
The name of the server principal that owns the schedule. owner_login_name is sysname, with a default of NULL,
which indicates that the schedule is owned by the creator.
[ @automatic_post =] automatic_post
Reserved.

Return Code Values


0 (success) or 1 (failure)

Remarks
All jobs that use the schedule immediately use the new settings. However, changing a schedule does not stop jobs
that are currently running.

Permissions
By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be
granted one of the following SQL Server Agent fixed database roles in the msdb database:
SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.
Only members of sysadmin can modify a schedule owned by another user.

Examples
The following example changes the enabled status of the NightlyJobs schedule to 0 and sets the owner to
terrid .

USE msdb ;
GO

EXEC dbo.sp_update_schedule
@name = 'NightlyJobs',
@enabled = 0,
@owner_login_name = 'terrid' ;
GO

See Also
Create and Attach Schedules to Jobs
Schedule a Job
Create a Schedule
SQL Server Agent Stored Procedures (Transact-SQL)
sp_add_schedule (Transact-SQL)
sp_add_jobschedule (Transact-SQL)
sp_delete_schedule (Transact-SQL)
sp_help_schedule (Transact-SQL)
sp_attach_schedule (Transact-SQL)
sp_update_targetservergroup (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the name of the specified target server group.
Transact-SQL Syntax Conventions

Syntax
sp_update_targetservergroup
[@name =] 'current_name' ,
[@new_name =] 'new_name'

Arguments
[ @name =] 'current_name'
The name of the target server group. current_name is sysname, with no default.
[ @new_name =] 'new_name'
The new name for the target server group. new_name is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Permissions
To run this stored procedure, users must be granted the sysadmin fixed server role.

Remarks
sp_update_targetservergroup must be run from the msdb database.

Examples
The following example changes the name of the target server group Servers Processing Customer Orders to
Local Servers Processing Customer Orders .

USE msdb ;
GO

EXEC dbo.sp_update_targetservergroup
@name = N'Servers Processing Customer Orders',
@new_name = N'Local Servers Processing Customer Orders' ;
GO

See Also
sp_add_targetservergroup (Transact-SQL)
sp_delete_targetservergroup (Transact-SQL)
sp_help_targetservergroup (Transact-SQL)
System Stored Procedures (Transact-SQL)
SQL Server Profiler Stored Procedures (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
SQL Server supports the following system stored procedures that are used by SQL Server Profiler to monitor
performance and activity.

sp_trace_create sp_trace_setfilter

sp_trace_generateevent sp_trace_setstatus

sp_trace_setevent

For an example of using trace stored procedures, see Create a Trace (Transact-SQL).

See Also
SQL Server Event Class Reference
SQL Trace
System Stored Procedures (Transact-SQL)
sp_trace_create (Transact-SQL)
11/17/2017 • 6 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Creates a trace definition. The new trace will be in a stopped state.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use Extended Events instead.

Transact-SQL Syntax Conventions

Syntax
sp_trace_create [ @traceid = ] trace_id OUTPUT
, [ @options = ] option_value
, [ @tracefile = ] 'trace_file'
[ , [ @maxfilesize = ] max_file_size ]
[ , [ @stoptime = ] 'stop_time' ]
[ , [ @filecount = ] 'max_rollover_files' ]

Arguments
[ @traceid= ] trace_id
Is the number assigned by Microsoft SQL Server to the new trace. Any user-provided input will be ignored. trace_id
is int, with a default of NULL. The user employs the trace_id value to identify, modify, and control the trace defined
by this stored procedure.
[ @options= ] option_value
Specifies the options set for the trace. option_value is int, with no default. Users may choose a combination of
these options by specifying the sum value of options picked. For example, to turn on both the options
TRACE_FILE_ROLLOVER and SHUTDOWN_ON_ERROR, specify 6 for option_value.
The following table lists the options, descriptions, and their values.

OPTION NAME OPTION VALUE DESCRIPTION


OPTION NAME OPTION VALUE DESCRIPTION

TRACE_FILE_ROLLOVER 2 Specifies that when the max_file_size is


reached, the current trace file is closed
and a new file is created. All new records
will be written to the new file. The new
file will have the same name as the
previous file, but an integer will be
appended to indicate its sequence. For
example, if the original trace file is
named filename.trc, the next trace file is
named filename_1.trc, the following
trace file is filename_2.trc, and so on.

As more rollover trace files are created,


the integer value appended to the file
name increases sequentially.

SQL Server uses the default value of


max_file_size (5 MB) if this option is
specified without specifying a value for
max_file_size.

SHUTDOWN_ON_ERROR 4 Specifies that if the trace cannot be


written to the file for whatever reason,
SQL Server shuts down. This option is
useful when performing security audit
traces.

TRACE_PRODUCE_BLACKBOX 8 Specifies that a record of the last 5 MB


of trace information produced by the
server will be saved by the server.
TRACE_PRODUCE_BLACKBOX is
incompatible with all other options.

[ @tracefile= ] 'trace_file'
Specifies the location and file name to which the trace will be written. trace_file is nvarchar(245) with no default.
trace_file can be either a local directory (such as N 'C:\MSSQL\Trace\trace.trc') or a UNC to a share or path
(N'\\Servername\Sharename\Directory\trace.trc').
SQL Server will append a .trc extension to all trace file names. If the TRACE_FILE_ROLLOVER option and a
max_file_size are specified, SQL Server creates a new trace file when the original trace file grows to its maximum
size. The new file has the same name as the original file, but _n is appended to indicate its sequence, starting with 1.
For example, if the first trace file is named filename.trc, the second trace file is named filename_1.trc.
If you use the TRACE_FILE_ROLLOVER option, we recommend that you do not use underscore characters in the
original trace file name. If you do use underscores, the following behavior occurs:
SQL Server Profiler does not automatically load or prompt you to load the rollover files (if either of these file
rollover options are configured).
The fn_trace_gettable function does not load rollover files (when specified by using the number_files
argument) where the original file name ends with an underscore and a numeric value. (This does not apply
to the underscore and number that are automatically appended when a file rolls over.)
NOTE
As a workaround for both of these behaviors, you can rename the files to remove the underscores in the original file name.
For example, if the original file is named my_trace.trc, and the rollover file is named my_trace_1.trc, you can rename the
files to mytrace.trc and mytrace_1.trc before you open the files in SQL Server Profiler.

trace_file cannot be specified when the TRACE_PRODUCE_BLACKBOX option is used.


[ @maxfilesize= ] max_file_size
Specifies the maximum size in megabytes (MB) a trace file can grow. max_file_size is bigint, with a default value of
5.
If this parameter is specified without the TRACE_FILE_ROLLOVER option, the trace stops recording to the file when
the disk space used exceeds the amount specified by max_file_size.
[ @stoptime= ] 'stop_time'
Specifies the date and time the trace will be stopped. stop_time is datetime, with a default of NULL. If NULL, the
trace runs until it is manually stopped or until the server shuts down.
If both stop_time and max_file_size are specified, and TRACE_FILE_ROLLOVER is not specified, the trace tops when
either the specified stop time or maximum file size is reached. If stop_time, max_file_size, and
TRACE_FILE_ROLLOVER are specified, the trace stops at the specified stop time, assuming the trace does not fill up
the drive.
[ @filecount= ] 'max_rollover_files'
Specifies the maximum number or trace files to be maintained with the same base filename. max_rollover_files is
int, greater than one. This parameter is valid only if the TRACE_FILE_ROLLOVER option is specified. When
max_rollover_files is specified, SQL Server tries to maintain no more than max_rollover_files trace files by deleting
the oldest trace file before opening a new trace file. SQL Server tracks the age of trace files by appending a number
to the base file name.
For example, when the trace_file parameter is specified as "c:\mytrace", a file with the name "c:\mytrace_123.trc" is
older than a file with the name "c:\mytrace_124.trc". If max_rollover_files is set to 2, then SQL Server deletes the file
"c:\mytrace_123.trc" before creating the trace file "c:\mytrace_125.trc".
Notice that SQL Server only tries to delete each file once, and cannot delete a file that is in use by another process.
Therefore, if another application is working with trace files while the trace is running, SQL Server may leave these
trace files in the file system.

Return Code Values


The following table describes the code values that users may get following completion of the stored procedure.

RETURN CODE DESCRIPTION

0 No error.

1 Unknown error.

10 Invalid options. Returned when options specified are


incompatible.

12 File not created.


RETURN CODE DESCRIPTION

13 Out of memory. Returned when there is not enough memory


to perform the specified action.

14 Invalid stop time. Returned when the stop time specified has
already happened.

15 Invalid parameters. Returned when the user supplied


incompatible parameters.

Remarks
sp_trace_create is a SQL Server stored procedure that performs many of the actions previously executed by
xp_trace_\* extended stored procedures available in earlier versions of SQL Server. Use sp_trace_create instead
of:
xp_trace_addnewqueue
xp_trace_setqueuecreateinfo
xp_trace_setqueuedestination
sp_trace_create only creates a trace definition. This stored procedure cannot be used to start or change a
trace.
Parameters of all SQL Trace stored procedures (sp_trace_xx) are strictly typed. If these parameters are not
called with the correct input parameter data types, as specified in the argument description, the stored
procedure will return an error.
For sp_trace_create, the SQL Server service account must have Write permission on the trace file folder. If
the SQL Server service account is not an administrator on the computer where the trace file is located, you
must explicitly grant Write permission to the SQL Server service account.

NOTE
You can automatically load the trace file created with sp_trace_create into a table by using the fn_trace_gettable system
function. For information about how to use this system function, see sys.fn_trace_gettable (Transact-SQL).

For an example of using trace stored procedures, see Create a Trace (Transact-SQL).
TRACE_PRODUCE_BLACKBOX has the following characteristics:
It is a rollover trace. The default file_count is 2 but can be overridden by the user using filecount option.
The default file_size as with other traces is 5 MB and can be changed.
No filename can be specified. The file will be saved as: N'%SQLDIR%\MSSQL\DATA\blackbox.trc'
Only the following events and their columns are contained in the trace:
RPC starting
Batch starting
Exception
Attention
Events or columns cannot be added or removed from this trace.
Filters cannot be specified for this trace.

Permissions
User must have ALTER TRACE permission.

See Also
sp_trace_generateevent (Transact-SQL)
sp_trace_setevent (Transact-SQL)
sp_trace_setfilter (Transact-SQL)
sp_trace_setstatus (Transact-SQL)
SQL Trace
sp_trace_generateevent (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a user-defined event in SQL Server.

NOTE: This stored procedure is not deprecated. All other trace-related stored procedures are deprecated.

Transact-SQL Syntax Conventions

Syntax
sp_trace_generateevent [ @eventid = ] event_id
[ , [ @userinfo = ] 'user_info' ]
[ , [ @userdata = ] user_data ]

Arguments
[ @eventid=] event_id
Is the ID of the event to turn on. event_id is int, with no default. The ID must be one of the event numbers from 82
through 91, which represent user-defined events as set with sp_trace_setevent.
[ @userinfo= ] 'user_info'
Is the optional user-defined string identifying the reason for the event. user_info is nvarchar(128), with a default
of NULL.
[ @userdata= ] user_data
Is the optional user-specified data for the event. user_data is varbinary(8000), with a default of NULL.

Return Code Values


The following table describes the code values that users may get following completion of the stored procedure.

RETURN CODE DESCRIPTION

0 No error.

1 Unknown error.

3 The specified event is not valid. The event may not exist or it
is not an appropriate one for the store procedure.

13 Out of memory. Returned when there is not enough memory


to perform the specified action.

Remarks
sp_trace_generateevent performs many of the actions previously executed by the xp_trace_\* extended stored
procedures. Use sp_trace_generateevent instead of xp_trace_generate_event.
Only ID numbers of user-defined events may be used with sp_trace_generateevent. SQL Server will raise an
error if other event ID numbers are used.
Parameters of all SQL Trace stored procedures (sp_trace_xx) are strictly typed. If these parameters are not called
with the correct input parameter data types, as specified in the argument description, the stored procedure will
return an error.

Permissions
User must have ALTER TRACE permission.

Examples
The following example creates a user-configurable event on a sample table.

--Create a sample table.


CREATE TABLE user_config_test(col1 int, col2 char(10));

--DROP the trigger if it already exists.


IF EXISTS
(SELECT * FROM sysobjects WHERE name = 'userconfig_trg')
DROP TRIGGER userconfig_trg;

--Create an ON INSERT trigger on the sample table.


CREATE TRIGGER userconfig_trg
ON user_config_test FOR INSERT;
AS
EXEC master..sp_trace_generateevent
@event_class = 82, @userinfo = N'Inserted row into user_config_test';

--When an insert action happens, the user-configurable event fires. If


you were capturing the event id=82, you will see it in the Profiler output.
INSERT INTO user_config_test VALUES(1, 'abc');

See also
sys.fn_trace_geteventinfo (Transact-SQL)
sp_trace_setevent (Transact-SQL)
SQL Trace
sp_trace_setevent (Transact-SQL)
11/27/2017 • 23 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds or removes an event or event column to a trace. sp_trace_setevent may be executed only on existing traces
that are stopped (status is 0). An error is returned if this stored procedure is executed on a trace that does not exist
or whose status is not 0.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use Extended Events instead.

Transact-SQL Syntax Conventions

Syntax
sp_trace_setevent [ @traceid = ] trace_id
, [ @eventid = ] event_id
, [ @columnid = ] column_id
, [ @on = ] on

Arguments
[ @traceid= ] trace_id
Is the ID of the trace to be modified. trace_id is int, with no default. The user employs this trace_id value to
identify, modify, and control the trace.
[ @eventid= ] event_id
Is the ID of the event to turn on. event_id is int, with no default.
This table lists the events that can be added to or removed from a trace.

EVENT NUMBER EVENT NAME DESCRIPTION

0-9 Reserved Reserved

10 RPC:Completed Occurs when a remote procedure call


(RPC) has completed.

11 RPC:Starting Occurs when an RPC has started.

12 SQL:BatchCompleted Occurs when a Transact-SQL batch has


completed.

13 SQL:BatchStarting Occurs when a Transact-SQL batch has


started.
EVENT NUMBER EVENT NAME DESCRIPTION

14 Audit Login Occurs when a user successfully logs in


to SQL Server.

15 Audit Logout Occurs when a user logs out of SQL


Server.

16 Attention Occurs when attention events, such as


client-interrupt requests or broken
client connections, happen.

17 ExistingConnection Detects all activity by users connected


to SQL Server before the trace started.

18 Audit Server Starts and Stops Occurs when the SQL Server service
state is modified.

19 DTCTransaction Tracks Microsoft Distributed


Transaction Coordinator (MS DTC)
coordinated transactions between two
or more databases.

20 Audit Login Failed Indicates that a login attempt to SQL


Server from a client failed.

21 EventLog Indicates that events have been logged


in the Windows application log.

22 ErrorLog Indicates that error events have been


logged in the SQL Server error log.

23 Lock:Released Indicates that a lock on a resource, such


as a page, has been released.

24 Lock:Acquired Indicates acquisition of a lock on a


resource, such as a data page.

25 Lock:Deadlock Indicates that two concurrent


transactions have deadlocked each
other by trying to obtain incompatible
locks on resources the other
transaction owns.

26 Lock:Cancel Indicates that the acquisition of a lock


on a resource has been canceled (for
example, due to a deadlock).

27 Lock:Timeout Indicates that a request for a lock on a


resource, such as a page, has timed out
due to another transaction holding a
blocking lock on the required resource.
Time-out is determined by the
@@LOCK_TIMEOUT function, and can
be set with the SET LOCK_TIMEOUT
statement.
EVENT NUMBER EVENT NAME DESCRIPTION

28 Degree of Parallelism Event (7.0 Insert) Occurs before a SELECT, INSERT, or


UPDATE statement is executed.

29-31 Reserved Use Event 28 instead.

32 Reserved Reserved

33 Exception Indicates that an exception has


occurred in SQL Server.

34 SP:CacheMiss Indicates when a stored procedure is


not found in the procedure cache.

35 SP:CacheInsert Indicates when an item is inserted into


the procedure cache.

36 SP:CacheRemove Indicates when an item is removed


from the procedure cache.

37 SP:Recompile Indicates that a stored procedure was


recompiled.

38 SP:CacheHit Indicates when a stored procedure is


found in the procedure cache.

39 Deprecated Deprecated

40 SQL:StmtStarting Occurs when the Transact-SQL


statement has started.

41 SQL:StmtCompleted Occurs when the Transact-SQL


statement has completed.

42 SP:Starting Indicates when the stored procedure


has started.

43 SP:Completed Indicates when the stored procedure


has completed.

44 SP:StmtStarting Indicates that a Transact-SQL


statement within a stored procedure
has started executing.

45 SP:StmtCompleted Indicates that a Transact-SQL


statement within a stored procedure
has finished executing.

46 Object:Created Indicates that an object has been


created, such as for CREATE INDEX,
CREATE TABLE, and CREATE DATABASE
statements.
EVENT NUMBER EVENT NAME DESCRIPTION

47 Object:Deleted Indicates that an object has been


deleted, such as in DROP INDEX and
DROP TABLE statements.

48 Reserved

49 Reserved

50 SQL Transaction Tracks Transact-SQL BEGIN, COMMIT,


SAVE, and ROLLBACK TRANSACTION
statements.

51 Scan:Started Indicates when a table or index scan


has started.

52 Scan:Stopped Indicates when a table or index scan


has stopped.

53 CursorOpen Indicates when a cursor is opened on a


Transact-SQL statement by ODBC, OLE
DB, or DB-Library.

54 TransactionLog Tracks when transactions are written to


the transaction log.

55 Hash Warning Indicates that a hashing operation (for


example, hash join, hash aggregate,
hash union, and hash distinct) that is
not processing on a buffer partition has
reverted to an alternate plan. This can
occur because of recursion depth, data
skew, trace flags, or bit counting.

56-57 Reserved

58 Auto Stats Indicates an automatic updating of


index statistics has occurred.

59 Lock:Deadlock Chain Produced for each of the events leading


up to the deadlock.

60 Lock:Escalation Indicates that a finer-grained lock has


been converted to a coarser-grained
lock (for example, a page lock escalated
or converted to a TABLE or HoBT lock).

61 OLE DB Errors Indicates that an OLE DB error has


occurred.

62-66 Reserved

67 Execution Warnings Indicates any warnings that occurred


during the execution of a SQL Server
statement or stored procedure.
EVENT NUMBER EVENT NAME DESCRIPTION

68 Showplan Text (Unencoded) Displays the plan tree of the Transact-


SQL statement executed.

69 Sort Warnings Indicates sort operations that do not fit


into memory. Does not include sort
operations involving the creating of
indexes; only sort operations within a
query (such as an ORDER BY clause
used in a SELECT statement).

70 CursorPrepare Indicates when a cursor on a Transact-


SQL statement is prepared for use by
ODBC, OLE DB, or DB-Library.

71 Prepare SQL ODBC, OLE DB, or DB-Library has


prepared a Transact-SQL statement or
statements for use.

72 Exec Prepared SQL ODBC, OLE DB, or DB-Library has


executed a prepared Transact-SQL
statement or statements.

73 Unprepare SQL ODBC, OLE DB, or DB-Library has


unprepared (deleted) a prepared
Transact-SQL statement or statements.

74 CursorExecute A cursor previously prepared on a


Transact-SQL statement by ODBC, OLE
DB, or DB-Library is executed.

75 CursorRecompile A cursor opened on a Transact-SQL


statement by ODBC or DB-Library has
been recompiled either directly or due
to a schema change.

Triggered for ANSI and non-ANSI


cursors.

76 CursorImplicitConversion A cursor on a Transact-SQL statement


is converted by SQL Server from one
type to another.

Triggered for ANSI and non-ANSI


cursors.

77 CursorUnprepare A prepared cursor on a Transact-SQL


statement is unprepared (deleted) by
ODBC, OLE DB, or DB-Library.

78 CursorClose A cursor previously opened on a


Transact-SQL statement by ODBC, OLE
DB, or DB-Library is closed.

79 Missing Column Statistics Column statistics that could have been


useful for the optimizer are not
available.
EVENT NUMBER EVENT NAME DESCRIPTION

80 Missing Join Predicate Query that has no join predicate is


being executed. This could result in a
long-running query.

81 Server Memory Change SQL Server memory usage has


increased or decreased by either 1
megabyte (MB) or 5 percent of the
maximum server memory, whichever is
greater.

82-91 User Configurable (0-9) Event data defined by the user.

92 Data File Auto Grow Indicates that a data file was extended
automatically by the server.

93 Log File Auto Grow Indicates that a log file was extended
automatically by the server.

94 Data File Auto Shrink Indicates that a data file was shrunk
automatically by the server.

95 Log File Auto Shrink Indicates that a log file was shrunk
automatically by the server.

96 Showplan Text Displays the query plan tree of the SQL


statement from the query optimizer.
Note that the TextData column does
not contain the Showplan for this
event.

97 Showplan All Displays the query plan with full


compile-time details of the SQL
statement executed. Note that the
TextData column does not contain the
Showplan for this event.

98 Showplan Statistics Profile Displays the query plan with full run-
time details of the SQL statement
executed. Note that the TextData
column does not contain the Showplan
for this event.

99 Reserved

100 RPC Output Parameter Produces output values of the


parameters for every RPC.

101 Reserved

102 Audit Database Scope GDR Occurs every time a GRANT, DENY,
REVOKE for a statement permission is
issued by any user in SQL Server for
database-only actions such as granting
permissions on a database.
EVENT NUMBER EVENT NAME DESCRIPTION

103 Audit Object GDR Event Occurs every time a GRANT, DENY,
REVOKE for an object permission is
issued by any user in SQL Server.

104 Audit AddLogin Event Occurs when a SQL Server login is


added or removed; for sp_addlogin
and sp_droplogin.

105 Audit Login GDR Event Occurs when a Windows login right is
added or removed; for sp_grantlogin,
sp_revokelogin, and sp_denylogin.

106 Audit Login Change Property Event Occurs when a property of a login,
except passwords, is modified; for
sp_defaultdb and
sp_defaultlanguage.

107 Audit Login Change Password Event Occurs when a SQL Server login
password is changed.

Passwords are not recorded.

108 Audit Add Login to Server Role Event Occurs when a login is added or
removed from a fixed server role; for
sp_addsrvrolemember, and
sp_dropsrvrolemember.

109 Audit Add DB User Event Occurs when a login is added or


removed as a database user (Windows
or SQL Server) to a database; for
sp_grantdbaccess,
sp_revokedbaccess, sp_adduser, and
sp_dropuser.

110 Audit Add Member to DB Role Event Occurs when a login is added or
removed as a database user (fixed or
user-defined) to a database; for
sp_addrolemember,
sp_droprolemember, and
sp_changegroup.

111 Audit Add Role Event Occurs when a login is added or


removed as a database user to a
database; for sp_addrole and
sp_droprole.

112 Audit App Role Change Password Event Occurs when a password of an
application role is changed.

113 Audit Statement Permission Event Occurs when a statement permission


(such as CREATE TABLE) is used.

114 Audit Schema Object Access Event Occurs when an object permission
(such as SELECT) is used, both
successfully or unsuccessfully.
EVENT NUMBER EVENT NAME DESCRIPTION

115 Audit Backup/Restore Event Occurs when a BACKUP or RESTORE


command is issued.

116 Audit DBCC Event Occurs when DBCC commands are


issued.

117 Audit Change Audit Event Occurs when audit trace modifications
are made.

118 Audit Object Derived Permission Event Occurs when a CREATE, ALTER, and
DROP object commands are issued.

119 OLEDB Call Event Occurs when OLE DB provider calls are
made for distributed queries and
remote stored procedures.

120 OLEDB QueryInterface Event Occurs when OLE DB QueryInterface


calls are made for distributed queries
and remote stored procedures.

121 OLEDB DataRead Event Occurs when a data request call is


made to the OLE DB provider.

122 Showplan XML Occurs when an SQL statement


executes. Include this event to identify
Showplan operators. Each event is
stored in a well-formed XML document.
Note that the Binary column for this
event contains the encoded Showplan.
Use SQL Server Profiler to open the
trace and view the Showplan.

123 SQL:FullTextQuery Occurs when a full text query executes.

124 Broker:Conversation Reports the progress of a Service


Broker conversation.

125 Deprecation Announcement Occurs when you use a feature that will
be removed from a future version of
SQL Server.

126 Deprecation Final Support Occurs when you use a feature that will
be removed from the next major
release of SQL Server.

127 Exchange Spill Event Occurs when communication buffers in


a parallel query plan have been
temporarily written to the tempdb
database.

128 Audit Database Management Event Occurs when a database is created,


altered, or dropped.
EVENT NUMBER EVENT NAME DESCRIPTION

129 Audit Database Object Management Occurs when a CREATE, ALTER, or


Event DROP statement executes on database
objects, such as schemas.

130 Audit Database Principal Management Occurs when principals, such as users,
Event are created, altered, or dropped from a
database.

131 Audit Schema Object Management Occurs when server objects are created,
Event altered, or dropped.

132 Audit Server Principal Impersonation Occurs when there is an impersonation


Event within server scope, such as EXECUTE
AS LOGIN.

133 Audit Database Principal Impersonation Occurs when an impersonation occurs


Event within the database scope, such as
EXECUTE AS USER or SETUSER.

134 Audit Server Object Take Ownership Occurs when the owner is changed for
Event objects in server scope.

135 Audit Database Object Take Ownership Occurs when a change of owner for
Event objects within database scope occurs.

136 Broker:Conversation Group Occurs when Service Broker creates a


new conversation group or drops an
existing conversation group.

137 Blocked Process Report Occurs when a process has been


blocked for more than a specified
amount of time. Does not include
system processes or processes that are
waiting on non deadlock-detectable
resources. Use sp_configure to
configure the threshold and frequency
at which reports are generated.

138 Broker:Connection Reports the status of a transport


connection managed by Service Broker.

139 Broker:Forwarded Message Sent Occurs when Service Broker forwards a


message.

140 Broker:Forwarded Message Dropped Occurs when Service Broker drops a


message that was intended to be
forwarded.

141 Broker:Message Classify Occurs when Service Broker determines


the routing for a message.

142 Broker:Transmission Indicates that errors have occurred in


the Service Broker transport layer. The
error number and state values indicate
the source of the error.
EVENT NUMBER EVENT NAME DESCRIPTION

143 Broker:Queue Disabled Indicates a poison message was


detected because there were five
consecutive transaction rollbacks on a
Service Broker queue. The event
contains the database ID and queue ID
of the queue that contains the poison
message.

144-145 Reserved

146 Showplan XML Statistics Profile Occurs when an SQL statement


executes. Identifies the Showplan
operators and displays complete,
compile-time data. Note that the
Binary column for this event contains
the encoded Showplan. Use SQL Server
Profiler to open the trace and view the
Showplan.

148 Deadlock Graph Occurs when an attempt to acquire a


lock is canceled because the attempt
was part of a deadlock and was chosen
as the deadlock victim. Provides an
XML description of a deadlock.

149 Broker:Remote Message Occurs when Service Broker sends or


Acknowledgement receives a message acknowledgement.

150 Trace File Close Occurs when a trace file closes during a
trace file rollover.

151 Reserved

152 Audit Change Database Owner Occurs when ALTER AUTHORIZATION


is used to change the owner of a
database and permissions are checked
to do that.

153 Audit Schema Object Take Ownership Occurs when ALTER AUTHORIZATION
Event is used to assign an owner to an object
and permissions are checked to do that.

154 Reserved

155 FT:Crawl Started Occurs when a full-text crawl


(population) starts. Use to check if a
crawl request is picked up by worker
tasks.

156 FT:Crawl Stopped Occurs when a full-text crawl


(population) stops. Stops occur when a
crawl completes successfully or when a
fatal error occurs.
EVENT NUMBER EVENT NAME DESCRIPTION

157 FT:Crawl Aborted Occurs when an exception is


encountered during a full-text crawl.
Usually causes the full-text crawl to
stop.

158 Audit Broker Conversation Reports audit messages related to


Service Broker dialog security.

159 Audit Broker Login Reports audit messages related to


Service Broker transport security.

160 Broker:Message Undeliverable Occurs when Service Broker is unable to


retain a received message that should
have been delivered to a service.

161 Broker:Corrupted Message Occurs when Service Broker receives a


corrupted message.

162 User Error Message Displays error messages that users see
in the case of an error or exception.

163 Broker:Activation Occurs when a queue monitor starts an


activation stored procedure, sends a
QUEUE_ACTIVATION notification, or
when an activation stored procedure
started by a queue monitor exits.

164 Object:Altered Occurs when a database object is


altered.

165 Performance statistics Occurs when a compiled query plan has


been cached for the first time,
recompiled, or removed from the plan
cache.

166 SQL:StmtRecompile Occurs when a statement-level


recompilation occurs.

167 Database Mirroring State Change Occurs when the state of a mirrored
database changes.

168 Showplan XML For Query Compile Occurs when an SQL statement
compiles. Displays the complete,
compile-time data. Note that the
Binary column for this event contains
the encoded Showplan. Use SQL Server
Profiler to open the trace and view the
Showplan.

169 Showplan All For Query Compile Occurs when an SQL statement
compiles. Displays complete, compile-
time data. Use to identify Showplan
operators.
EVENT NUMBER EVENT NAME DESCRIPTION

170 Audit Server Scope GDR Event Indicates that a grant, deny, or revoke
event for permissions in server scope
occurred, such as creating a login.

171 Audit Server Object GDR Event Indicates that a grant, deny, or revoke
event for a schema object, such as a
table or function, occurred.

172 Audit Database Object GDR Event Indicates that a grant, deny, or revoke
event for database objects, such as
assemblies and schemas, occurred.

173 Audit Server Operation Event Occurs when Security Audit operations
such as altering settings, resources,
external access, or authorization are
used.

175 Audit Server Alter Trace Event Occurs when a statement checks for
the ALTER TRACE permission.

176 Audit Server Object Management Event Occurs when server objects are created,
altered, or dropped.

177 Audit Server Principal Management Occurs when server principals are
Event created, altered, or dropped.

178 Audit Database Operation Event Occurs when database operations


occur, such as checkpoint or subscribe
query notification.

180 Audit Database Object Access Event Occurs when database objects, such as
schemas, are accessed.

181 TM: Begin Tran starting Occurs when a BEGIN TRANSACTION


request starts.

182 TM: Begin Tran completed Occurs when a BEGIN TRANSACTION


request completes.

183 TM: Promote Tran starting Occurs when a PROMOTE


TRANSACTION request starts.

184 TM: Promote Tran completed Occurs when a PROMOTE


TRANSACTION request completes.

185 TM: Commit Tran starting Occurs when a COMMIT


TRANSACTION request starts.

186 TM: Commit Tran completed Occurs when a COMMIT


TRANSACTION request completes.

187 TM: Rollback Tran starting Occurs when a ROLLBACK


TRANSACTION request starts.
EVENT NUMBER EVENT NAME DESCRIPTION

188 TM: Rollback Tran completed Occurs when a ROLLBACK


TRANSACTION request completes.

189 Lock:Timeout (timeout > 0) Occurs when a request for a lock on a


resource, such as a page, times out.

190 Progress Report: Online Index Reports the progress of an online index
Operation build operation while the build process
is running.

191 TM: Save Tran starting Occurs when a SAVE TRANSACTION


request starts.

192 TM: Save Tran completed Occurs when a SAVE TRANSACTION


request completes.

193 Background Job Error Occurs when a background job


terminates abnormally.

194 OLEDB Provider Information Occurs when a distributed query runs


and collects information corresponding
to the provider connection.

195 Mount Tape Occurs when a tape mount request is


received.

196 Assembly Load Occurs when a request to load a CLR


assembly occurs.

197 Reserved

198 XQuery Static Type Occurs when an XQuery expression is


executed. This event class provides the
static type of the XQuery expression.

199 QN: subscription Occurs when a query registration


cannot be subscribed. The TextData
column contains information about the
event.

200 QN: parameter table Information about active subscriptions


is stored in internal parameter tables.
This event class occurs when a
parameter table is created or deleted.
Typically, these tables are created or
deleted when the database is restarted.
The TextData column contains
information about the event.
EVENT NUMBER EVENT NAME DESCRIPTION

201 QN: template A query template represents a class of


subscription queries. Typically, queries
in the same class are identical except for
their parameter values. This event class
occurs when a new subscription request
falls into an already existing class of
(Match), a new class (Create), or a Drop
class, which indicates cleanup of
templates for query classes without
active subscriptions. The TextData
column contains information about the
event.

202 QN: dynamics Tracks internal activities of query


notifications. The TextData column
contains information about the event.

212 Bitmap Warning Indicates when bitmap filters have been


disabled in a query.

213 Database Suspect Data Page Indicates when a page is added to the
suspect_pages table in msdb.

214 CPU threshold exceeded Indicates when the Resource Governor


detects a query has exceeded the CPU
threshold value
(REQUEST_MAX_CPU_TIME_SEC).

215 Indicates when a LOGON trigger or Indicates when a LOGON trigger or


Resource Governor classifier function Resource Governor classifier function
starts execution. starts execution.

216 PreConnect:Completed Indicates when a LOGON trigger or


Resource Governor classifier function
completes execution.

217 Plan Guide Successful Indicates that SQL Server successfully


produced an execution plan for a query
or batch that contained a plan guide.

218 Plan Guide Unsuccessful Indicates that SQL Server could not
produce an execution plan for a query
or batch that contained a plan guide.
SQL Server attempted to generate an
execution plan for this query or batch
without applying the plan guide. An
invalid plan guide may be the cause of
this problem. You can validate the plan
guide by using the
sys.fn_validate_plan_guide system
function.

235 Audit Fulltext

[ @columnid= ] column_id
Is the ID of the column to be added for the event. column_id is int, with no default.
The following table lists the columns that can be added for an event.

COLUMN NUMBER COLUMN NAME DESCRIPTION

1 TextData Text value dependent on the event


class that is captured in the trace.

2 BinaryData Binary value dependent on the event


class captured in the trace.

3 DatabaseID ID of the database specified by the USE


database statement, or the default
database if no USE database statement
is issued for a given connection.

The value for a database can be


determined by using the DB_ID
function.

4 TransactionID System-assigned ID of the transaction.

5 LineNumber Contains the number of the line that


contains the error. For events that
involve Transact-SQL statements, like
SP:StmtStarting, the LineNumber
contains the line number of the
statement in the stored procedure or
batch.

6 NTUserName Microsoft Windows user name.

7 NTDomainName Windows domain to which the user


belongs.

8 HostName Name of the client computer that


originated the request.

9 ClientProcessID ID assigned by the client computer to


the process in which the client
application is running.

10 ApplicationName Name of the client application that


created the connection to an instance
of SQL Server. This column is populated
with the values passed by the
application rather than the displayed
name of the program.

11 LoginName SQL Server login name of the client.

12 SPID Server Process ID assigned by SQL


Server to the process associated with
the client.

13 Duration Amount of elapsed time (in


microseconds) taken by the event. This
data column is not populated by the
Hash Warning event.
COLUMN NUMBER COLUMN NAME DESCRIPTION

14 StartTime Time at which the event started, when


available.

15 EndTime Time at which the event ended. This


column is not populated for starting
event classes, such as
SQL:BatchStarting or SP:Starting. It is
also not populated by the Hash
Warning event.

16 Reads Number of logical disk reads performed


by the server on behalf of the event.
This column is not populated by the
Lock:Released event.

17 Writes Number of physical disk writes


performed by the server on behalf of
the event.

18 CPU Amount of CPU time (in milliseconds)


used by the event.

19 Permissions Represents the bitmap of permissions;


used by Security Auditing.

20 Severity Severity level of an exception.

21 EventSubClass Type of event subclass. This data


column is not populated for all event
classes.

22 ObjectID System-assigned ID of the object.

23 Success Success of the permissions usage


attempt; used for auditing.

1 = success0 = failure

24 IndexID ID for the index on the object affected


by the event. To determine the index ID
for an object, use the indid column of
the sysindexes system table.

25 IntegerData Integer value dependent on the event


class captured in the trace.

26 ServerName Name of the instance of SQL Server,


either servername or
servername\instancename, being
traced.

27 EventClass Type of event class being recorded.

28 ObjectType Type of object, such as: table, function,


or stored procedure.
COLUMN NUMBER COLUMN NAME DESCRIPTION

29 NestLevel The nesting level at which this stored


procedure is executing. See
@@NESTLEVEL (Transact-SQL).

30 State Server state, in case of an error.

31 Error Error number.

32 Mode Lock mode of the lock acquired. This


column is not populated by the
Lock:Released event.

33 Handle Handle of the object referenced in the


event.

34 ObjectName Name of object accessed.

35 DatabaseName Name of the database specified in the


USE database statement.

36 FileName Logical name of the file name modified.

37 OwnerName Owner name of the referenced object.

38 RoleName Name of the database or server-wide


role targeted by a statement.

39 TargetUserName User name of the target of some action.

40 DBUserName SQL Server database user name of the


client.

41 LoginSid Security identifier (SID) of the logged-in


user.

42 TargetLoginName Login name of the target of some


action.

43 TargetLoginSid SID of the login that is the target of


some action.

44 ColumnPermissions Column-level permissions status; used


by Security Auditing.

45 LinkedServerName Name of the linked server.

46 ProviderName Name of the OLE DB provider.

47 MethodName Name of the OLE DB method.

48 RowCounts Number of rows in the batch.


COLUMN NUMBER COLUMN NAME DESCRIPTION

49 RequestID ID of the request containing the


statement.

50 XactSequence A token to describe the current


transaction.

51 EventSequence Sequence number for this event.

52 BigintData1 bigint value, which is dependent on the


event class captured in the trace.

53 BigintData2 bigint value, which is dependent on the


event class captured in the trace.

54 GUID GUID value, which is dependent on the


event class captured in the trace.

55 IntegerData2 Integer value, which is dependent on


the event class captured in the trace.

56 ObjectID2 ID of the related object or entity, if


available.

57 Type Integer value, which is dependent on


the event class captured in the trace.

58 OwnerID Type of the object that owns the lock.


For lock events only.

59 ParentName Name of the schema the object is


within.

60 IsSystem Indicates whether the event occurred


on a system process or a user process.

1 = system

0 = user.

61 Offset Starting offset of the statement within


the stored procedure or batch.

62 SourceDatabaseID ID of the database in which the source


of the object exists.

63 SqlHandle 64-bit hash based on the text of an ad


hoc query or the database and object
ID of an SQL object. This value can be
passed to sys.dm_exec_sql_text() to
retrieve the associated SQL text.
COLUMN NUMBER COLUMN NAME DESCRIPTION

64 SessionLoginName The login name of the user who


originated the session. For example, if
you connect to SQL Server using
Login1 and execute a statement as
Login2, SessionLoginName displays
Login1, while LoginName displays
Login2. This data column displays both
SQL Server and Windows logins.

[ @on=] on
Specifies whether to turn the event ON (1) or OFF (0). on is bit, with no default.
If on is set to 1, and column_id is NULL, then the event is set to ON and all columns are cleared. If column_id is not
null, then the column is set to ON for that event.
If on is set to 0, and column_id is NULL, then the event is turned OFF and all columns are cleared. If column_id is
not null, then the column is turned OFF.
This table illustrates the interaction between @on and @columnid.

@ON @COLUMNID RESULT

ON (1) NULL Event is turned ON.

All Columns are cleared.

NOT NULL Column is turned ON for the specified


Event.

OFF (0) NULL Event is turned OFF.

All Columns are cleared.

NOT NULL Column is turned OFF for the specified


Event.

Return Code Values


The following table describes the code values that users may get following completion of the stored procedure.

RETURN CODE DESCRIPTION

0 No error.

1 Unknown error.

2 The trace is currently running. Changing the trace at this time


will result in an error.

3 The specified event is not valid. The event may not exist or it
is not an appropriate one for the store procedure.

4 The specified column is not valid.


RETURN CODE DESCRIPTION

9 The specified trace handle is not valid.

11 The specified column is used internally and cannot be


removed.

13 Out of memory. Returned when there is not enough memory


to perform the specified action.

16 The function is not valid for this trace.

Remarks
sp_trace_setevent performs many of the actions previously executed by extended stored procedures available in
earlier versions of SQL Server. Use sp_trace_setevent instead of the following:
xp_trace_addnewqueue
xp_trace_eventclassrequired
xp_trace_seteventclassrequired
Users must execute sp_trace_setevent for each column added for each event. During each execution, if
@on is set to 1, sp_trace_setevent adds the specified event to the list of events of the trace. If @on is set
to 0, sp_trace_setevent removes the specified event from the list.
Parameters of all SQL Trace stored procedures (sp_trace_xx) are strictly typed. If these parameters are not
called with the correct input parameter data types, as specified in the argument description, the stored
procedure will return an error.
For an example of using trace stored procedures, see Create a Trace (Transact-SQL).

Permissions
User must have ALTER TRACE permission.

See Also
sys.fn_trace_geteventinfo (Transact-SQL)
sys.fn_trace_getinfo (Transact-SQL)
sp_trace_generateevent (Transact-SQL)
SQL Server Event Class Reference
SQL Trace
sp_trace_setfilter (Transact-SQL)
11/27/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Applies a filter to a trace. sp_trace_setfilter may be executed only on existing traces that are stopped (status is 0).
SQL Server returns an error if this stored procedure is executed on a trace that does not exist or whose status is
not 0.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use Extended Events instead.

Transact-SQL Syntax Conventions

Syntax
sp_trace_setfilter [ @traceid = ] trace_id
, [ @columnid = ] column_id
, [ @logical_operator = ] logical_operator
, [ @comparison_operator = ] comparison_operator
, [ @value = ] value

Arguments
[ @traceid= ] trace_id
Is the ID of the trace to which the filter is set. trace_id is int, with no default. The user employs this trace_id value to
identify, modify, and control the trace.
[ @columnid= ] column_id
Is the ID of the column on which the filter is applied. column_id is int, with no default. If column_id is NULL, SQL
Server clears all filters for the specified trace.
[ @logical_operator = ] logical_operator
Specifies whether the AND (0) or OR (1) operator is applied. logical_operator is int, with no default.
[ @comparison_operator= ] comparison_operator
Specifies the type of comparison to be made. comparison_operator is int, with no default. The table contains the
comparison operators and their representative values.

VALUE COMPARISON OPERATOR

0 = (Equal)

1 <> (Not Equal)

2 > (Greater Than)


VALUE COMPARISON OPERATOR

3 < (Less Than)

4 >= (Greater Than Or Equal)

5 <= (Less Than Or Equal)

6 LIKE

7 NOT LIKE

[ @value= ] value
Specifies the value on which to filter. The data type of value must match the data type of the column to be filtered.
For example, if the filter is set on an Object ID column that is an int data type, value must be int. If value is
nvarchar or varbinary, it can have a maximum length of 8000.
When the comparison operator is LIKE or NOT LIKE, the logical operator can include "%" or other filter appropriate
for the LIKE operation.
You can specify NULL for value to filter out events with NULL column values. Only 0 (= Equal) and 1 (<> Not
Equal) operators are valid with NULL. In this case, these operators are equivalent to the Transact-SQL IS NULL and
IS NOT NULL operators.
To apply the filter between a range of column values, sp_trace_setfilter must be executed twice -- once with a
greater-than-or-equals ('>=') comparison operator, and another time with a less-than-or-equals ('<=') operator.
For more information about data column data types, see the SQL Server Event Class Reference.

Return Code Values


The following table describes the code values that users may get following completion of the stored procedure.

RETURN CODE DESCRIPTION

0 No error.

1 Unknown error.

2 The trace is currently running. Changing the trace at this time


results in an error.

4 The specified Column is not valid.

5 The specified Column is not allowed for filtering. This value is


returned only from sp_trace_setfilter.

6 The specified Comparison Operator is not valid.

7 The specified Logical Operator is not valid.

9 The specified Trace Handle is not valid.


RETURN CODE DESCRIPTION

13 Out of memory. Returned when there is not enough memory


to perform the specified action.

16 The function is not valid for this trace.

Remarks
sp_trace_setfilter is a SQL Server stored procedure that performs many of the actions previously executed by
extended stored procedures available in earlier versions of SQL Server. Use sp_trace_setfilter instead of the
xp_trace_set*filter extended stored procedures to create, apply, remove, or manipulate filters on traces. For more
information, see Filter a Trace.
All filters for a particular column must be enabled together in one execution of sp_trace_setfilter. For example, if a
user intends to apply two filters on the application name column and one filter on the username column, the user
must specify the filters on application name in sequence. SQL Server returns an error if the user attempts to
specify a filter on application name in one stored procedure call, followed by a filter on username, then another
filter on application name.
Parameters of all SQL Trace stored procedures (sp_trace_xx) are strictly typed. If these parameters are not called
with the correct input parameter data types, as specified in the argument description, the stored procedure returns
an error.

Permissions
User must have ALTER TRACE permission.

Examples
The following example sets three filters on Trace 1 . The filters N'SQLT%' and N'MS%' operate on one column (
AppName , value 10 ) using the " LIKE " comparison operator. The filter N'joe' operates on a different column (
UserName , value 11 ) using the " EQUAL " comparison operator.

sp_trace_setfilter 1, 10, 0, 6, N'SQLT%';


sp_trace_setfilter 1, 10, 0, 6, N'MS%';
sp_trace_setfilter 1, 11, 0, 0, N'joe';

See Also
sys.fn_trace_getfilterinfo (Transact-SQL)
sys.fn_trace_getinfo (Transact-SQL)
SQL Trace
sp_trace_setstatus (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Modifies the current state of the specified trace.

IMPORTANT
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work,
and plan to modify applications that currently use this feature. Use Extended Events instead.

Transact-SQL Syntax Conventions

Syntax
sp_trace_setstatus [ @traceid = ] trace_id , [ @status = ] status

Arguments
[ @traceid= ] trace_id
Is the ID of the trace to be modified. trace_id is int, with no default. The user employs this trace_id value to identify,
modify, and control the trace. For information about retrieving the trace_id, see sys.fn_trace_getinfo (Transact-
SQL).
[ @status= ] status
Specifies the action to implement on the trace. status is int, with no default.
The following table lists the status that may be specified.

STATUS DESCRIPTION

0 Stops the specified trace.

1 Starts the specified trace.

2 Closes the specified trace and deletes its definition from the
server.

NOTE
A trace must be stopped first before it can be closed. A trace must be stopped and closed first before it can be viewed.

Return Code Values


The following table describes the code values that users may get following completion of the stored procedure.
RETURN CODE DESCRIPTION

0 No error.

1 Unknown error.

8 The specified Status is not valid.

9 The specified Trace Handle is not valid.

13 Out of memory. Returned when there is not enough memory


to perform the specified action.

If the trace is already in the state specified, SQL Server will return 0.

Remarks
Parameters of all SQL Trace stored procedures (sp_trace_xx) are strictly typed. If these parameters are not called
with the correct input parameter data types, as specified in the argument description, the stored procedure will
return an error.
For an example of using trace stored procedures, see Create a Trace (Transact-SQL).

Permissions
User must have ALTER TRACE permission.

See Also
sys.fn_trace_geteventinfo (Transact-SQL)
sys.fn_trace_getfilterinfo (Transact-SQL)
sp_trace_generateevent (Transact-SQL)
sp_trace_setevent (Transact-SQL)
sp_trace_setfilter (Transact-SQL)
SQL Trace
Stretch Database Extended Stored Procedures
(Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
This section describes the extended stored procedures that are related to Stretch Database.

In This Section
sys.sp_rda_deauthorize_db Removes the authenticated connection between a local Stretch-enabled database and
the remote Azure database.
sys.sp_rda_get_rpo_duration Gets the number of hours of migrated data that SQL Server retains in a staging table
to help ensure a full restore of the remote Azure database, if a restore is necessary.
sys.sp_rda_reauthorize_db Restores the authenticated connection between a local database enabled for Stretch and
the remote database.
sys.sp_rda_reconcile_batch
Reconciles the batch ID stored in the Stretch-enabled SQL Server table for the most recently migrated data with the
batch ID stored in the remote Azure table.
sys.sp_rda_reconcile_columns Reconciles the columns in the remote Azure table to the columns in the the Stretch-
enabled SQL Server table.
sys.sp_rda_reconcile_indexes Queues a schema task to reconcile indexes on the remote table.
sys.sp_rda_set_query_mode Specifies whether queries against the current Stretch-enabled database and its tables
return both local and remote data (the default), or local data only.
sys.sp_rda_set_rpo_duration Sets the number of hours of migrated data that SQL Server retains in a staging table
to help ensure a full restore of the remote Azure database, if a restore is necessary.
sys.sp_rda_test_connection Tests the connection from SQL Server to the remote Azure server and reports problems
that may prevent data migration.

See Also
Stretch Database
sys.sp_rda_deauthorize_db (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the authenticated connection between a local Stretch-enabled database and the remote Azure database.
Run sp_rda_deauthorize_db when the remote database is unreachable or in an inconsistent state and you want
to change query behavior for all Stretch-enabled tables in the database.
Transact-SQL Syntax Conventions

Syntax
sp_rda_deauthorize_db

Return Code Values


0 (success) or >0 (failure)

Permissions
Requires db_owner permissions.

Remarks
After you run sp_rda_deauthorize_db , all queries against Stretch-enabled databases and tables fail. That is, the
query mode is set to DISABLED. To exit this mode, do one of the following things.
Run sys.sp_rda_reauthorize_db (Transact-SQL) to reconnect to the remote Azure database. This operation
automatically resets the query mode to LOCAL_AND_REMOTE, which is the default behavior for Stretch
Database. That is, queries return results from both local and remote data.
Run sys.sp_rda_set_query_mode (Transact-SQL) with the LOCAL_ONLY argument to let queries continue to
run against local data only.

See Also
sys.sp_rda_set_query_mode (Transact-SQL)
sys.sp_rda_reauthorize_db (Transact-SQL)
Stretch Database
sys.sp_rda_get_rpo_duration (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Gets the number of hours of migrated data that SQL Server retains in a staging table to help ensure a full restore
of the remote Azure database, if a point in time restore is necessary.
For more info, see Stretch Database reduces the risk of data loss for your Azure data by retaining migrated rows
temporarily.
Transact-SQL Syntax Conventions

Syntax
sp_rda_get_rpo_duration @durationinhours output

Output parameter
@durationinhours
Is the number of hours (a non-null integer value) of migrated data that SQL Server retains for the current Stretch-
enabled database.

Permissions
Requires db_owner permissions.

Remarks
Change the value by running sys.sp_rda_set_rpo_duration (Transact-SQL).

See Also
sys.sp_rda_set_rpo_duration (Transact-SQL)
Restore Stretch-enabled databases (Stretch Database)
Stretch Database
sys.sp_rda_reauthorize_db (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Restores the authenticated connection between a local database enabled for Stretch and the remote database.
Transact-SQL Syntax Conventions

Syntax
sp_rda_reauthorize_db @credential = @credential, @with_copy = @with_copy [ , @azure_servername =
@azure_servername, @azure_databasename = @azure_databasename ]

Arguments
@credential = @credential
Is the database scoped credential associated with the local Stretch-enabled database.
@with_copy = @with_copy
Specifies whether to make a copy of the remote data and connect to the copy (recommended). @with_copy is bit.
@azure_servername = @azure_servername
Specifies the name of the Azure server that contains the remote data. @azure_servername is sysname.
@azure_databasename = @azure_databasename
Specifies the name of the Azure database that contains the remote data. @azure_databasename is sysname.

Return Code Values


0 (success) or >0 (failure)

Permissions
Requires db_owner permissions.

Remarks
When you run sys.sp_rda_reauthorize_db (Transact-SQL) to reconnect to the remote Azure database, this
operation automatically resets the query mode to LOCAL_AND_REMOTE, which is the default behavior for Stretch
Database. That is, queries return results from both local and remote data.

Example
The following example restores the authenticated connection between a local database enabled for Stretch and the
remote database. It makes a copy of the remote data (recommended) and connects to the new copy.
DECLARE @credentialName nvarchar(128);
SET @credentialName = N'<existing_database_scoped_credential_name>';
EXEC sp_rda_reauthorize_db @credential = @credentialName, @with_copy = 1;

See Also
sys.sp_rda_deauthorize_db (Transact-SQL)
Stretch Database
sys.sp_rda_reconcile_batch (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reconciles the batch ID stored in the Stretch-enabled SQL Server table with the batch ID stored in the remote Azure
table.
Typically you only have to run sp_rda_reconcile_batch if you have manually deleted the most recently migrated
data from the remote table. When you manually delete remote data that includes the most recent batch, the batch
IDs are out of sync and migration stops.
To delete data that has already been migrated to Azure, see the Remarks on this page.
Transact-SQL Syntax Conventions

Syntax
sp_rda_reconcile_batch @objname = '@objname'

Arguments
@objname = '@objname'
The name of the Stretch-enabled SQL Server table.

Permissions
Requires db_owner permissions.

Remarks
If you want to delete data that has already been migrated to Azure, do the following things.
1. Pause data migration. For more info, see Pause and resume data migration (Stretch Database).
2. Delete the data from the SQL Server staging table by running a DELETE command with the STAGE_ONLY
hint. For more info, see Make administrative updates and deletes.
3. Delete the same data from the remote Azure table by running a DELETE command with the REMOTE_ONLY
hint.
4. Run sp_rda_reconcile_batch.
5. Resume data migration. For more info, see Pause and resume data migration (Stretch Database).

Example
To reconcile the batch IDs, run the following statement.
EXEC sp_rda_reconcile_batch @objname = N'StretchEnabledTableName';
sys.sp_rda_reconcile_columns (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Reconciles the columns in the remote Azure table to the columns in the the Stretch-enabled SQL Server table.
sp_rda_reconcile_columns adds columns to the remote table that exist in the Stretch-enabled SQL Server table
but not in the remote table. These columns may be columns that you accidentally deleted from the remote table.
However, sp_rda_reconcile_columns does not delete columns from the remote table that exist in the remote
table but not in the SQL Server table.

IMPORTANT
When sp_rda_reconcile_columns recreates columns that you accidentally deleted from the remote table, it does not restore
the data that was previously in the deleted columns.

Transact-SQL Syntax Conventions

Syntax
sp_rda_reconcile_columns @objname = '@objname'

Arguments
@objname = '@objname'
The name of the Stretch-enabled SQL Server table.

Return Code Values


0 (success) or >0 (failure)

Permissions
Requires db_owner permissions.

Remarks
If there are columns in the remote Azure table that no longer exist in the Stretch-enabled SQL Server table, these
extra columns do not prevent Stretch Database from operating normally. You can optionally remove the extra
columns manually.

Example
To reconcile the the columns in the remote Azure table, run the following statement.
EXEC sp_rda_reconcile_columns @objname = N'StretchEnabledTableName';
sys.sp_rda_reconcile_indexes (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Queues a schema task to reconcile indexes on the remote table. After this task finishes successfully, the remote
table has the same indexes that exist on the local Stretch-enabled table.
If there is another task queued to reconcile indexes when you call sp_rda_reconcile_indexes, this stored
procedure does not queue a duplicate task.
Transact-SQL Syntax Conventions

Syntax
sp_rda_reconcile_indexes [@objname = ] 'objname'

Arguments
[@objname = ] 'objname'
Is the qualified or non-qualified name of the Stretch-enabled table for which you want to reconcile indexes. Quotes
are required only if you specify a qualified object.

Return Code Values


0 (success) or >0 (failure)

See Also
Stretch Database
sys.sp_rda_set_query_mode (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Specifies whether queries against the current Stretch-enabled database and its tables return both local and remote
data (the default), or local data only.
Transact-SQL Syntax Conventions

Syntax
sp_rda_set_query_mode [ @mode = ] @mode
[ , [ @force = ] @force ]

Arguments
[ @mode = ] @mode
Is one of the following values.
DISABLED All queries against Stretch-enabled tables fail.
LOCAL_ONLY Queries against Stretch-enabled tables return local data only.
LOCAL_AND_REMOTE Queries against Stretch-enabled tables return both local and remote data. This is
the default behavior.
[ @force = ] @force
Is an optional bit value that you can set to 1 if you want to change query mode without validation.

Return Code Values


0 (success) or >0 (failure)

Permissions
Requires db_owner permissions.

Remarks
The following extended stored procedures also set the query mode for a Stretch-enabled database.
sp_rda_deauthorize_db
After you run sp_rda_deauthorize_db , all queries against Stretch-enabled databases and tables fail. That
is, the query mode is set to DISABLED. To exit this mode, do one of the following things.
Run sys.sp_rda_reauthorize_db (Transact-SQL) to reconnect to the remote Azure database. This
operation automatically resets the query mode to LOCAL_AND_REMOTE, which is the default
behavior for Stretch Database. That is, queries return results from both local and remote data.
Run sys.sp_rda_set_query_mode with the LOCAL_ONLY argument to let queries continue to run
against local data only.
sp_rda_reauthorize_db
When you run sys.sp_rda_reauthorize_db (Transact-SQL) to reconnect to the remote Azure database, this
operation automatically resets the query mode to LOCAL_AND_REMOTE, which is the default behavior for
Stretch Database. That is, queries return results from both local and remote data.

See Also
sys.sp_rda_deauthorize_db (Transact-SQL)
Stretch Database
sys.sp_rda_set_rpo_duration (Transact-SQL)
11/17/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sets the number of hours of migrated data that SQL Server retains in a staging table to help ensure a full restore
of the remote Azure database, if a point in time restore is necessary.
For more info, see Stretch Database reduces the risk of data loss for your Azure data by retaining migrated rows
temporarily.
Transact-SQL Syntax Conventions

Syntax
sp_rda_set_rpo_duration [ @duration_hrs = ] duration_hrs

Arguments
[ @duration_hrs = ] duration_hrs
Is the number of hours (a non-null integer value) of migrated data that you want SQL Server to retain for the
current Stretch-enabled database. The default value and the minimum value is 8 hours.

NOTE
Higher values require more storage space on SQL Server.

Permissions
Requires db_owner permissions.

Remarks
Get the current value by running sys.sp_rda_get_rpo_duration (Transact-SQL).

See Also
sys.sp_rda_get_rpo_duration (Transact-SQL)
Restore Stretch-enabled databases (Stretch Database)
Stretch Database
sys.sp_rda_test_connection (Transact-SQL)
1/2/2018 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2016) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Tests the connection from SQL Server to the remote Azure server and reports problems that may prevent data
migration.

Syntax
EXECUTE sys.sp_rda_test_connection
@database_name = N'db_name',
@server_address = N'azure_server_fully_qualified_address',
@azure_username = N'azure_username',
@azure_password = N'azure_password',
@credential_name = N'credential_name'

Arguments
@database_name = N'db_name'
The name of the Stretch-enabled SQL Server database. This parameter is optional.
@server_address = N'azure_server_fully_qualified_address'
The fully qualified address of the Azure server.
If you provide a value for @database_name, but the specified database is not Stretch-enabled, then you
have to provide a value for @server_address.
If you provide a value for @database_name, and the specified database is Stretch-enabled, then you don't
have to provide a value for @server_address. If you provide a value for @server_address, the stored
procedure ignores it and uses existing Azure server already associated with the Stretch-enabled database.
@azure_username = N'azure_username
The user name for the remote Azure server.
@azure_password = N'azure_password'
The password for the remote Azure server.
@credential_name = N'credential_name'
Instead of providing a user name and password, you can provide the name of a credential stored in the
Stretch-enabled database.

Return Code Values


In case of success, sp_rda_test_connection returns error 14855 (STRETCH_MAJOR,
STRETCH_CONNECTION_TEST_PROC_SUCCEEDED) with severity EX_INFO and a success return code.
In case of failure, sp_rda_test_connection returns error 14856 (STRETCH_MAJOR,
STRETCH_CONNECTION_TEST_PROC_FAILED) with severity EX_USER and an error return code.
Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

link_state int One of the following values, which


correspond to the values for
link_state_desc.

-0
-1
-2
-3
-4

link_state_desc varchar(32) One of the following values, which


correspond to the preceding values for
link_state.

- HEALTHY
The between SQL Server and the
remote Azure server is healthy.
- ERROR_AZURE_FIREWALL
The Azure firewall is preventing the link
between SQL Server and the remote
Azure server.
- ERROR_NO_CONNECTION
SQL Server can't make a connection to
the remote Azure server.
- ERROR_AUTH_FAILURE
An authentication failure is preventing
the link between SQL Server and the
remote Azure server.
- ERROR
An error that's not an authentication
issue, a connectivity issue, or a firewall
issue is preventing the link between
SQL Server and the remote Azure
server.

error_number int The number of the error. If there is no


error, this field is NULL.

error_message nvarchar(1024) The error message. If there is no error,


this field is NULL.

Permissions
Requires db_owner permissions.

Examples
Check the connection from SQL Server to the remote Azure server

EXECUTE sys.sp_rda_test_connection @database_name = N'<Stretch-enabled database>'


GO

The results show that SQL Server can't connect to the remote Azure server.
LINK_STATE LINK_STATE_DESC ERROR_NUMBER ERROR_MESSAGE

2 ERROR_NO_CONNECTION <connection-related error <connection-related error


number> message>

Check the Azure firewall

USE <Stretch-enabled database>


GO
EXECUTE sys.sp_rda_test_connection
GO

The results show that the Azure firewall is preventing the link between SQL Server and the remote Azure server.

LINK_STATE LINK_STATE_DESC ERROR_NUMBER ERROR_MESSAGE

1 ERROR_AZURE_FIREWALL <firewall-related error <firewall-related error


number> message>

Check authentication credentials

USE <Stretch-enabled database>


GO
EXECUTE sys.sp_rda_test_connection
GO

The results show that an authentication failure is preventing the link between SQL Server and the remote Azure
server.

LINK_STATE LINK_STATE_DESC ERROR_NUMBER ERROR_MESSAGE

3 ERROR_AUTH_FAILURE <authentication-related <authentication-related


error number> error message>

Check the status of the remote Azure server

USE <SQL Server database>


GO
EXECUTE sys.sp_rda_test_connection
@server_address = N'<server name>.database.windows.net',
@azure_username = N'<user name>',
@azure_password = N'<password>'
GO

The results show that the connection is healthy and that you can enable Stretch Database for the specified
database.

LINK_STATE LINK_STATE_DESC ERROR_NUMBER ERROR_MESSAGE

0 HEALTHY NULL NULL


XML Stored Procedures (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Microsoft SQL Server supports the following system stored procedures that are used for XML text management.

sp_xml_preparedocument sp_xml_removedocument

See Also
System Stored Procedures (Transact-SQL)
sp_xml_preparedocument (Transact-SQL)
11/27/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Reads the XML text provided as input, parses the text by using the MSXML parser (Msxmlsql.dll), and provides the
parsed document in a state ready for consumption. This parsed document is a tree representation of the various
nodes in the XML document: elements, attributes, text, comments, and so on.
sp_xml_preparedocument returns a handle that can be used to access the newly created internal representation
of the XML document. This handle is valid for the duration of the session or until the handle is invalidated by
executing sp_xml_removedocument.

NOTE
A parsed document is stored in the internal cache of SQL Server. The MSXML parser uses one-eighth the total memory
available for SQL Server. To avoid running out of memory, run sp_xml_removedocument to free up the memory.

NOTE
For backwards compatibility, sp_xml_preparedocument collapses the CR (char(13)) and LF (char(10)) characters in
attributes even if these characters are entitized.

NOTE
The XML parser invoked by sp_xml_preparedocument can parse internal DTDs and entity declarations. Because maliciously
constructed DTDs and entity declarations can be used to perform a denial of service attack, we strongly recommend that
users not directly pass XML documents from untrusted sources to sp_xml_preparedocument.
To mitigate recursive entity expansion attacks, sp_xml_preparedocument limits to 10,000 the number of entities that can
be expanded underneath a single entity at the top level of a document. The limit does not apply to character or numeric
entities. This limit allows documents with many entity references to be stored, but prevents any one entity from being
recursively expanded in a chain longer than 10,000 expansions.

NOTE
sp_xml_preparedocument limits the number of elements that can be open at one time to 256.

Transact-SQL Syntax Conventions

Syntax
sp_xml_preparedocument
hdoc
OUTPUT
[ , xmltext ]
[ , xpath_namespaces ]
Arguments
hdoc
Is the handle to the newly created document. hdoc is an integer.
[ xmltext ]
Is the original XML document. The MSXML parser parses this XML document. xmltext is a text parameter: char,
nchar, varchar, nvarchar, text, ntext or xml. The default value is NULL, in which case an internal representation
of an empty XML document is created.

NOTE
sp_xml_preparedocument can only process text or untyped XML. If an instance value to be used as input is already typed
XML, first cast it to a new untyped XML instance or as a string and then pass that value as input. For more information, see
Compare Typed XML to Untyped XML.

[ xpath_namespaces ]
Specifies the namespace declarations that are used in row and column XPath expressions in OPENXML.
xpath_namespaces is a text parameter: char, nchar, varchar, nvarchar, text, ntext or xml.
The default value is <root xmlns:mp="urn:schemas-microsoft-com:xml-metaprop">. xpath_namespaces
provides the namespace URIs for the prefixes used in the XPath expressions in OPENXML by means of a well-
formed XML document. xpath_namespaces declares the prefix that must be used to refer to the namespace
urn:schemas-microsoft-com:xml-metaprop; this provides metadata about the parsed XML elements. Although
you can redefine the namespace prefix for the metaproperty namespace by using this technique, this namespace is
not lost. The prefix mp is still valid for urn:schemas-microsoft-com:xml-metaprop even if xpath_namespaces
contains no such declaration.

Return Code Values


0 (success) or >0 (failure)

Permissions
Requires membership in the public role.

Examples
A. Preparing an internal representation for a well-formed XML document
The following example returns a handle to the newly created internal representation of the XML document that is
provided as input. In the call to sp_xml_preparedocument , a default namespace prefix mapping is used.
DECLARE @hdoc int;
DECLARE @doc varchar(1000);
SET @doc ='
<ROOT>
<Customer CustomerID="VINET" ContactName="Paul Henriot">
<Order CustomerID="VINET" EmployeeID="5" OrderDate="1996-07-04T00:00:00">
<OrderDetail OrderID="10248" ProductID="11" Quantity="12"/>
<OrderDetail OrderID="10248" ProductID="42" Quantity="10"/>
</Order>
</Customer>
<Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">
<Order CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00">
<OrderDetail OrderID="10283" ProductID="72" Quantity="3"/>
</Order>
</Customer>
</ROOT>';
--Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @hdoc OUTPUT, @doc;
-- Remove the internal representation.
exec sp_xml_removedocument @hdoc;

B. Preparing an internal representation for a well-formed XML document with a DTD


The following example returns a handle to the newly created internal representation of the XML document that is
provided as input. The stored procedure validates the document loaded against the DTD included in the document.
In the call to sp_xml_preparedocument , a default namespace prefix mapping is used.

DECLARE @hdoc int;


DECLARE @doc varchar(2000);
SET @doc = '
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE root
[<!ELEMENT root (Customers)*>
<!ELEMENT Customers EMPTY>
<!ATTLIST Customers CustomerID CDATA #IMPLIED ContactName CDATA #IMPLIED>]>
<root>
<Customers CustomerID="ALFKI" ContactName="Maria Anders"/>
</root>';

EXEC sp_xml_preparedocument @hdoc OUTPUT, @doc;

C. Specifying a namespace URI


The following example returns a handle to the newly created internal representation of the XML document that is
provided as input. The call to sp_xml_preparedocument preserves the mp prefix to the metaproperty namespace
mapping and adds the xyz mapping prefix to the namespace urn:MyNamespace .
DECLARE @hdoc int;
DECLARE @doc varchar(1000);
SET @doc ='
<ROOT>
<Customer CustomerID="VINET" ContactName="Paul Henriot">
<Order CustomerID="VINET" EmployeeID="5"
OrderDate="1996-07-04T00:00:00">
<OrderDetail OrderID="10248" ProductID="11" Quantity="12"/>
<OrderDetail OrderID="10248" ProductID="42" Quantity="10"/>
</Order>
</Customer>
<Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">
<Order CustomerID="LILAS" EmployeeID="3"
OrderDate="1996-08-16T00:00:00">
<OrderDetail OrderID="10283" ProductID="72" Quantity="3"/>
</Order>
</Customer>
</ROOT>'
--Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @hdoc OUTPUT, @doc, '<ROOT xmlns:xyz="urn:MyNamespace"/>';

See Also
XML Stored Procedures (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_xml_removedocument (Transact-SQL)
OPENXML (Transact-SQL)
sp_xml_removedocument (Transact-SQL)
11/27/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the internal representation of the XML document specified by the document handle and invalidates the
document handle.

NOTE
A parsed document is stored in the internal cache of SQL Server. The MSXML parser (Msxmlsql.dll) uses one-eighth the total
memory available for SQL Server. To avoid running out of memory, run sp_xml_removedocument to free up the memory.

Transact-SQL Syntax Conventions

Syntax
sp_xml_removedocument hdoc

Arguments
hdoc
Is the handle to the newly created document. A handle that is not valid returns an error. hdoc is an integer.

Return Code Values


0 (success) or >0 (failure)

Permissions
Requires membership in the public role.

Examples
The following example removes the internal representation of an XML document. The handle to the document is
provided as input.

EXEC sp_xml_removedocument @hdoc;

See Also
System Stored Procedures (Transact-SQL)
XML Stored Procedures (Transact-SQL)
sp_xml_preparedocument (Transact-SQL)
OPENXML (Transact-SQL)
sp_db_selective_xml_index (Transact-SQL)
1/2/2018 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Enables and disables Selective XML Index functionality on a SQL Server database. If called without any parameters,
the stored procedure returns 1 if the Selective XML Index is enabled on a particular database.

NOTE
In order to disable the Selective XML Index using this stored procedure, the database must be put in simple recovery mode
by using the ALTER DATABASE SET Options (Transact-SQL) command.

Transact-SQL Syntax Conventions

Syntax
sys.sp_db_selective_xml_index[[ @db_name = ] 'db_name'],
[[ @action = ] 'action']

Arguments
[ @ db_name = ] 'db_name'
The name of the database to enable or disable Selective XML Index on. If db_name is NULL, the current database is
assumed.
[ @action = ] 'action'
Determines whether to enable or disable the index. If another value except 'on', ‘true’, ‘off’, or ‘false’ is passed, an
error will be raised.

Allowed values: 'on', 'off', 'true', 'false'

Return Code Values


1 if the Selective XML Index is enabled on a particular database.

Examples
A. Enable Selective XML Index functionality
The following example enables Selective XML Index on the current database.

EXECUTE sys.sp_db_selective_xml_index
@db_name = NULL
, @action = N'on';
GO
The following example enables Selective XML Index on the AdventureWorks2012 database.

EXECUTE sys.sp_db_selective_xml_index
@db_name = N'AdventureWorks2012'
, @action = N'true';
GO

B. Disable Selective XML Index functionality


The following example disables Selective XML Index on the current database.

EXECUTE sys.sp_db_selective_xml_index
@db_name = NULL
, @action = N'off';
GO

The following example disables Selective XML Index on the AdventureWorks2012 database.

EXECUTE sys.sp_db_selective_xml_index
@db_name = N'AdventureWorks2012'
, @action = N'false';
GO

C. Detect if Selective XML Index is enabled


The following example detects if Selective XML Index is enabled. Returns 1 if Selective XML Index is enabled.

EXECUTE sys.sp_db_selective_xml_index;
GO

See Also
Selective XML Indexes (SXI)
Replication Stored Procedures (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Replication system stored procedures are documented and available as a method for accomplishing one-
time tasks, such as implementing replication, and for using in batch files and scripts.
SQL Server Books Online provides examples of how to program most of the common replication tasks
using Transact-SQL stored procedures. For more information, see Replication System Stored Procedures
Concepts.

IMPORTANT
Only the replication stored procedures documented in SQL Server Books Online are supported. Undocumented
stored procedures are only for the use of internal replication components and should not be used to administer
replication.

sp_add_agent_parameter (Transact-SQL) sp_helparticledts (Transact-SQL)

sp_add_agent_profile (Transact-SQL) sp_helpdatatypemap (Transact-SQL)

sp_addarticle (Transact-SQL) sp_helpdistpublisher (Transact-SQL)

sp_adddistpublisher (Transact-SQL) sp_helpdistributiondb (Transact-SQL)

sp_adddistributiondb (Transact-SQL) sp_helpdistributor (Transact-SQL)

sp_adddistributor (Transact-SQL) sp_helpdistributor_properties (Transact-SQL)

sp_adddynamicsnapshot_job (Transact-SQL) sp_helpdynamicsnapshot_job (Transact-SQL)

sp_addlogreader_agent (Transact-SQL) sp_helplogreader_agent (Transact-SQL)

sp_addmergealternatepublisher (Transact-SQL) sp_helpmergealternatepublisher (Transact-SQL)

sp_addmergearticle (Transact-SQL) sp_helpmergearticle (Transact-SQL)

sp_addmergefilter (Transact-SQL) sp_helpmergearticlecolumn (Transact-SQL)

sp_addmergepartition (Transact-SQL) sp_helpmergearticleconflicts (Transact-SQL)

sp_addmergepublication (Transact-SQL) sp_helpmergeconflictrows (Transact-SQL)

sp_addmergepullsubscription (Transact-SQL) sp_helpmergedeleteconflictrows (Transact-SQL)

sp_addmergepullsubscription_agent (Transact-SQL) sp_helpmergefilter (Transact-SQL)


sp_addmergepushsubscription_agent (Transact-SQL) sp_helpmergepartition (Transact-SQL)

sp_addmergesubscription (Transact-SQL) sp_helpmergepublication (Transact-SQL)

sp_addpublication (Transact-SQL) sp_helpmergepullsubscription (Transact-SQL)

sp_addpublication_snapshot (Transact-SQL) sp_helpmergesubscription (Transact-SQL)

sp_addpullsubscription (Transact-SQL) sp_help_peerconflictdetection (Transact-SQL)

sp_addpullsubscription_agent (Transact-SQL) sp_helppeerrequests (Transact-SQL)

sp_addpushsubscription_agent (Transact-SQL) sp_helppeerresponses (Transact-SQL)

sp_addqreader_agent (Transact-SQL) sp_helppublication (Transact-SQL)

sp_addqueued_artinfo (Transact-SQL) sp_helppublication_snapshot (Transact-SQL)

sp_addscriptexec (Transact-SQL) sp_helppullsubscription (Transact-SQL)

sp_addsubscriber (Transact-SQL) sp_helpqreader_agent (Transact-SQL)

sp_addsubscriber_schedule (Transact-SQL) sp_helpreplfailovermode (Transact-SQL)

sp_addsubscription (Transact-SQL) sp_helpreplicationdboption (Transact-SQL)

sp_addsynctriggers (Transact-SQL) sp_helpreplicationoption (Transact-SQL)

sp_addtabletocontents (Transact-SQL) sp_helpsubscriberinfo (Transact-SQL)

sp_adjustpublisheridentityrange (Transact-SQL) sp_helpsubscription (Transact-SQL)

sp_article_validation (Transact-SQL) sp_helpsubscription_properties (Transact-SQL)

sp_articlecolumn (Transact-SQL) sp_helpsubscriptionerrors (Transact-SQL)

sp_articlefilter (Transact-SQL) sp_helptracertokenhistory (Transact-SQL)

sp_articleview (Transact-SQL) sp_helptracertokens (Transact-SQL)

sp_attachsubscription (Transact-SQL) sp_helpxactsetjob (Transact-SQL)

sp_browsemergesnapshotfolder (Transact-SQL) sp_ivindexhasnullcols (Transact-SQL)

sp_browsereplcmds (Transact-SQL) sp_link_publication (Transact-SQL)

sp_browsesnapshotfolder (Transact-SQL) sp_lookupcustomresolver (Transact-SQL)

sp_change_agent_parameter (Transact-SQL) sp_markpendingschemachange (Transact-SQL)

sp_change_agent_profile (Transact-SQL) sp_marksubscriptionvalidation (Transact-SQL)


sp_change_subscription_properties (Transact-SQL) sp_mergearticlecolumn (Transact-SQL)

sp_changearticle (Transact-SQL) sp_mergecleanupmetadata (Transact-SQL)

sp_changearticlecolumndatatype (Transact-SQL) sp_mergedummyupdate (Transact-SQL)

sp_changedistpublisher (Transact-SQL) sp_mergemetadataretentioncleanup (Transact-SQL)

sp_changedistributiondb (Transact-SQL) sp_mergesubscription_cleanup (Transact-SQL)

sp_changedistributor_password (Transact-SQL) sp_MSchange_distribution_agent_properties (Transact-


SQL)

sp_changedistributor_property (Transact-SQL) sp_MSchange_logreader_agent_properties (Transact-SQL)

sp_changedynamicsnapshot_job (Transact-SQL) sp_MSchange_merge_agent_properties (Transact-SQL)

sp_changelogreader_agent (Transact-SQL) sp_MSchange_snapshot_agent_properties (Transact-SQL)

sp_changemergearticle (Transact-SQL) sp_posttracertoken (Transact-SQL)

sp_changemergefilter (Transact-SQL) sp_publication_validation (Transact-SQL)

sp_changemergepublication (Transact-SQL) sp_publisherproperty (Transact-SQL)

sp_changemergepullsubscription (Transact-SQL) sp_redirect_publisher (Transact-SQL)

sp_changemergesubscription (Transact-SQL) sp_refreshsubscriptions (Transact-SQL)

sp_changepublication (Transact-SQL) sp_register_custom_scripting (Transact-SQL)

sp_changepublication_snapshot (Transact-SQL) sp_registercustomresolver (Transact-SQL)

sp_changeqreader_agent (Transact-SQL) sp_reinitmergepullsubscription (Transact-SQL)

sp_changereplicationserverpasswords (Transact-SQL) sp_reinitmergesubscription (Transact-SQL)

sp_changesubscriber (Transact-SQL) sp_reinitpullsubscription (Transact-SQL)

sp_changesubscriber_schedule (Transact-SQL) sp_reinitsubscription (Transact-SQL)

sp_changesubscription (Transact-SQL) sp_removedbreplication (Transact-SQL)

sp_changesubscriptiondtsinfo (Transact-SQL) sp_removedistpublisherdbreplication (Transact-SQL)

sp_changesubstatus (Transact-SQL) sp_repladdcolumn (Transact-SQL)

sp_check_dynamic_filters (Transact-SQL) sp_replcmds (Transact-SQL)

sp_check_for_sync_trigger (Transact-SQL) sp_replcounters (Transact-SQL)


sp_check_join_filter (Transact-SQL) sp_repldone (Transact-SQL)

sp_check_subset_filter (Transact-SQL) sp_repldropcolumn (Transact-SQL)

sp_configure_peerconflictdetection (Transact-SQL) sp_replflush (Transact-SQL)

sp_copymergesnapshot (Transact-SQL) sp_replication_agent_checkup (Transact-SQL)

sp_copysnapshot (Transact-SQL) sp_replicationdboption (Transact-SQL)

sp_copysubscription (Transact-SQL) sp_replmonitorchangepublicationthreshold (Transact-SQL)

sp_deletemergeconflictrow (Transact-SQL) sp_replmonitorhelpmergesession (Transact-SQL)

sp_deletepeerrequesthistory (Transact-SQL) sp_replmonitorhelpmergesessiondetail (Transact-SQL)

sp_deletetracertokenhistory (Transact-SQL) sp_replmonitorhelppublication (Transact-SQL)

sp_drop_agent_parameter (Transact-SQL) sp_replmonitorhelppublicationthresholds (Transact-SQL)

sp_drop_agent_profile (Transact-SQL) sp_replmonitorhelppublisher (Transact-SQL)

sp_dropanonymousagent (Transact-SQL) sp_replmonitorhelpsubscription (Transact-SQL)

sp_droparticle (Transact-SQL) sp_replmonitorsubscriptionpendingcmds (Transact-SQL)

sp_dropdistpublisher (Transact-SQL) sp_replqueuemonitor (Transact-SQL)

sp_dropdistributiondb (Transact-SQL) sp_replrestart (Transact-SQL)

sp_dropdistributor (Transact-SQL) sp_replsetoriginator (Transact-SQL)

sp_dropdynamicsnapshot_job (Transact-SQL) sp_replshowcmds (Transact-SQL)

sp_dropmergealternatepublisher (Transact-SQL) sp_repltrans (Transact-SQL)

sp_dropmergearticle (Transact-SQL) sp_requestpeerresponse (Transact-SQL)

sp_dropmergefilter (Transact-SQL) sp_requestpeertopologyinfo (Transact-SQL)

sp_dropmergepartition (Transact-SQL) sp_resetsnapshotdeliveryprogress (Transact-SQL)

sp_dropmergepublication (Transact-SQL) sp_restoredbreplication (Transact-SQL)

sp_dropmergepullsubscription (Transact-SQL) sp_restoremergeidentityrange (Transact-SQL)

sp_dropmergesubscription (Transact-SQL) sp_resyncmergesubscription (Transact-SQL)

sp_droppublication (Transact-SQL) sp_revoke_publication_access (Transact-SQL)

sp_droppullsubscription (Transact-SQL) sp_schemafilter (Transact-SQL)


sp_dropsubscriber (Transact-SQL) sp_script_synctran_commands (Transact-SQL)

sp_dropsubscription (Transact-SQL) sp_scriptdynamicupdproc (Transact-SQL)

sp_dsninfo (Transact-SQL) sp_scriptpublicationcustomprocs (Transact-SQL)

sp_enumcustomresolvers (Transact-SQL) sp_scriptsubconflicttable (Transact-SQL)

sp_enumdsn (Transact-SQL) sp_setdefaultdatatypemapping (Transact-SQL)

sp_enumeratependingschemachanges (Transact-SQL) sp_setreplfailovermode (Transact-SQL)

sp_expired_subscription_cleanup (Transact-SQL) sp_setsubscriptionxactseqno (Transact-SQL)

sp_generatefilters (Transact-SQL) sp_showpendingchanges (Transact-SQL)

sp_get_distributor (Transact-SQL) sp_showrowreplicainfo (Transact-SQL)

sp_get_redirected_publisher (Transact-SQL) sp_startpublication_snapshot (Transact-SQL)

sp_getagentparameterlist (Transact-SQL) sp_subscription_cleanup (Transact-SQL)

sp_getdefaultdatatypemapping (Transact-SQL) sp_table_validation (Transact-SQL)

sp_getmergedeletetype (Transact-SQL) sp_unregister_custom_scripting (Transact-SQL)

sp_getqueuedrows (Transact-SQL) sp_unregistercustomresolver (Transact-SQL)

sp_getsubscriptiondtspackagename (Transact-SQL) sp_update_agent_profile (Transact-SQL)

sp_gettopologyinfo (Transact-SQL) sp_validate_redirected_publisher (Transact-SQL)

sp_grant_publication_access (Transact-SQL) sp_validate_replica_hosts_as_publishers (Transact-SQL)

sp_help_agent_default (Transact-SQL) sp_validatemergepublication (Transact-SQL)

sp_help_agent_parameter (Transact-SQL) sp_validatemergesubscription (Transact-SQL)

sp_help_agent_profile (Transact-SQL) sp_vupgrade_mergeobjects (Transact-SQL)

sp_helparticle (Transact-SQL) sp_vupgrade_replication (Transact-SQL)

sp_helparticlecolumns (Transact-SQL)

See Also
Replication Management Objects Concepts
Replication Programming Concepts
sp_add_agent_parameter (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a new parameter and its value to an agent profile. This stored procedure is executed at the Distributor on
any database.
Transact-SQL Syntax Conventions

Syntax
sp_add_agent_parameter [ @profile_id = ] profile_id
, [ @parameter_name = ] 'parameter_name'
, [ @parameter_value = ] 'parameter_value'

Arguments
[ @profile_id= ] profile_id
Is the ID of the profile from the MSagent_profiles table in the msdb database. profile_id is int, with no default.
To find out what agent type this profile_id represents, find the profile_id in the MSagent_profiles (Transact-SQL)
table, and note the agent_type field value. The values are as follows:

VALUE DESCRIPTION

1 Snapshot Agent

2 Log Reader Agent

3 Distribution Agent

4 Merge Agent

9 Queue Reader Agent

[ @parameter_name= ] 'parameter_name'
Is the name of the parameter. parameter_name is sysname, with no default. For a list of parameters already
defined in system profiles, see Replication Agent Profiles. For a complete list of valid parameters for each agent,
see the following topics:
Replication Snapshot Agent
Replication Log Reader Agent
Replication Distribution Agent
Replication Merge Agent
Replication Queue Reader Agent
[ @parameter_value=] 'parameter_value'
Is the value to be assigned to the parameter. parameter_value is nvarchar(255), with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_add_agent_parameter is used in snapshot replication, transactional replication, and merge replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_add_agent_parameter.

See Also
Work with Replication Agent Profiles
Replication Agent Profiles
sp_add_agent_profile (Transact-SQL)
sp_change_agent_profile (Transact-SQL)
sp_change_agent_parameter (Transact-SQL)
sp_drop_agent_parameter (Transact-SQL)
sp_help_agent_parameter (Transact-SQL)
sp_add_agent_profile (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a new profile for a replication agent. This stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_add_agent_profile [ [ @profile_id= ] profile_id OUTPUT ]
, [ @profile_name= ] 'profile_name'
, [ @agent_type= ] 'agent_type' ]
[ , [ @profile_type= ] profile_type ]
[ , [ @description= ] 'description' ]
[ , [ @default= ] default ]

Arguments
[ @profile_id= ] profile_id
Is the ID associated with the newly inserted profile. profile_id is int and is an optional OUTPUT parameter. If
specified, the value is set to the new profile ID.
[ @profile_name= ] 'profile_name'
Is the name of the profile. profile_name is sysname, with no default.
[ @agent_type= ] 'agent_type'
Is the type of replication agent. agent_type is int, with no default, and can be one of these values.

VALUE DESCRIPTION

1 Snapshot Agent

2 Log Reader Agent

3 Distribution Agent

4 Merge Agent

9 Queue Reader Agent

[ @profile_type= ] profile_type
Is the type of profile.profile_type is int, with a default of 1.
0 indicates a system profile. 1 indicates a custom profile. Only custom profiles can be created using this stored
procedure; therefore the only valid value is 1. Only Microsoft SQL Server creates system profiles.
[ @description= ] 'description'
Is a description of the profile. description is nvarchar(3000), with no default.
[ @default= ] default
Indicates whether the profile is the default for agent_type. default is bit, with a default of 0. 1 indicates that the
profile being added will become the new default profile for the agent specified by agent_type.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_add_agent_profile is used in snapshot replication, transactional replication, and merge replication.
Custom agent profiles are added with the default agent parameter values. Use sp_change_agent_parameter
(Transact-SQL) to change these default values or sp_add_agent_parameter (Transact-SQL) to add additional
parameters.
When sp_add_agent_profile is executed, a row is added for the new custom profile in the MSagent_profiles
(Transact-SQL) table and the associated default parameters for this profile are added to the MSagent_parameters
(Transact-SQL) table.

Permissions
Only members of the sysadmin fixed server role can execute sp_add_agent_profile.

See Also
Work with Replication Agent Profiles
Replication Agent Profiles
sp_add_agent_parameter (Transact-SQL)
sp_change_agent_parameter (Transact-SQL)
sp_change_agent_profile (Transact-SQL)
sp_drop_agent_parameter (Transact-SQL)
sp_drop_agent_profile (Transact-SQL)
sp_help_agent_parameter (Transact-SQL)
sp_help_agent_profile (Transact-SQL)
sp_addarticle (Transact-SQL)
11/21/2017 • 26 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates an article and adds it to a publication. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_addarticle [ @publication = ] 'publication'
, [ @article = ] 'article'
[ , [ @source_table = ] 'source_table' ]
[ , [ @destination_table = ] 'destination_table' ]
[ , [ @vertical_partition = ] 'vertical_partition' ]
[ , [ @type = ] 'type' ]
[ , [ @filter = ] 'filter' ]
[ , [ @sync_object= ] 'sync_object' ]
[ , [ @ins_cmd = ] 'ins_cmd' ]
[ , [ @del_cmd = ] 'del_cmd' ]
[ , [ @upd_cmd = ] 'upd_cmd' ]
[ , [ @creation_script = ] 'creation_script' ]
[ , [ @description = ] 'description' ]
[ , [ @pre_creation_cmd = ] 'pre_creation_cmd' ]
[ , [ @filter_clause = ] 'filter_clause' ]
[ , [ @schema_option = ] schema_option ]
[ , [ @destination_owner = ] 'destination_owner' ]
[ , [ @status = ] status ]
[ , [ @source_owner = ] 'source_owner' ]
[ , [ @sync_object_owner = ] 'sync_object_owner' ]
[ , [ @filter_owner = ] 'filter_owner' ]
[ , [ @source_object = ] 'source_object' ]
[ , [ @artid = ] article_ID OUTPUT ]
[ , [ @auto_identity_range = ] 'auto_identity_range' ]
[ , [ @pub_identity_range = ] pub_identity_range ]
[ , [ @identity_range = ] identity_range ]
[ , [ @threshold = ] threshold ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @use_default_datatypes = ] use_default_datatypes
[ , [ @identityrangemanagementoption = ] identityrangemanagementoption ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @fire_triggers_on_snapshot = ] 'fire_triggers_on_snapshot' ]

Arguments
[ @publication = ] 'publication'
Is the name of the publication that contains the article. The name must be unique in the database. publication is
sysname, with no default.
[ @article = ] 'article'
Is the name of the article. The name must be unique within the publication. article is sysname, with no default.
[ @source_table = ] 'source_table'
This parameter has been deprecated; use source_object instead.
This parameter is not supported for Oracle Publishers.
[ @destination_table = ] 'destination_table'
Is the name of the destination (subscription) table, if different from source_tableor the stored procedure.
destination_table is sysname, with a default of NULL, which means that source_table equals destination_table.
[ @vertical_partition = ] 'vertical_partition'
Enables and disables column filtering on a table article. vertical_partition is nchar(5), with a default of FALSE.
false indicates there is no vertical filtering and publishes all columns.
true clears all columns except the declared primary key, nullable columns with no default, and unique key
columns. Columns are added using sp_articlecolumn.
[ @type = ] 'type'
Is the type of article. type is sysname, and can be one of the following values.

VALUE DESCRIPTION

aggregate schema only Aggregate function with schema only.

func schema only Function with schema only.

indexed view logbased Log-based indexed view article. Not supported for Oracle
Publishers. For this type of article, the base table does not
need to be published separately.

indexed view logbased manualboth Log-based indexed view article with manual filter and manual
view. This option requires that you specify both sync_object
and filter parameters. For this type of article, the base table
does not need to be published separately. Not supported for
Oracle Publishers.

indexed view logbased manualfilter Log-based indexed view article with manual filter. This option
requires that you specify both sync_object and filter
parameters. For this type of article, the base table does not
need to be published separately. Not supported for Oracle
Publishers.

indexed view logbased manualview Log-based indexed view article with manual view. This option
requires that you specify the sync_object parameter. For this
type of article, the base table does not need to be published
separately. Not supported for Oracle Publishers.

indexed view schema only Indexed view with schema only. For this type of article, the
base table must also be published.

logbased (default) Log-based article.

logbased manualboth Log-based article with manual filter and manual view. This
option requires that you specify both sync_object and filter
parameters. Not supported for Oracle Publishers.

logbased manualfilter Log-based article with manual filter. This option requires that
you specify both sync_object and filter parameters. Not
supported for Oracle Publishers.
VALUE DESCRIPTION

logbased manualview Log-based article with manual view. This option requires that
you specify the sync_object parameter. Not supported for
Oracle Publishers.

proc exec Replicates the execution of the stored procedure to all


Subscribers of the article. Not supported for Oracle
Publishers. We recommend that you use the option
serializable proc exec instead of proc exec. For more
information, see the section "Types of Stored Procedure
Execution Articles" in Publishing Stored Procedure Execution
in Transactional Replication. Not available when change data
capture is enabled.

proc schema only Procedure with schema only. Not supported for Oracle
Publishers.

serializable proc exec Replicates the execution of the stored procedure only if it is
executed within the context of a serializable transaction. Not
supported for Oracle Publishers.

The procedure also must be executed inside an explicit


transaction for the procedure execution to be replicated.

view schema only View with schema only. Not supported for Oracle Publishers.
When using this option, you must also publish the base
table.

[ @filter = ] 'filter'
Is the stored procedure (created with FOR REPLICATION) used to filter the table horizontally. filter is
nvarchar(386), with a default of NULL. sp_articleview and sp_articlefilter must be executed manually to create
the view and filter stored procedure. If not NULL, the filter procedure is not created (assumes the stored
procedure is created manually).
[ @sync_object = ] 'sync_object'
Is the name of the table or view used for producing the data file used to represent the snapshot for this article.
sync_object is nvarchar(386), with a default of NULL. If NULL, sp_articleview is called to automatically create the
view used to generate the output file. This occurs after adding any columns with sp_articlecolumn. If not NULL, a
view is not created (assumes the view is manually created).
[ @ins_cmd = ] 'ins_cmd'
Is the replication command type used when replicating inserts for this article. ins_cmd is nvarchar(255), and can
be one of the following values.

VALUE DESCRIPTION

NONE No action is taken.


VALUE DESCRIPTION

CALL sp_MSins_ Calls a stored procedure to be executed at the Subscriber. To


table (default) use this method of replication, use schema_option to specify
automatic creation of the stored procedure, or create the
-or- specified stored procedure in the destination database of
each Subscriber of the article. custom_stored_procedure is
CALL custom_stored_procedure_name the name of a user-created stored procedure.
sp_MSins_*table* contains the name of the destination table
in place of the _table part of the parameter. When
destination_owner is specified, it is prepended to the
destination table name. For example, for the
ProductCategory table owned by the Production schema
at the Subscriber, the parameter would be
CALL sp_MSins_ProductionProductCategory . For an article
in a peer-to-peer replication topology, _table is appended
with a GUID value. Specifying custom_stored_procedure is
not supported for updating subscribers.

SQL or NULL Replicates an INSERT statement. The INSERT statement is


provided values for all columns published in the article. This
command is replicated on inserts:

INSERT INTO <table name> VALUES (c1value, c2value,


c3value, ..., cnvalue)

For more information, see Specify How Changes Are Propagated for Transactional Articles.
[ @del_cmd =] 'del_cmd'
Is the replication command type used when replicating deletes for this article. del_cmd is nvarchar(255), and can
be one of the following values.

VALUE DESCRIPTION

NONE No action is taken.

CALLsp_MSdel_ Calls a stored procedure to be executed at the Subscriber. To


table (default) use this method of replication, use schema_option to specify
automatic creation of the stored procedure, or create the
-or- specified stored procedure in the destination database of
each Subscriber of the article. custom_stored_procedure is
CALL custom_stored_procedure_name the name of a user-created stored procedure.
sp_MSdel_*table* contains the name of the destination
table in place of the _table part of the parameter. When
destination_owner is specified, it is prepended to the
destination table name. For example, for the
ProductCategory table owned by the Production schema
at the Subscriber, the parameter would be
CALL sp_MSdel_ProductionProductCategory . For an article
in a peer-to-peer replication topology, _table is appended
with a GUID value. Specifying custom_stored_procedure is
not supported for updating subscribers.

XCALL sp_MSdel_ Calls a stored procedure taking XCALL style parameters. To


table use this method of replication, use schema_option to specify
automatic creation of the stored procedure, or create the
-or- specified stored procedure in the destination database of
each Subscriber of the article. Specifying a user-created
XCALL custom_stored_procedure_name stored procedure is not allowed for updating subscribers.
VALUE DESCRIPTION

SQL or NULL Replicates a DELETE statement. The DELETE statement is


provided all primary key column values. This command is
replicated on deletes:

DELETE FROM <table name> WHERE pkc1 = pkc1value AND


pkc2 = pkc2value AND pkcn = pkcnvalue

For more information, see Specify How Changes Are Propagated for Transactional Articles.
[ @upd_cmd =] 'upd_cmd'
Is the replication command type used when replicating updates for this article. upd_cmd is nvarchar(255), and
can be one of the following values.

VALUE DESCRIPTION

NONE No action is taken.

CALL sp_MSupd_ Calls a stored procedure to be executed at the Subscriber. To


table use this method of replication, use schema_option to specify
automatic creation of the stored procedure, or create the
-or- specified stored procedure in the destination database of
each Subscriber of the article.
CALL custom_stored_procedure_name

MCALL sp_MSupd_ Calls a stored procedure taking MCALL style parameters. To


table use this method of replication, use schema_option to specify
automatic creation of the stored procedure, or create the
-or- specified stored procedure in the destination database of
each Subscriber of the article. custom_stored_procedure is
MCALL custom_stored_procedure_name the name of a user-created stored procedure.
sp_MSupd_*table* contains the name of the destination
table in place of the _table part of the parameter. When
destination_owner is specified, it is prepended to the
destination table name. For example, for the
ProductCategory table owned by the Production schema
at the Subscriber, the parameter would be
MCALL sp_MSupd_ProductionProductCategory . For an
article in a peer-to-peer replication topology, _table is
appended with a GUID value. Specifying a user-created
stored procedure is not allowed for updating subscribers.

SCALL sp_MSupd_ Calls a stored procedure taking SCALL style parameters. To


table (default) use this method of replication, use schema_option to specify
automatic creation of the stored procedure, or create the
-or- specified stored procedure in the destination database of
each Subscriber of the article. custom_stored_procedure is
SCALL custom_stored_procedure_name the name of a user-created stored procedure.
sp_MSupd_*table* contains the name of the destination
table in place of the _table part of the parameter. When
destination_owner is specified, it is prepended to the
destination table name. For example, for the
ProductCategory table owned by the Production schema
at the Subscriber, the parameter would be
SCALL sp_MSupd_ProductionProductCategory . For an
article in a peer-to-peer replication topology, _table is
appended with a GUID value. Specifying a user-created
stored procedure is not allowed for updating subscribers.
VALUE DESCRIPTION

XCALL sp_MSupd_ Calls a stored procedure taking XCALL style parameters. To


table use this method of replication, use schema_option to specify
automatic creation of the stored procedure, or create the
-or- specified stored procedure in the destination database of
each Subscriber of the article. Specifying a user-created
XCALL custom_stored_procedure_name stored procedure is not allowed for updating subscribers.

SQL or NULL Replicates an UPDATE statement. The UPDATE statement is


provided on all column values and the primary key column
values. This command is replicated on updates:

UPDATE <table name> SET c1 = c1value, SET c2 =


c2value, SET cn = cnvalue WHERE pkc1 = pkc1value AND
pkc2 = pkc2value AND pkcn = pkcnvalue

NOTE
The CALL, MCALL, SCALL, and XCALL syntax vary the amount of data propagated to the subscriber. The CALL syntax
passes all values for all inserted and deleted columns. The SCALL syntax passes values only for affected columns. The
XCALL syntax passes values for all columns, whether changed or not, including the previous value of the column. For more
information, see Specify How Changes Are Propagated for Transactional Articles.

[ @creation_script =] 'creation_script'
Is the path and name of an optional article schema script used to create the article in the subscription database.
creation_script is nvarchar(255), with a default of NULL.
[ @description =] 'description'
Is a descriptive entry for the article. description is nvarchar(255), with a default of NULL.
[ @pre_creation_cmd =] 'pre_creation_cmd'
Specifies what the system should do if it detects an existing object of the same name at the subscriber when
applying the snapshot for this article. pre_creation_cmd is nvarchar(10), and can be one of the following values.

VALUE DESCRIPTION

none Does not use a command.

delete Deletes data from the destination table before applying the
snapshot. When the article is horizontally filtered, only data in
columns specified by the filter clause is deleted. Not
supported for Oracle Publishers when a horizontal filter is
defined.

drop (default) Drops the destination table.

truncate Truncates the destination table. Is not valid for ODBC or OLE
DB Subscribers.

[ @filter_clause=] 'filter_clause'
Is a restriction (WHERE) clause that defines a horizontal filter. When entering the restriction clause, omit the
keyword WHERE. filter_clause is ntext, with a default of NULL. For more information, see Filter Published Data.
[ @schema_option =] schema_option
Is a bitmask of the schema generation option for the given article. schema_option is binary(8), and can be the |
(Bitwise OR) product of one or more of these values:
NOTE
If this value is NULL, the system auto-generates a valid schema option for the article depending on other article properties.
The Default Schema Options table given in the Remarks shows the value that will be chosen based upon the combination
of the article type and the replication type.

VALUE DESCRIPTION

0x00 Disables scripting by the Snapshot Agent and uses


creation_script.

0x01 Generates the object creation script (CREATE TABLE, CREATE


PROCEDURE, and so on). This value is the default for stored
procedure articles.

0x02 Generates the stored procedures that propagate changes for


the article, if defined.

0x04 Identity columns are scripted using the IDENTITY property.

0x08 Replicate timestamp columns. If not set, timestamp


columns are replicated as binary.

0x10 Generates a corresponding clustered index. Even if this


option is not set, indexes related to primary keys and unique
constraints are generated if they are already defined on a
published table.

0x20 Converts user-defined data types (UDT) to base data types at


the Subscriber. This option cannot be used when there is a
CHECK or DEFAULT constraint on a UDT column, if a UDT
column is part of the primary key, or if a computed column
references a UDT column. Not supported for Oracle
Publishers.

0x40 Generates corresponding nonclustered indexes. Even if this


option is not set, indexes related to primary keys and unique
constraints are generated if they are already defined on a
published table.

0x80 Replicates primary key constraints. Any indexes related to the


constraint are also replicated, even if options 0x10 and 0x40
are not enabled.

0x100 Replicates user triggers on a table article, if defined. Not


supported for Oracle Publishers.

0x200 Replicates foreign key constraints. If the referenced table is


not part of a publication, all foreign key constraints on a
published table are not replicated. Not supported for Oracle
Publishers.

0x400 Replicates check constraints. Not supported for Oracle


Publishers.

0x800 Replicates defaults. Not supported for Oracle Publishers.


VALUE DESCRIPTION

0x1000 Replicates column-level collation.

Note: This option should be set for Oracle Publishers to


enable case-sensitive comparisons.

0x2000 Replicates extended properties associated with the published


article source object. Not supported for Oracle Publishers.

0x4000 Replicates UNIQUE constraints. Any indexes related to the


constraint are also replicated, even if options 0x10 and 0x40
are not enabled.

0x8000 This option is not valid for SQL Server 2005 Publishers.

0x10000 Replicates CHECK constraints as NOT FOR REPLICATION so


that the constraints are not enforced during synchronization.

0x20000 Replicates FOREIGN KEY constraints as NOT FOR


REPLICATION so that the constraints are not enforced during
synchronization.

0x40000 Replicates filegroups associated with a partitioned table or


index.

0x80000 Replicates the partition scheme for a partitioned table.

0x100000 Replicates the partition scheme for a partitioned index.

0x200000 Replicates table statistics.

0x400000 Default Bindings

0x800000 Rule Bindings

0x1000000 Full-text index

0x2000000 XML schema collections bound to xml columns are not


replicated.

0x4000000 Replicates indexes on xml columns.

0x8000000 Create any schemas not already present on the subscriber.

0x10000000 Converts xml columns to ntext on the Subscriber.

0x20000000 Converts large object data types (nvarchar(max),


varchar(max), and varbinary(max)) introduced in SQL
Server 2005 to data types that are supported on SQL Server
2000.

0x40000000 Replicate permissions.


VALUE DESCRIPTION

0x80000000 Attempt to drop dependencies to any objects that are not


part of the publication.

0x100000000 Use this option to replicate the FILESTREAM attribute if it is


specified on varbinary(max) columns. Do not specify this
option if you are replicating tables to SQL Server 2005
Subscribers. Replicating tables that have FILESTREAM
columns to SQL Server 2000 Subscribers is not supported,
regardless of how this schema option is set.

See related option 0x800000000.

0x200000000 Converts date and time data types (date, time,


datetimeoffset, and datetime2) introduced in SQL Server
2008 to data types that are supported on earlier versions of
SQL Server.

0x400000000 Replicates the compression option for data and indexes. For
more information, see Data Compression.

0x800000000 Set this option to store FILESTREAM data on its own


filegroup at the Subscriber. If this option is not set,
FILESTREAM data is stored on the default filegroup.
Replication does not create filegroups; therefore, if you set
this option, you must create the filegroup before you apply
the snapshot at the Subscriber. For more information about
how to create objects before you apply the snapshot, see
Execute Scripts Before and After the Snapshot Is Applied.

See related option 0x100000000.

0x1000000000 Converts common language runtime (CLR) user-defined


types (UDTs) that are larger than 8000 bytes to
varbinary(max) so that columns of type UDT can be
replicated to Subscribers that are running SQL Server 2005.

0x2000000000 Converts the hierarchyid data type to varbinary(max) so


that columns of type hierarchyid can be replicated to
Subscribers that are running SQL Server 2005. For more
information about how to use hierarchyid columns in
replicated tables, see hierarchyid (Transact-SQL).

0x4000000000 Replicates any filtered indexes on the table. For more


information about filtered indexes, see Create Filtered
Indexes.

0x8000000000 Converts the geography and geometry data types to


varbinary(max) so that columns of these types can be
replicated to Subscribers that are running SQL Server 2005.

0x10000000000 Replicates indexes on columns of type geography and


geometry.

0x20000000000 Replicates the SPARSE attribute for columns. For more


information about this attribute, see Use Sparse Columns.
VALUE DESCRIPTION

0x40000000000 Enable scripting by the snapshot agent to create memory-


optimized table on the subscriber.

0x80000000000 Converts clustered index to nonclustered index for memory-


optimized articles.

0x400000000000 Replicates any non-clustered columnstore indexes on the


table(s)

0x800000000000 Replicates any flitered non-clustered columnstore indexes on


the table(s).

NULL Replication automatically sets schema_option to a default


value, the value of which depends on other article properties.
The "Default Schema Options" table in the Remarks section
shows the default schema options based on article type and
replication type.

The default for non- SQL Server publications is 0x050D3.

Not all schema_option values are valid for every type of replication and article type. The Valid Schema Options
table in the Remarks section shows the valid schema options that can be chosen based upon the combination of
the article type and the replication type.
[ @destination_owner =] 'destination_owner'
Is the name of the owner of the destination object. destination_owner is sysname, with a default of NULL. When
destination_owner is not specified, the owner is specified automatically based on the following rules:

CONDITION DESTINATION OBJECT OWNER

Publication uses native-mode bulk copy to generate the Defaults to the value of source_owner.
initial snapshot, which only supports SQL Server Subscribers.

Published from a non- SQL Server Publisher. Defaults to the owner of the destination database.

Publication uses character-mode bulk copy to generate the Not assigned.


initial snapshot, which supports non- SQL Server Subscribers.

To support non- SQL Server Subscribers, destination_owner must be NULL.


[ @status=] status
Specifies if the article is active and additional options for how changes are propagated. status is tinyint, and can
be the | (Bitwise OR) product of one or more of these values.

VALUE DESCRIPTION

1 Article is active.

8 Includes the column name in INSERT statements.

16 (default) Uses parameterized statements.


VALUE DESCRIPTION

24 Includes the column name in INSERT statements and uses


parameterized statements.

64 Identified for informational purposes only. Not supported.


Future compatibility is not guaranteed.

For example, an active article using parameterized statements would have a value of 17 in this column. A value of
0 means that the article is inactive and no additional properties are defined.
[ @source_owner =] 'source_owner'
Is the owner of the source object. source_owner is sysname, with a default of NULL. source_owner must be
specified for Oracle Publishers.
[ @sync_object_owner =] 'sync_object_owner'
Is the owner of the view that defines the published article. sync_object_owner is sysname, with a default of NULL.
[ @filter_owner =] 'filter_owner'
Is the owner of the filter. filter_owner is sysname, with a default of NULL.
[ @source_object =] 'source_object'
Is the database object to be published. source_object is sysname, with a default of NULL. If source_table is NULL,
source_object cannot be NULL.source_object should be used instead of source_table. For more information about
the types of objects that can be published using snapshot or transactional replication, see Publish Data and
Database Objects.
[ @artid = ] article_ID OUTPUT
Is the article ID of the new article. article_ID is int with a default of NULL, and it is an OUTPUT parameter.
[ @auto_identity_range = ] 'auto_identity_range'
Enables and disables automatic identity range handling on a publication at the time it is created.
auto_identity_range is nvarchar(5), and can be one of the following values:

VALUE DESCRIPTION

true Enables automatic identity range handling

false Disables automatic identity range handling

NULL(default) Identity range handling is set by


identityrangemanagementoption.

NOTE
auto_identity_range has been deprecated and is provided for backward compatibility only. You should use
identityrangemanagementoption for specifying identity range management options. For more information, see Replicate
Identity Columns.

[ @pub_identity_range = ] pub_identity_range
Controls the range size at the Publisher if the article has identityrangemanagementoption set to auto or
auto_identity_range set to true. pub_identity_range is bigint, with a default of NULL. Not supported for Oracle
Publishers.
[ @identity_range = ] identity_range
Controls the range size at the Subscriber if the article has identityrangemanagementoption set to auto or
auto_identity_range set to true. identity_range is bigint, with a default of NULL. Used when auto_identity_range
is set to true. Not supported for Oracle Publishers.
[ @threshold = ] threshold
Is the percentage value that controls when the Distribution Agent assigns a new identity range. When the
percentage of values specified in threshold is used, the Distribution Agent creates a new identity range. threshold
is bigint, with a default of NULL. Used when identityrangemanagementoption is set to auto or
auto_identity_range is set to true. Not supported for Oracle Publishers.
[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure may invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default of 0.
0 specifies that adding an article does not cause the snapshot to be invalid. If the stored procedure detects that
the change requires a new snapshot, an error occurs and no changes are made.
1 specifies that adding an article may cause the snapshot to be invalid, and if subscriptions exist that would
require a new snapshot, gives permission for the existing snapshot to be marked as obsolete and a new snapshot
to be generated.
[ @use_default_datatypes = ] use_default_datatypes
Is whether the default column data type mappings are used when publishing an article from an Oracle Publisher.
use_default_datatypes is bit, with a default of 1.
1 = the default article column mappings are used. The default data type mappings can be displayed by executing
sp_getdefaultdatatypemapping.
0 = custom article column mappings are defined, and therefore sp_articleview is not called by sp_addarticle.
When use_default_datatypes is set to 0, you must execute sp_changearticlecolumndatatype once for each column
mapping being changed from the default. After all custom column mappings have been defined, you must
execute sp_articleview.

NOTE
This parameter should only be used for Oracle Publishers. Setting use_default_datatypes to 0 for a SQL Server Publisher
generates an error.

[ @identityrangemanagementoption = ] identityrangemanagementoption
Specifies how identity range management is handled for the article. identityrangemanagementoption is
nvarchar(10), and can be one of the following values.

VALUE DESCRIPTION

none Replication does no explicit identity range management. This


option is recommended only for backwards compatibility with
earlier versions of SQL Server. Not allowed for peer
replication.

manual Marks the identity column using NOT FOR REPLICATION to


enable manual identity range handling.

auto Specifies automatic management of identity ranges.


VALUE DESCRIPTION

NULL(default) Defaults to none when the value of auto_identity_range is


not true. Defaults to manual in a peer-to-peer topology
default (auto_identity_range is ignored).

For backward compatibility, when the value of identityrangemanagementoption is NULL, the value of
auto_identity_range is checked. However, when the value of identityrangemanagementoption is not NULL, then
the value of auto_identity_range is ignored.
For more information, see Replicate Identity Columns.
[ @publisher = ] 'publisher'
Specifies a non- SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when adding an article to a SQL Server Publisher.

[ @fire_triggers_on_snapshot = ] 'fire_triggers_on_snapshot'
Is if replicated user triggers are executed when the initial snapshot is applied. fire_triggers_on_snapshot is
nvarchar(5), with a default of FALSE. true means that user triggers on a replicated table are executed when the
snapshot is applied. In order for triggers to be replicated, the bitmask value of schema_option must include the
value 0x100.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addarticle is used in snapshot replication or transactional replication.
By default, replication does not publish any columns in the source table when the column data type is not
supported by replication. If you need to publish such a column, you must execute sp_articlecolumn to add the
column.
When adding an article to a publication that supports peer-to-peer transactional replication, the following
restrictions apply:
Parameterized statements must be specified for all logbased articles. You must include 16 in the status
value.
Name and owner of the destination table must match the source table.
The article cannot be filtered horizontally or vertically.
Automatic identity range management is not supported. You must specify a value of manual for
identityrangemanagementoption.
If a timestamp column exists in the table, you must include 0x08 in schema_option to replicate the
column as timestamp.
A value of SQL cannot be specified for ins_cmd, upd_cmd, and del_cmd.
For more information, see Peer-to-Peer Transactional Replication.
When you publish objects, their definitions are copied to Subscribers. If you are publishing a database
object that depends on one or more other objects, you must publish all referenced objects. For example, if
you publish a view that depends on a table, you must publish the table also.
If vertical_partition is set to true, sp_addarticle defers the creation of the view until sp_articleview is
called (after the last sp_articlecolumn is added).
If the publication allows updating subscriptions and the published table does not have a uniqueidentifier
column, sp_addarticle adds a uniqueidentifier column to the table automatically.
When replicating to a subscriber that is not an instance of SQL Server (heterogeneous replication), only
Transact-SQL statements are supported for INSERT, UPDATE, and DELETE commands.
When the log reader agent is running, adding an article to a peer-to-peer publication can cause a deadlock
between the log reader agent and the process that adds the article. To avoid this issue, before adding an
article to a peer-to-peer publication use the Replication Monitor to stop the log reader agent on the node
where you are adding the article. Restart the log reader agent after adding the article.
When setting @del_cmd = 'NONE' or @ins_cmd = 'NONE' , the propagation of UPDATE commands might
also be affected by not sending those commands when a bounded update occurs. (A bounded update is
type of UPDATE statement from the publisher that replicates as a DELETE/INSERT pair on the subscriber.)

Default Schema Options


This table describes the default value set by replication if schema_options is not specified by the user, where this
value depends on the replication type (shown across the top) and the article type (shown down the first column).

ARTICLE TYPE REPLICATION TYPE

Transactional Snapshot

aggregate schema only 0x01 0x01

func schema only 0x01 0x01

indexed view schema only 0x01 0x01

indexed view logbased 0x30F3 0x3071

indexed view logbase manualboth 0x30F3 0x3071

indexed view logbased manualfilter 0x30F3 0x3071

indexed view logbased manualview 0x30F3 0x3071

logbased 0x30F3 0x3071

logbased manualfilter 0x30F3 0x3071

logbased manualview 0x30F3 0x3071

proc exec 0x01 0x01

proc schema only 0x01 0x01


ARTICLE TYPE REPLICATION TYPE

serializable proc exec 0x01 0x01

view schema only 0x01 0x01

NOTE
If a publication is enabled for queued updating, a schema_option value of 0x80 is added to the default value shown in the
table. The default schema_option for a non- SQL Server publication is 0x050D3.

Valid Schema Options


This table describes the allowable values of schema_option based upon the replication type (shown across the
top) and the article type (shown down the first column).

ARTICLE TYPE REPLICATION TYPE

Transactional Snapshot

logbased All options All options but 0x02

logbased manualfilter All options All options but 0x02

logbased manualview All options All options but 0x02

indexed view logbased All options All options but 0x02

indexed view logbased manualfilter All options All options but 0x02

indexed view logbased manualview All options All options but 0x02

indexed view logbase manualboth All options All options but 0x02

proc exec 0x01, 0x20, 0x2000, 0x400000, 0x01, 0x20, 0x2000, 0x400000,
0x800000, 0x2000000, 0x8000000, 0x800000, 0x2000000, 0x8000000,
0x10000000, 0x20000000, 0x10000000, 0x20000000,
0x40000000, and 0x80000000 0x40000000, and 0x80000000

serializable proc exec 0x01, 0x20, 0x2000, 0x400000, 0x01, 0x20, 0x2000, 0x400000,
0x800000, 0x2000000, 0x8000000, 0x800000, 0x2000000, 0x8000000,
0x10000000, 0x20000000, 0x10000000, 0x20000000,
0x40000000, and 0x80000000 0x40000000, and 0x80000000

proc schema only 0x01, 0x20, 0x2000, 0x400000, 0x01, 0x20, 0x2000, 0x400000,
0x800000, 0x2000000, 0x8000000, 0x800000, 0x2000000, 0x8000000,
0x10000000, 0x20000000, 0x10000000, 0x20000000,
0x40000000, and 0x80000000 0x40000000, and 0x80000000

view schema only 0x01, 0x010, 0x020, 0x040, 0x0100, 0x01, 0x010, 0x020, 0x040, 0x0100,
0x2000, 0x40000, 0x100000, 0x2000, 0x40000, 0x100000,
0x200000, 0x400000, 0x800000, 0x200000, 0x400000, 0x800000,
0x2000000, 0x8000000, 0x40000000, 0x2000000, 0x8000000, 0x40000000,
and 0x80000000 and 0x80000000
ARTICLE TYPE REPLICATION TYPE

func schema only 0x01, 0x20, 0x2000, 0x400000, 0x01, 0x20, 0x2000, 0x400000,
0x800000, 0x2000000, 0x8000000, 0x800000, 0x2000000, 0x8000000,
0x10000000, 0x20000000, 0x10000000, 0x20000000,
0x40000000, and 0x80000000 0x40000000, and 0x80000000

indexed view schema only 0x01, 0x010, 0x020, 0x040, 0x0100, 0x01, 0x010, 0x020, 0x040, 0x0100,
0x2000, 0x40000, 0x100000, 0x2000, 0x40000, 0x100000,
0x200000, 0x400000, 0x800000, 0x200000, 0x400000, 0x800000,
0x2000000, 0x8000000, 0x40000000, 0x2000000, 0x8000000, 0x40000000,
and 0x80000000 and 0x80000000

NOTE
For queued updating publications, the schema_option values of 0x8000 and 0x80 must be enabled. The supported
schema_option values for non- SQL Server publications are: 0x01, 0x02, 0x10, 0x40, 0x80, 0x1000, 0x4000 and 0X8000.

Example
DECLARE @publication AS sysname;
DECLARE @table AS sysname;
DECLARE @filterclause AS nvarchar(500);
DECLARE @filtername AS nvarchar(386);
DECLARE @schemaowner AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @table = N'Product';
SET @filterclause = N'[DiscontinuedDate] IS NULL';
SET @filtername = N'filter_out_discontinued';
SET @schemaowner = N'Production';

-- Add a horizontally and vertically filtered article for the Product table.
-- Manually set @schema_option to ensure that the Production schema
-- is generated at the Subscriber (0x8000000).
EXEC sp_addarticle
@publication = @publication,
@article = @table,
@source_object = @table,
@source_owner = @schemaowner,
@schema_option = 0x80030F3,
@vertical_partition = N'true',
@type = N'logbased',
@filter_clause = @filterclause;

-- (Optional) Manually call the stored procedure to create the


-- horizontal filtering stored procedure. Since the type is
-- 'logbased', this stored procedures is executed automatically.
EXEC sp_articlefilter
@publication = @publication,
@article = @table,
@filter_clause = @filterclause,
@filter_name = @filtername;

-- Add all columns to the article.


EXEC sp_articlecolumn
@publication = @publication,
@article = @table;

-- Remove the DaysToManufacture column from the article


EXEC sp_articlecolumn
@publication = @publication,
@article = @table,
@column = N'DaysToManufacture',
@operation = N'drop';

-- (Optional) Manually call the stored procedure to create the


-- vertical filtering view. Since the type is 'logbased',
-- this stored procedures is executed automatically.
EXEC sp_articleview
@publication = @publication,
@article = @table,
@filter_clause = @filterclause;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addarticle.

See Also
Define an Article
sp_articlecolumn (Transact-SQL)
sp_articlefilter (Transact-SQL)
sp_articleview (Transact-SQL)
sp_changearticle (Transact-SQL)
sp_droparticle (Transact-SQL)
sp_helparticle (Transact-SQL)
sp_helparticlecolumns (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
Publish Data and Database Objects
sp_adddistpublisher (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Configures a Publisher to use a specified distribution database. This stored procedure is executed at the
Distributor on any database. Note that the stored procedures sp_adddistributor (Transact-SQL) and
sp_adddistributiondb (Transact-SQL) must have been run prior to using this stored procedure.
Transact-SQL Syntax Conventions

Syntax
sp_adddistpublisher [ @publisher= ] 'publisher'
, [ @distribution_db= ] 'distribution_db'
[ , [ @security_mode= ] security_mode ]
[ , [ @login= ] 'login' ]
[ , [ @password= ] 'password' ]
[ , [ @working_directory= ] 'working_directory' ]
[ , [ @trusted= ] 'trusted' ]
[ , [ @encrypted_password= ] encrypted_password ]
[ , [ @thirdparty_flag = ] thirdparty_flag ]
[ , [ @publisher_type = ] 'publisher_type' ]

Arguments
[ @publisher=] 'publisher'
Is the Publisher name. publisher is sysname, with no default.
[ @distribution_db=] 'distribution_db'
Is the name of the distribution database. distributor_db is sysname, with no default. This parameter is used by
replication agents to connect to the Publisher.
[ @security_mode=] security_mode
Is the implemented security mode. This parameter is only used by replication agents to connect to the Publisher
for queued updating subscriptions or with a non- SQL Server Publisher. security_mode is int, and can be one of
these values.

VALUE DESCRIPTION

0 Replication agents at the Distributor use SQL Server


Authentication to connect to the Publisher.

1 (default) Replication agents at the Distributor use Windows


Authentication to connect to the Publisher.

[ @login=] 'login'
Is the login. This parameter is required if security_mode is 0. login is sysname, with a default of NULL. This
parameter is used by replication agents to connect to the Publisher.
[ @password=] 'password']
Is the password. password is sysname, with a default of NULL. This parameter is used by replication agents to
connect to the Publisher.

IMPORTANT
Do not use a blank password. Use a strong password.

[ @working_directory=] 'working_directory'
Is the name of the working directory used to store data and schema files for the publication. working_directory is
nvarchar(255), and defaults to the ReplData folder for this instance of SQL Server, for example 'C:\Program
Files\Microsoft SQL Server\MSSQL\MSSQ.1\ReplData'. The name should be specified in UNC format.
[ @trusted=] 'trusted'
This parameter has been deprecated and is provided for backward compatibility only. trusted is nvarchar(5), and
setting it to anything but false will result in an error.
[ @encrypted_password=] encrypted_password
Setting encrypted_password is no longer supported. Attempting to set this bit parameter to 1 will result in an
error.
[ @thirdparty_flag =] thirdparty_flag
Is when the Publisher is SQL Server. thirdparty_flag is bit, and can be one of the following values.

VALUE DESCRIPTION

0 (default) SQL Server database.

1 Database other than SQL Server.

[ @publisher_type= ] 'publisher_type'
Specifies the Publisher type when the Publisher is not SQL Server. publisher_type is sysname, and can be one of
the following values.

VALUE DESCRIPTION

MSSQLSERVER Specifies a SQL Server Publisher.

(default)

ORACLE Specifies a standard Oracle Publisher.

ORACLE GATEWAY Specifies an Oracle Gateway Publisher.

For more information about the differences between an Oracle Publisher and an Oracle Gateway Publisher, see
Configure an Oracle Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_adddistpublisher is used by snapshot replication, transactional replication, and merge replication.
Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Install the Distributor and the distribution database.


DECLARE @distributor AS sysname;
DECLARE @distributionDB AS sysname;
DECLARE @publisher AS sysname;
DECLARE @directory AS nvarchar(500);
DECLARE @publicationDB AS sysname;
-- Specify the Distributor name.
SET @distributor = $(DistPubServer);
-- Specify the distribution database.
SET @distributionDB = N'distribution';
-- Specify the Publisher name.
SET @publisher = $(DistPubServer);
-- Specify the replication working directory.
SET @directory = N'\\' + $(DistPubServer) + '\repldata';
-- Specify the publication database.
SET @publicationDB = N'AdventureWorks2012';

-- Install the server MYDISTPUB as a Distributor using the defaults,


-- including autogenerating the distributor password.
USE master
EXEC sp_adddistributor @distributor = @distributor;

-- Create a new distribution database using the defaults, including


-- using Windows Authentication.
USE master
EXEC sp_adddistributiondb @database = @distributionDB,
@security_mode = 1;
GO

-- Create a Publisher and enable AdventureWorks2012 for replication.


-- Add MYDISTPUB as a publisher with MYDISTPUB as a local distributor
-- and use Windows Authentication.
DECLARE @distributionDB AS sysname;
DECLARE @publisher AS sysname;
-- Specify the distribution database.
SET @distributionDB = N'distribution';
-- Specify the Publisher name.
SET @publisher = $(DistPubServer);

USE [distribution]
EXEC sp_adddistpublisher @publisher=@publisher,
@distribution_db=@distributionDB,
@security_mode = 1;
GO

Permissions
Only members of the sysadmin fixed server role can execute sp_adddistpublisher.

See Also
Configure Publishing and Distribution
sp_changedistpublisher (Transact-SQL)
sp_dropdistpublisher (Transact-SQL)
sp_helpdistpublisher (Transact-SQL)
System Stored Procedures (Transact-SQL)
Configure Distribution
sp_adddistributiondb (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a new distribution database and installs the Distributor schema. The distribution database stores
procedures, schema, and metadata used in replication. This stored procedure is executed at the Distributor on the
master database in order to create the distribution database, and install the necessary tables and stored
procedures required to enable the replication distribution.
Transact-SQL Syntax Conventions

Syntax
sp_adddistributiondb [ @database= ] 'database'
[ , [ @data_folder= ] 'data_folder' ]
[ , [ @data_file= ] 'data_file' ]
[ , [ @data_file_size= ] data_file_size ]
[ , [ @log_folder= ] 'log_folder' ]
[ , [ @log_file= ] 'log_file' ]
[ , [ @log_file_size= ] log_file_size ]
[ , [ @min_distretention= ] min_distretention ]
[ , [ @max_distretention= ] max_distretention ]
[ , [ @history_retention= ] history_retention ]
[ , [ @security_mode= ] security_mode ]
[ , [ @login= ] 'login' ]
[ , [ @password= ] 'password' ]
[ , [ @createmode= ] createmode ]
[ , [ @from_scripting = ] from_scripting ]

Arguments
[ @database=] database'
Is the name of the distribution database to be created. database is sysname, with no default. If the specified
database already exists and is not already marked as a distribution database, then the objects needed to enable
distribution are installed and the database is marked as a distribution database. If the specified database is already
enabled as a distribution database, an error is returned.
[ @data_folder=] 'data_folder'
Is the name of the directory used to store the distribution database data file. data_folder is nvarchar(255), with a
default of NULL. If NULL, the data directory for that instance of Microsoft SQL Server is used, for example,
C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data .

[ @data_file=] 'data_file'
Is the name of the database file. data_file is nvarchar(255), with a default of database. If NULL, the stored
procedure constructs a file name using the database name.
[ @data_file_size=] data_file_size
Is the initial data file size in megabytes (MB). data_file_size is int, with a default of 5MB.
[ @log_folder=] 'log_folder'
Is the name of the directory for the database log file. log_folder is nvarchar(255), with a default of NULL. If NULL,
the data directory for that instance of SQL Server is used (for example,
C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data ).
[ @log_file=] 'log_file'
Is the name of the log file. log_file is nvarchar(255), with a default of NULL. If NULL, the stored procedure
constructs a file name using the database name.
[ @log_file_size=] log_file_size
Is the initial log file size in megabytes (MB). log_file_size is int, with a default of 0 MB, which means the file size is
created using the smallest log file size allowed by SQL Server.
[ @min_distretention=] min_distretention
Is the minimum retention period, in hours, before transactions are deleted from the distribution database.
min_distretention is int, with a default of 0 hours.
[ @max_distretention=] max_distretention
Is the maximum retention period, in hours, before transactions are deleted. max_distretention is int, with a default
of 72 hours. Subscriptions that have not received replicated commands that are older than the maximum
distribution retention period are marked as inactive and need to be reinitialized. RAISERROR 21011 is issued for
each inactive subscription. A value of 0 means that replicated transactions are not stored in the distribution
database.
[ @history_retention=] history_retention
Is the number of hours to retain history. history_retention is int, with a default of 48 hours.
[ @security_mode=] security_mode
Is the security mode to use when connecting to the Distributor. security_mode is int, with a default of 1. 0 specifies
SQL Server Authentication; 1 specifies Windows Integrated Authentication.
[ @login=] 'login'
Is the login name used when connecting to the Distributor to create the distribution database. This is required if
security_mode is set to 0. login is sysname, with a default of NULL.
[ @password=] 'password'
Is the password used when connecting to the Distributor. This is required if security_mode is set to 0. password is
sysname, with a default of NULL.
[ @createmode=] createmode
createmode is int, with a default of 1, and can be one of the following values.

VALUE DESCRIPTION

0 Identified for informational purposes only. Not supported.


Future compatibility is not guaranteed.

1 (default) CREATE DATABASE or use existing database and then apply


instdist.sql file to create replication objects in the distribution
database.

2 Identified for informational purposes only. Not supported.


Future compatibility is not guaranteed.

[ @from_scripting = ] from_scripting
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_adddistributiondb is used in all types of replication. However, this stored procedure only runs at a distributor.
You must configure the distributor by executing sp_adddistributor before executing sp_adddistributiondb.
Run sp_adddistributor prior to running sp_adddistributiondb.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Install the Distributor and the distribution database.


DECLARE @distributor AS sysname;
DECLARE @distributionDB AS sysname;
DECLARE @publisher AS sysname;
DECLARE @directory AS nvarchar(500);
DECLARE @publicationDB AS sysname;
-- Specify the Distributor name.
SET @distributor = $(DistPubServer);
-- Specify the distribution database.
SET @distributionDB = N'distribution';
-- Specify the Publisher name.
SET @publisher = $(DistPubServer);
-- Specify the replication working directory.
SET @directory = N'\\' + $(DistPubServer) + '\repldata';
-- Specify the publication database.
SET @publicationDB = N'AdventureWorks2012';

-- Install the server MYDISTPUB as a Distributor using the defaults,


-- including autogenerating the distributor password.
USE master
EXEC sp_adddistributor @distributor = @distributor;

-- Create a new distribution database using the defaults, including


-- using Windows Authentication.
USE master
EXEC sp_adddistributiondb @database = @distributionDB,
@security_mode = 1;
GO

-- Create a Publisher and enable AdventureWorks2012 for replication.


-- Add MYDISTPUB as a publisher with MYDISTPUB as a local distributor
-- and use Windows Authentication.
DECLARE @distributionDB AS sysname;
DECLARE @publisher AS sysname;
-- Specify the distribution database.
SET @distributionDB = N'distribution';
-- Specify the Publisher name.
SET @publisher = $(DistPubServer);

USE [distribution]
EXEC sp_adddistpublisher @publisher=@publisher,
@distribution_db=@distributionDB,
@security_mode = 1;
GO
Permissions
Only members of the sysadmin fixed server role can execute sp_adddistributiondb.

See Also
Configure Publishing and Distribution
sp_changedistributiondb (Transact-SQL)
sp_dropdistributiondb (Transact-SQL)
sp_helpdistributiondb (Transact-SQL)
System Stored Procedures (Transact-SQL)
Configure Distribution
sp_adddistributor (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates an entry in the sys.sysservers table (if there is not one), marks the server entry as a Distributor, and stores
property information. This stored procedure is executed at the Distributor on the master database to register and
mark the server as a distributor. In the case of a remote distributor, it is also executed at the Publisher from the
master database to register the remote distributor.
Transact-SQL Syntax Conventions

Syntax
sp_adddistributor [ @distributor= ] 'distributor'
[ , [ @heartbeat_interval= ] heartbeat_interval ]
[ , [ @password= ] 'password' ]
[ , [ @from_scripting= ] from_scripting ]

Arguments
[ @distributor=] 'distributor'
Is the distribution server name. distributor is sysname, with no default. This parameter is only used if setting up a
remote Distributor. It adds entries for the Distributor properties in the msdb..MSdistributor table.
[ @heartbeat_interval=] heartbeat_interval
Is the maximum number of minutes that an agent can go without logging a progress message. heartbeat_interval
is int, with a default of 10 minutes. A SQL Server Agent job is created that runs on this interval to check the status
of the replication agents that are running.
[ @password=] 'password']
Is the password of the distributor_admin login. password is sysname, with a default of NULL. If NULL or an
empty string, password is reset to a random value. The password must be configured when the first remote
distributor is added. distributor_admin login and password are stored for linked server entry used for a
distributor RPC connection, including local connections. If distributor is local, the password for distributor_admin
is set to a new value. For Publishers with a remote Distributor, the same value for password must be specified
when executing sp_adddistributor at both the Publisher and Distributor. sp_changedistributor_password can be
used to change the Distributor password.

IMPORTANT
When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must
secure the file to prevent unauthorized access.

[ @from_scripting= ] from_scripting
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_adddistributor is used in snapshot replication, transactional replication, and merge replication.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Install the Distributor and the distribution database.


DECLARE @distributor AS sysname;
DECLARE @distributionDB AS sysname;
DECLARE @publisher AS sysname;
DECLARE @directory AS nvarchar(500);
DECLARE @publicationDB AS sysname;
-- Specify the Distributor name.
SET @distributor = $(DistPubServer);
-- Specify the distribution database.
SET @distributionDB = N'distribution';
-- Specify the Publisher name.
SET @publisher = $(DistPubServer);
-- Specify the replication working directory.
SET @directory = N'\\' + $(DistPubServer) + '\repldata';
-- Specify the publication database.
SET @publicationDB = N'AdventureWorks2012';

-- Install the server MYDISTPUB as a Distributor using the defaults,


-- including autogenerating the distributor password.
USE master
EXEC sp_adddistributor @distributor = @distributor;

-- Create a new distribution database using the defaults, including


-- using Windows Authentication.
USE master
EXEC sp_adddistributiondb @database = @distributionDB,
@security_mode = 1;
GO

-- Create a Publisher and enable AdventureWorks2012 for replication.


-- Add MYDISTPUB as a publisher with MYDISTPUB as a local distributor
-- and use Windows Authentication.
DECLARE @distributionDB AS sysname;
DECLARE @publisher AS sysname;
-- Specify the distribution database.
SET @distributionDB = N'distribution';
-- Specify the Publisher name.
SET @publisher = $(DistPubServer);

USE [distribution]
EXEC sp_adddistpublisher @publisher=@publisher,
@distribution_db=@distributionDB,
@security_mode = 1;
GO

Permissions
Only members of the sysadmin fixed server role can execute sp_adddistributor.
See Also
Configure Publishing and Distribution
sp_changedistributor_property (Transact-SQL)
sp_dropdistributor (Transact-SQL)
sp_helpdistributor (Transact-SQL)
System Stored Procedures (Transact-SQL)
Configure Distribution
sp_adddynamicsnapshot_job (Transact-SQL)
11/21/2017 • 7 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Creates an agent job that generates a filtered data snapshot for a publication with parameterized row filters. This
stored procedure is executed at the Publisher on the publication database. This stored procedure is used by an
administrator to manually create filtered data snapshot jobs for Subscribers.

NOTE
In order for a filtered data snapshot job to be created, a standard snapshot job for the publication must already exist.

For more information, see Snapshots for Merge Publications with Parameterized Filters.
Transact-SQL Syntax Conventions

Syntax
sp_adddynamicsnapshot_job [ @publication = ] 'publication'
[ , [ @suser_sname = ] 'suser_sname' ]
[ , [ @host_name = ] 'host_name' ]
[ , [ @dynamic_snapshot_jobname = ] 'dynamic_snapshot_jobname' OUTPUT ]
[ , [ @dynamic_snapshot_jobid = ] 'dynamic_snapshot_jobid' OUTPUT ]
[ , [ @frequency_type= ] frequency_type ]
[ , [ @frequency_interval= ] frequency_interval ]
[ , [ @frequency_subday= ] frequency_subday ]
[ , [ @frequency_subday_interval= ] frequency_subday_interval ]
[ , [ @frequency_relative_interval= ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor= ] frequency_recurrence_factor ]
[ , [ @active_start_date= ] active_start_date ]
[ , [ @active_end_date= ] active_end_date ]
[ , [ @active_start_time_of_day= ] active_start_time_of_day ]
[ , [ @active_end_time_of_day= ] active_end_time_of_day ]

Arguments
[ @publication=] 'publication'
Is the name of the publication to which the filtered data snapshot job is being added. publication is sysname, with
no default.
[ @suser_sname= ] 'suser_sname'
Is the value used when creating a filtered data snapshot for a subscription that is filtered by the value of the
SUSER_SNAME function at the Subscriber. suser_sname is sysname, with no default. suser_sname should be NULL
if this function is not used to dynamically filter the publication.
[ @host_name= ] 'host_name'
Is the value used when creating a filtered data snapshot for a subscription that is filtered by the value of the
HOST_NAME function at the Subscriber. host_name is sysname, with no default. host_name should be NULL if this
function is not used to dynamically filter the publication.
[ @dynamic_snapshot_jobname= ] 'dynamic_snapshot_jobname'
Is the name of the filtered data snapshot job created. dynamic_snapshot_jobname is sysname, with default of
NULL, and is an optional OUTPUT parameter. If specified, dynamic_snapshot_jobname must resolve to a unique
job at the Distributor. If unspecified, a job name will be automatically generated and returned in the result set,
where the name is created as follows:

'dyn_' + <name of the standard snapshot job> + <GUID>

NOTE
When generating the name of the dynamic snapshot job, you may truncate the name of the standard snapshot job.

[ @dynamic_snapshot_jobid= ] 'dynamic_snapshot_jobid'
Is an identifier for the filtered data snapshot job created. dynamic_snapshot_jobid is uniqueidentifier, with default
of NULL, and is an optional OUTPUT parameter.
[ @frequency_type=] frequency_type
Is the frequency with which to schedule the filtered data snapshot job. frequency_type is int, and can be one of
these values.

VALUE DESCRIPTION

1 One time

2 On demand

4 (default) Daily

8 Weekly

16 Monthly

32 Monthly relative

64 Autostart

128 Recurring

[ @frequency_interval = ] frequency_interval
Is the period (measured in days) when the filtered data snapshot job is executed. frequency_interval is int, with a
default value of 1, and depends on the value of frequency_type.

VALUE OF FREQUENCY_TYPE EFFECT ON FREQUENCY_INTERVAL

1 frequency_interval is unused.

4 (default) Every frequency_interval days, with a default of daily.


VALUE OF FREQUENCY_TYPE EFFECT ON FREQUENCY_INTERVAL

8 frequency_interval is one or more of the following (combined


with a | (Bitwise OR) (Transact-SQL) logical operator):

1 = Sunday | 2 = Monday | 4 = Tuesday | 8 = Wednesday | 16


= Thursday | 32 = Friday | 64 = Saturday

16 On the frequency_interval day of the month.

32 frequency_interval is one of the following:

1 = Sunday | 2 = Monday | 3 = Tuesday | 4 = Wednesday | 5


= Thursday | 6 = Friday | 7 = Saturday | 8 = Day | 9 =
Weekday | 10 = Weekend day

64 frequency_interval is unused.

128 frequency_interval is unused.

[ @frequency_subday=] frequency_subday
Specifies the units for frequency_subday_interval. frequency_subday is int, and can be one of these values.

VALUE DESCRIPTION

1 Once

2 Second

4 (default) Minute

8 Hour

[ @frequency_subday_interval=] frequency_subday_interval
Is the number of frequency_subday periods that occur between each execution of the job.
frequency_subday_interval is int, with a default of 5.
[ @frequency_relative_interval=] frequency_relative_interval
Is the occurrence of the filtered data snapshot job in each month. This parameter is used when frequency_type is
set to 32 (monthly relative). frequency_relative_interval is int, and can be one of these values.

VALUE DESCRIPTION

1 (default) First

2 Second

4 Third

8 Fourth

16 Last

[ @frequency_recurrence_factor=] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 0.
[ @active_start_date=] active_start_date
Is the date when the filtered data snapshot job is first scheduled, formatted as YYYYMMDD. active_start_date is int,
with a default of NULL.
[ @active_end_date=] active_end_date
Is the date when the filtered data snapshot job stops being scheduled, formatted as YYYYMMDD. active_end_date
is int, with a default of NULL.
[ @active_start_time_of_day=] active_start_time_of_day
Is the time of day when the filtered data snapshot job is first scheduled, formatted as HHMMSS.
active_start_time_of_day is int, with a default of NULL.
[ @active_end_time_of_day=] active_end_time_of_day
Is the time of day when the filtered data snapshot job stops being scheduled, formatted as HHMMSS.
active_end_time_of_day is int, with a default of NULL.

Result Set
COLUMN NAME DATA TYPE DESCRIPTION

id int Identifies the filtered data snapshot job


in the MSdynamicsnapshotjobs system
table.

dynamic_snapshot_jobname sysname Name of the filtered data snapshot job.

dynamic_snapshot_jobid uniqueidentifier Uniquely identifies the Microsoft SQL


Server Agent job at the Distributor.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_adddynamicsnapshot_job is used in merge replication for publications that use a parameterized filter.

Example
-- To avoid storing the login and password in the script file, the value
-- is passed into SQLCMD as a scripting variable. For information about
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

--Add a new merge publication.


DECLARE @publicationdb AS sysname;
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @filter AS sysname;
DECLARE @schema_hr AS sysname;
DECLARE @schema_sales AS sysname;

SET @publicationdb = N'AdventureWorks2012';


SET @publication = N'AdvWorksSalesPersonMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesPerson';
SET @filter = N'SalesPerson_Employee';
SET @filter = N'SalesPerson_Employee';
SET @schema_hr = N'HumanResources';
SET @schema_sales = N'Sales';

USE [AdventureWorks2012];

-- Enable AdventureWorks2012 for merge replication.


EXEC sp_replicationdboption
@dbname = @publicationdb,
@optname = N'merge publish',
@value = N'true';

-- Create new merge publication.


EXEC sp_addmergepublication
@publication = @publication,
@description = N'Merge publication of AdventureWorks2012.',
@allow_subscriber_initiated_snapshot = N'false';

-- Create a new snapshot job for the publication, using the


-- default schedule. Pass credentials at runtime using
-- sqlcmd scripting variables.
EXEC sp_addpublication_snapshot
@publication = @publication,
@job_login = $(Login),
@job_password = $(password);

-- Add an article for the Employee table,


-- which is horizontally partitioned using
-- a parameterized row filter.
EXEC sp_addmergearticle
@publication = @publication,
@article = @table1,
@source_owner = @schema_hr,
@source_object = @table1,
@type = N'table',
@description = 'contains employee information',
@subset_filterclause = N'[LoginID] = HOST_NAME()';

-- Add an article for the SalesPerson table,


-- which is partitioned based on a join filter.
EXEC sp_addmergearticle
@publication = @publication,
@article = @table2,
@source_owner = @schema_sales,
@source_object = @table2,
@type = N'table',
@description = 'contains customer information';

-- Add a join filter between the two articles.


EXEC sp_addmergefilter
@publication = @publication,
@article = @table1,
@filtername = @filter,
@join_articlename = @table2,
@join_filterclause = N'[Employee].[BusinessEntityID] = [SalesPerson].[SalesPersonID]',
@join_unique_key = 1,
@filter_type = 1;
GO

-- Start the snapshot agent job.


DECLARE @publication AS sysname;
SET @publication = N'AdvWorksSalesPersonMerge';

EXEC sp_startpublication_snapshot
@publication = @publication;
GO

PRINT '*** Waiting for the initial snapshot.';


GO
-- Create a temporary table to store the filtered data snapshot
-- job information.
CREATE TABLE #temp (id int,
job_name sysname,
job_id uniqueidentifier,
dynamic_filter_login sysname NULL,
dynamic_filter_hostname sysname NULL,
dynamic_snapshot_location nvarchar(255),
frequency_type int,
frequency_interval int,
frequency_subday_type int,
frequency_subday_interval int,
frequency_relative_interval int,
frequency_recurrence_factor int,
active_start_date int,
active_end_date int,
active_start_time int,
active_end_time int
)

-- Create each snapshot for a partition


-- The initial snapshot must already be generated.
DECLARE @publication AS sysname;
DECLARE @jobname AS sysname
DECLARE @hostname AS sysname
SET @publication = N'AdvWorksSalesPersonMerge';
SET @hostname = N'adventure-works\Fernando';

WHILE NOT EXISTS(SELECT * FROM sysmergepublications


WHERE [name] = @publication
AND snapshot_ready = 1)
BEGIN
WAITFOR DELAY '00:00:05'
END

-- Create a data partition by overriding HOST_NAME().


EXEC sp_addmergepartition
@publication = @publication,
@host_name = @hostname;

-- Create the filtered data snapshot job, and use the returned
-- information to start the job.
EXEC sp_adddynamicsnapshot_job
@publication = @publication,
@host_name = @hostname;

INSERT INTO #temp (id, job_name, job_id, dynamic_filter_login,


dynamic_filter_hostname, dynamic_snapshot_location,
frequency_type, frequency_interval, frequency_subday_type,
frequency_subday_interval, frequency_relative_interval,
frequency_recurrence_factor, active_start_date, active_end_date,
active_start_time,active_end_time)
EXEC sp_helpdynamicsnapshot_job;

SELECT @jobname = (SELECT DISTINCT job_name FROM #temp WHERE dynamic_filter_hostname = @hostname);

EXEC msdb..sp_start_job @job_name = @jobname;


DROP TABLE #temp;
GO

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_adddynamicsnapshot_job.
See Also
Create a Snapshot for a Merge Publication with Parameterized Filters
Parameterized Row Filters
sp_dropdynamicsnapshot_job (Transact-SQL)
sp_helpdynamicsnapshot_job (Transact-SQL)
sp_addlogreader_agent (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a Log Reader agent for a given database. This stored procedure is executed at the Publisher on the
publication database.

IMPORTANT
When configuring a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and
job_password, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its
remote Distributor before executing this stored procedure. For more information, see Enable Encrypted Connections to the
Database Engine (SQL Server Configuration Manager).

Transact-SQL Syntax Conventions

Syntax
sp_addlogreader_agent [ @job_login = ] 'job_login'
, [ @job_password = ] 'job_password'
[ , [ @job_name = ] 'job_name' ]
[ , [ @publisher_security_mode = ] publisher_security_mode ]
[ , [ @publisher_login = ] 'publisher_login' ]
[ , [ @publisher_password = ] 'publisher_password' ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @job_login= ] 'job_login'
Is the login for the Microsoft Windows account under which the agent runs. job_login is nvarchar(257), with a
default value of NULL. This Windows account is always used for agent connections to the Distributor.

NOTE
For non- Microsoft SQL Server Publishers, this must be the same login specified in sp_adddistpublisher (Transact-SQL).

[ @job_password= ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with a default
value of NULL.

IMPORTANT
Do not store authentication information in script files. For best security, login names and passwords should be supplied at
runtime.

[ @job_name= ] 'job_name'
Is the name of an existing agent job. job_name is sysname, with a default value of NULL. This parameter is only
specified when the agent is started using an existing job instead of a newly created job (the default).
[ @publisher_security_mode= ] publisher_security_mode
Is the security mode used by the agent when connecting to the Publisher. publisher_security_mode is smallint,
with a default of 1. 0 specifies SQL Server Authentication, and 1 specifies Windows Authentication. A value of 0
must be specified for non- SQL Server Publishers.
[ @publisher_login= ] 'publisher_login'
Is the login used when connecting to the Publisher. publisher_login is sysname, with a default of NULL.
publisher_login must be specified when publisher_security_mode is 0. If publisher_login is NULL and
publisher_security_mode is 1, then the Windows account specified in job_login will be used when connecting to
the Publisher.
[ @publisher_password= ] 'publisher_password'
Is the password used when connecting to the Publisher. publisher_password is sysname, with a default of NULL.

IMPORTANT
Do not store authentication information in script files. For best security, login names and passwords should be supplied at
runtime.

[ @publisher= ] 'publisher'
Is the name of the non- SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
You should not specify this parameter for a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addlogreader_agent is used in transactional replication.
You must execute sp_addlogreader_agent to add a Log Reader agent if you upgraded a database that was
enabled for replication to this version of SQL Server before a publication was created that used the database.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_addlogreader_agent.

Example
-- To avoid storing the login and password in the script file, the values
-- are passed into SQLCMD as scripting variables. For information about
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

DECLARE @publicationDB AS sysname;


DECLARE @publication AS sysname;
DECLARE @login AS sysname;
DECLARE @password AS sysname;
SET @publicationDB = N'AdventureWorks';
SET @publication = N'AdvWorksProductTran';
-- Windows account used to run the Log Reader and Snapshot Agents.
SET @login = $(Login);
-- This should be passed at runtime.
SET @password = $(Password);

-- Enable transactional or snapshot replication on the publication database.


EXEC sp_replicationdboption
@dbname=@publicationDB,
@optname=N'publish',
@value = N'true';

-- Execute sp_addlogreader_agent to create the agent job.


EXEC sp_addlogreader_agent
@job_login = @login,
@job_password = @password,
-- Explicitly specify the use of Windows Integrated Authentication (default)
-- when connecting to the Publisher.
@publisher_security_mode = 1;

-- Create a new transactional publication with the required properties.


EXEC sp_addpublication
@publication = @publication,
@status = N'active',
@allow_push = N'true',
@allow_pull = N'true',
@independent_agent = N'true';

-- Create a new snapshot job for the publication, using a default schedule.
EXEC sp_addpublication_snapshot
@publication = @publication,
@job_login = @login,
@job_password = @password,
-- Explicitly specify the use of Windows Integrated Authentication (default)
-- when connecting to the Publisher.
@publisher_security_mode = 1;
GO

See Also
Create a Publication
sp_addpublication (Transact-SQL)
sp_changelogreader_agent (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_addmergealternatepublisher (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adds the ability for a Subscriber to use an alternate synchronization partner. The publication properties must
specify that Subscribers can synchronize with other Publishers. This stored procedure is executed at the Subscriber
on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_addmergealternatepublisher [ @publisher= ] 'publisher'
, [ @publisher_db= ] 'publisher_db'
, [ @publication= ] 'publication'
, [ @alternate_publisher= ] 'alternate_synchronization_partner'
, [ @alternate_publisher_db= ] 'alternate_publisher_db'
, [ @alternate_publication= ] 'alternate_synchronization_partner'
, [ @alternate_distributor= ] 'alternate_distributor'
[ , [ @friendly_name= ] 'friendly_name' ]
[ , [ @reserved= ] 'reserved' ]

Arguments
[ @publisher=] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db=] 'publisher_db'
Is the name of the publication database. publisher_db is sysname, with no default.
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @alternate_publisher=] 'alternate_synchronization_partner'
Is the name of the alternate Publisher. alternate_synchronization_partner is sysname, with no default.
[ @alternate_publisher_db=] 'alternate_publisher_db'
Is the name of the publication database on the alternate publisher. alternate_publisher_db is sysname, with no
default.
[ @alternate_publication=] 'alternate_synchronization_partner'
Is the name of the publication on the alternate synchronization partner. alternate_synchronization_partner is
sysname, with no default.
[ @alternate_distributor=] 'alternate_distributor'
Is the name of the Distributor for the alternate synchronization partner. alternate_distributor is sysname, with no
default.
[ @friendly_name=] 'friendly_name'
Is a display name by which the association of Publisher, publication, and Distributor that makes up an alternate
synchronization partner can be identified. friendly_name is nvarchar(255), with a default of NULL.
[ @reserved=] 'reserved'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addmergealternatepublisher is used in merge replication.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addmergealternatepublisher.

See Also
sp_dropmergealternatepublisher (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addmergearticle (Transact-SQL)
11/21/2017 • 22 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds an article to an existing merge publication. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_addmergearticle [ @publication = ] 'publication'
, [ @article = ] 'article'
, [ @source_object = ] 'source_object'
[ , [ @type = ] 'type' ]
[ , [ @description = ] 'description' ]
[ , [ @column_tracking = ] 'column_tracking' ]
[ , [ @status = ] 'status' ]
[ , [ @pre_creation_cmd = ] 'pre_creation_cmd' ]
[ , [ @creation_script = ] 'creation_script' ]
[ , [ @schema_option = ] schema_option ]
[ , [ @subset_filterclause = ] 'subset_filterclause' ]
[ , [ @article_resolver = ] 'article_resolver' ]
[ , [ @resolver_info = ] 'resolver_info' ]
[ , [ @source_owner = ] 'source_owner' ]
[ , [ @destination_owner = ] 'destination_owner' ]
[ , [ @vertical_partition = ] 'vertical_partition' ]
[ , [ @auto_identity_range = ] 'auto_identity_range' ]
[ , [ @pub_identity_range = ] pub_identity_range ]
[ , [ @identity_range = ] identity_range ]
[ , [ @threshold = ] threshold ]
[ , [ @verify_resolver_signature = ] verify_resolver_signature ]
[ , [ @destination_object = ] 'destination_object' ]
[ , [ @allow_interactive_resolver = ] 'allow_interactive_resolver' ]
[ , [ @fast_multicol_updateproc = ] 'fast_multicol_updateproc' ]
[ , [ @check_permissions = ] check_permissions ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @published_in_tran_pub = ] 'published_in_tran_pub' ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]
[ , [ @logical_record_level_conflict_detection = ] 'logical_record_level_conflict_detection' ]
[ , [ @logical_record_level_conflict_resolution = ] 'logical_record_level_conflict_resolution' ]
[ , [ @partition_options = ] partition_options ]
[ , [ @processing_order = ] processing_order ]
[ , [ @subscriber_upload_options = ] subscriber_upload_options ]
[ , [ @identityrangemanagementoption = ] 'identityrangemanagementoption' ]
[ , [ @delete_tracking = ] delete_tracking ]
[ , [ @compensate_for_errors = ] 'compensate_for_errors' ]
[ , [ @stream_blob_columns = ] 'stream_blob_columns' ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication that contains the article. publication is sysname, with no default.
[ @article= ] 'article'
Is the name of the article. The name must be unique within the publication. article is sysname, with no default.
article must be on the local computer running Microsoft SQL Server, and must conform to the rules for
identifiers.
[ @source_object= ] 'source_object'
Is the database object to be published. source_object is sysname, with no default. For more information about the
types of objects that can be published using merge replication, see Publish Data and Database Objects.
[ @type= ] 'type'
Is the type of article. type is sysname, with a default of table, and can be one of the following values.

VALUE DESCRIPTION

table (default) Table with schema and data. Replication monitors the table to
determine data to be replicated.

func schema only Function with schema only.

indexed view schema only Indexed view with schema only.

proc schema only Stored procedure with schema only.

synonym schema only Synonym with schema only.

view schema only View with schema only.

[ @description= ] 'description'
Is a description of the article. description is nvarchar(255), with a default of NULL.
[ @column_tracking= ] 'column_tracking'
Is the setting for column-level tracking. column_tracking is nvarchar(10), with a default of FALSE. trueturns on
column tracking. false turns off column tracking and leaves conflict detection at the row level. If the table is
already published in other merge publications, you must use the same column tracking value used by existing
articles based on this table. This parameter is specific to table articles only.

NOTE
If row tracking is used for conflict detection (the default), the base table can include a maximum of 1,024 columns, but
columns must be filtered from the article so that a maximum of 246 columns is published. If column tracking is used, the
base table can include a maximum of 246 columns.

[ @status= ] 'status'
Is the status of the article. status is nvarchar(10), with a default of unsynced. If active, the initial processing
script to publish the table is run. If unsynced, the initial processing script to publish the table is run at the next
time the Snapshot Agent runs.
[ @pre_creation_cmd= ] 'pre_creation_cmd'
Specifies what the system is to do if the table exists at the subscriber when applying the snapshot.
pre_creation_cmd is nvarchar(10), and can be one of the following values.

VALUE DESCRIPTION

none If the table already exists at the Subscriber, no action is taken.


VALUE DESCRIPTION

delete Issues a delete based on the WHERE clause in the subset


filter.

drop (default) Drops the table before re-creating it. Required to support
Microsoft SQL Server Compact Subscribers.

truncate Truncates the destination table.

[ @creation_script= ] 'creation_script'
Is the path and name of an optional article schema script used to create the article in the subscription database.
creation_script is nvarchar(255), with a default of NULL.

NOTE
Creation scripts are not run on SQL Server Compact Subscribers.

[ @schema_option= ] schema_option
Is a bitmap of the schema generation option for the given article. schema_option is binary(8), and can be the |
(Bitwise OR) product of one or more of these values.

VALUE DESCRIPTION

0x00 Disables scripting by the Snapshot Agent and uses the


provided schema precreation script defined in creation_script.

0x01 Generates the object creation (CREATE TABLE, CREATE


PROCEDURE, and so on). This is the default value for stored
procedure articles.

0x10 Generates a corresponding clustered index. Even if this option


is not set, indexes related to primary keys and UNIQUE
constraints are generated if they are already defined on a
published table.

0x20 Converts user-defined data types (UDT) to base data types at


the Subscriber. This option cannot be used when there is a
CHECK or DEFAULT constraint on a UDT column, if a UDT
column is part of the primary key, or if a computed column
references a UDT column.

0x40 Generates corresponding nonclustered indexes. Even if this


option is not set, indexes related to primary keys and
UNIQUE constraints are generated if they are already defined
on a published table.

0x80 Replicates PRIMARY KEY constraints. Any indexes related to


the constraint are also replicated, even if options 0x10 and
0x40 are not enabled.

0x100 Replicates user triggers on a table article, if defined.


VALUE DESCRIPTION

0x200 Replicates FOREIGN KEY constraints. If the referenced table is


not part of a publication, all FOREIGN KEY constraints on a
published table are not replicated.

0x400 Replicates CHECK constraints.

0x800 Replicates defaults.

0x1000 Replicates column-level collation.

0x2000 Replicates extended properties associated with the published


article source object.

0x4000 Replicates UNIQUE constraints. Any indexes related to the


constraint are also replicated, even if options 0x10 and 0x40
are not enabled.

0x8000 This option is not valid for Publishers running SQL Server
2005 or later versions.

0x10000 Replicates CHECK constraints as NOT FOR REPLICATION so


that the constraints are not enforced during synchronization.

0x20000 Replicates FOREIGN KEY constraints as NOT FOR


REPLICATION so that the constraints are not enforced during
synchronization.

0x40000 Replicates filegroups associated with a partitioned table or


index.

0x80000 Replicates the partition scheme for a partitioned table.

0x100000 Replicates the partition scheme for a partitioned index.

0x200000 Replicates table statistics.

0x400000 Replicates default Bindings.

0x800000 Replicates rule Bindings.

0x1000000 Replicates the full-text index.

0x2000000 XML schema collections bound to xml columns are not


replicated.

0x4000000 Replicates indexes on xml columns.

0x8000000 Creates any schemas not already present on the subscriber.

0x10000000 Converts xml columns to ntext on the Subscriber.


VALUE DESCRIPTION

0x20000000 Converts large object data types (nvarchar(max),


varchar(max), and varbinary(max)) introduced in SQL
Server 2005 to data types that are supported on SQL Server
2000.

0x40000000 Replicates permissions.

0x80000000 Attempts to drop dependencies to any objects that are not


part of the publication.

0x100000000 Use this option to replicate the FILESTREAM attribute if it is


specified on varbinary(max) columns. Do not specify this
option if you are replicating tables to SQL Server 2005
Subscribers. Replicating tables that have FILESTREAM
columns to SQL Server 2000 Subscribers is not supported,
regardless of how this schema option is set. See related
option 0x800000000.

0x200000000 Converts date and time data types (date, time,


datetimeoffset, and datetime2) introduced in SQL Server
2008 to data types that are supported on earlier versions of
SQL Server.

0x400000000 Replicates the compression option for data and indexes. For
more information, see Data Compression.

0x800000000 Set this option to store FILESTREAM data on its own


filegroup at the Subscriber. If this option is not set,
FILESTREAM data is stored on the default filegroup.
Replication does not create filegroups; therefore, if you set
this option, you must create the filegroup before you apply
the snapshot at the Subscriber. For more information about
how to create objects before you apply the snapshot, see
Execute Scripts Before and After the Snapshot Is Applied.

See related option 0x100000000.

0x1000000000 Converts common language runtime (CLR) user-defined


types (UDTs) to varbinary(max) so that columns of type
UDT can be replicated to Subscribers that are running SQL
Server 2005.

0x2000000000 Converts the hierarchyid data type to varbinary(max) so


that columns of type hierarchyid can be replicated to
Subscribers that are running SQL Server 2005. For more
information about how to use hierarchyid columns in
replicated tables, see hierarchyid (Transact-SQL).

0x4000000000 Replicates any filtered indexes on the table. For more


information about filtered indexes, see Create Filtered
Indexes.

0x8000000000 Converts the geography and geometry data types to


varbinary(max) so that columns of these types can be
replicated to Subscribers that are running SQL Server 2005.
VALUE DESCRIPTION

0x10000000000 Replicates indexes on columns of type geography and


geometry.

If this value is NULL, the system auto-generates a valid schema option for the article. The Default Schema
Option table in the Remarks section shows the value that is chosen based upon the article type. Also, not all
schema_option values are valid for every type of replication and article type. The Valid Schema Option table
given in the Remarks shows the options that can be specified for a given article type.

NOTE
The schema_option parameter only affects replication options for the initial snapshot. Once the initial schema has been
generated by the Snapshot Agent and applied at the Subscriber, the replication of publication schema changes to the
Subscriber occur based on schema change replication rules and the replicate_ddl parameter setting specified in
sp_addmergepublication. For more information, see Make Schema Changes on Publication Databases.

[ @subset_filterclause= ] 'subset_filterclause'
Is a WHERE clause specifying the horizontal filtering of a table article without the word WHERE included.
subset_filterclause is of nvarchar(1000), with a default of an empty string.

IMPORTANT
For performance reasons, we recommended that you not apply functions to column names in parameterized row filter
clauses, such as LEFT([MyColumn]) = SUSER_SNAME() . If you use HOST_NAME in a filter clause and override the
HOST_NAME value, you might have to convert data types by using CONVERT. For more information about best practices
for this case, see the section "Overriding the HOST_NAME() Value" in Parameterized Row Filters.

[ @article_resolver= ] 'article_resolver'
Is the COM-based resolver used to resolve conflicts on the table article or the .NET Framework assembly invoked
to execute custom business logic on the table article. article_resolver is varchar(255), with a default of NULL.
Available values for this parameter are listed in Microsoft Custom Resolvers. If the value provided is not one of
the Microsoft resolvers, SQL Server uses the specified resolver instead of the system-supplied resolver. Use
sp_enumcustomresolvers to enumerate the list of available custom resolvers. For more information, see
Execute Business Logic During Merge Synchronization and Advanced Merge Replication Conflict Detection and
Resolution.
[ @resolver_info= ] 'resolver_info'
Is used to specify additional information required by a custom resolver. Some of the Microsoft Resolvers require
a column provided as input to the resolver. resolver_info is nvarchar(255), with a default of NULL. For more
information, see Microsoft COM-Based Resolvers.
[ @source_owner= ] 'source_owner'
Is the name of the owner of the source_object. source_owner is sysname, with a default of NULL. If NULL, the
current user is assumed to be the owner.
[ @destination_owner= ] 'destination_owner'
Is the owner of the object in the subscription database, if not 'dbo'. destination_owner is sysname, with a default
of NULL. If NULL, 'dbo' is assumed to be the owner.
[ @vertical_partition= ] 'column_filter'
Enables and disables column filtering on a table article. vertical_partition is nvarchar(5) with a default of FALSE.
false indicates there is no vertical filtering and publishes all columns.
true clears all columns except the declared primary key and ROWGUID columns. Columns are added by using
sp_mergearticlecolumn.
[ @auto_identity_range= ] 'automatic_identity_range'
Enables and disables automatic identity range handling for this table article on a publication at the time it is
created. auto_identity_range is nvarchar(5), with a default of FALSE. true enables automatic identity range
handling, while false disables it.

NOTE
auto_identity_range has been deprecated and is provided for backward compatibility only. You should use
identityrangemanagementoption for specifying identity range management options. For more information, see Replicate
Identity Columns.

[ @pub_identity_range= ] pub_identity_range
Controls the identity range size allocated to a Subscriber with a server subscription when automatic identity
range management is used. This identity range is reserved for a republishing Subscriber to allocate to its own
Subscribers. pub_identity_range is bigint, with a default of NULL. You must specify this parameter if
identityrangemanagementoption is auto or if auto_identity_range is true.
[ @identity_range= ] identity_range
Controls the identity range size allocated both to the Publisher and to the Subscriber when automatic identity
range management is used. identity_range is bigint, with a default of NULL. You must specify this parameter if
identityrangemanagementoption is auto or if auto_identity_range is true.

NOTE
identity_range controls the identity range size at republishing Subscribers using previous versions of SQL Server.

[ @threshold= ] threshold
Percentage value that controls when the Merge Agent assigns a new identity range. When the percentage of
values specified in threshold is used, the Merge Agent creates a new identity range. threshold is int, with a default
of NULL. You must specify this parameter if identityrangemanagementoption is auto or if auto_identity_range is
true.
[ @verify_resolver_signature= ] verify_resolver_signature
Specifies if a digital signature is verified before using a resolver in merge replication. verify_resolver_signature is
int, with a default of 1.
0 specifies that the signature will not be verified.
1 specifies that the signature will be verified to see if it is from a trusted source.
[ @destination_object= ] 'destination_object'
Is the name of the object in the subscription database. destination_object is sysname, with a default value of what
is in @source_object. This parameter can be specified only if the article is a schema-only article, such as stored
procedures, views, and UDFs. If the article specified is a table article, the value in @source_object overrides the
value in destination_object.
[ @allow_interactive_resolver= ] 'allow_interactive_resolver'
Enables or disables the use of the Interactive Resolver on an article. allow_interactive_resolver is nvarchar(5),
with a default of FALSE. true enables the use of the Interactive Resolver on the article; false disables it.
NOTE
Interactive Resolver is not supported by SQL Server Compact Subscribers.

[ @fast_multicol_updateproc= ] 'fast_multicol_updateproc'
This parameter has been deprecated and is maintained for backward compatibility of scripts.
[ @check_permissions= ] check_permissions
Is a bitmap of the table-level permissions that are verified when the Merge Agent applies changes to the
Publisher. If the Publisher login/user account used by the merge process does not have the correct table
permissions, the invalid changes are logged as conflicts. check_permissions is int, and can be the | (Bitwise OR)
product of one or more of the following values.

VALUE DESCRIPTION

0x00 (default) Permissions are not checked.

0x10 Checks permissions at the Publisher before insert operations


made at a Subscriber can be uploaded.

0x20 Checks permissions at the Publisher before update


operations made at a Subscriber can be uploaded.

0x40 Checks permissions at the Publisher before delete operations


made at a Subscriber can be uploaded.

[ @force_invalidate_snapshot= ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure may invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default of 0.
0 specifies that adding an article does not cause the snapshot to be invalid. If the stored procedure detects that
the change does require a new snapshot, an error occurs and no changes are made.
1 specifies that adding an article may cause the snapshot to be invalid, and if there are existing subscriptions that
require a new snapshot, gives permission for the existing snapshot to be marked as obsolete and a new snapshot
generated. force_invalidate_snapshot is set to 1 when adding an article to a publication with an existing snapshot.
[ @published_in_tran_pub= ] 'published_in_tran_pub'
Indicates that an article in a merge publication is also published in a transactional publication.
published_in_tran_pub is nvarchar(5), with a default of FALSE. true specifies that the article is also published in a
transactional publication.
[ @force_reinit_subscription= ] force_reinit_subscription
Acknowledges that the action taken by this stored procedure may require existing subscriptions to be reinitialized.
force_reinit_subscription is a bit, with a default of 0.
0 specifies that adding an article does not cause the subscription to be reinitialized. If the stored procedure detects
that the change would require existing subscriptions to be reinitialized, an error occurs and no changes are made.
1 means that changes to the merge article causes existing subscriptions to be reinitialized, and gives permission
for the subscription reinitialization to occur. force_reinit_subscription is set to 1 when subset_filterclause specifies
a parameterized row filter.
[ @logical_record_level_conflict_detection= ] 'logical_record_level_conflict_detection'
Specifies the level of conflict detection for an article that is a member of a logical record.
logical_record_level_conflict_detection is nvarchar(5), with a default of FALSE.
true specifies that a conflict will be detected if changes are made anywhere in the logical record.
false specifies that the default conflict detection is used as specified by column_tracking. For more information,
see Group Changes to Related Rows with Logical Records.

NOTE
Because logical records are not supported by SQL Server Compact Subscribers, you must specify a value of false for
logical_record_level_conflict_detection to support these Subscribers.

[ @logical_record_level_conflict_resolution= ] 'logical_record_level_conflict_resolution'
Specifies the level of conflict resolution for an article that is a member of a logical record.
logical_record_level_conflict_resolution is nvarchar(5), with a default of FALSE.
true specifies that the entire winning logical record overwrites the losing logical record.
false specifies that winning rows are not constrained to the logical record. If
logical_record_level_conflict_detection is true, then logical_record_level_conflict_resolution must also be set to
true. For more information, see Group Changes to Related Rows with Logical Records.

NOTE
Because logical records are not supported by SQL Server Compact Subscribers, you must specify a value of false for
logical_record_level_conflict_resolution to support these Subscribers.

[ @partition_options= ] partition_options
Defines the way in which data in the article is partitioned, which enables performance optimizations when all
rows belong in only one partition or in only one subscription. partition_options is tinyint, and can be one of the
following values.

VALUE DESCRIPTION

0 (default) The filtering for the article either is static or does not yield a
unique subset of data for each partition, that is, an
"overlapping" partition.

1 The partitions are overlapping, and data manipulation


language (DML) updates made at the Subscriber cannot
change the partition to which a row belongs.

2 The filtering for the article yields non-overlapping partitions,


but multiple Subscribers can receive the same partition.

3 The filtering for the article yields non-overlapping partitions


that are unique for each subscription.

NOTE
If the source table for an article is already published in another publication, then the value of partition_options must be the
same for both articles.

[ @processing_order= ] processing_order
Indicates the processing order of articles in a merge publication. processing_order is int, with a default of 0. 0
specifies that the article is unordered, and any other value represents the ordinal value of the processing order for
this article. Articles are processed in order from lowest to highest value. If two articles have the same value,
processing order is determined by the order of the article nickname in the sysmergearticles system table. For
more information, see Specify the Processing Order of Merge Articles.
[ @subscriber_upload_options= ] subscriber_upload_options
Defines restrictions on updates made at a Subscriber with a client subscription. For more information, see
Optimize Merge Replication Performance with Download-Only Articles. subscriber_upload_options is tinyint, and
can be one of the following values.

VALUE DESCRIPTION

0 (default) No restrictions. Changes made at the Subscriber are


uploaded to the Publisher.

1 Changes are allowed at the Subscriber, but they are not


uploaded to the Publisher.

2 Changes are not allowed at the Subscriber.

Changing subscriber_upload_options requires the subscription to be reinitialized by calling


sp_reinitmergepullsubscription (Transact-SQL).

NOTE
If the source table for an article is already published in another publication, the value of subscriber_upload_options must be
the same for both articles.

[ @identityrangemanagementoption= ] identityrangemanagementoption
Specifies how identity range management is handled for the article. identityrangemanagementoption is
nvarchar(10), and can be one of the following values.

VALUE DESCRIPTION

none Disables identity range management.

manual Marks the identity column using NOT FOR REPLICATION to


enable manual identity range handling.

auto Specifies automatic management of identity ranges.

NULL(default) Defaults to nonewhen the value of auto_identity_range is


not true.

For backward compatibility, when the value of identityrangemanagementoption is NULL, the value of
auto_identity_range is checked. However, when the value of identityrangemanagementoption is not NULL, then
the value of auto_identity_range is ignored. For more information, see Replicate Identity Columns.
[ @delete_tracking= ] 'delete_tracking'
Indicates whether deletes are replicated. delete_tracking is nvarchar(5), with a default of TRUE. false indicates
that deletes are not replicated, and true indicates that deletes are replicated, which is the usual behavior for
merge replication. When delete_tracking is set to false, rows deleted at the Subscriber must be manually
removed at the Publisher, and rows deleted at the Publisher must be manually removed at the Subscriber.
IMPORTANT
Setting delete_tracking to false results in non-convergence. If the source table for an article is already published in another
publication, then the value of delete_tracking must be the same for both articles.

NOTE
delete_tracking options cannot be set using the New Publication Wizard or the Publication Properties dialog box.

[ @compensate_for_errors= ] 'compensate_for_errors'
Indicates if compensating actions are taken when errors are encountered during synchronization.
compensate_for_errors is nvarchar(5), with a default of FALSE. When set to true, changes that cannot be applied
at a Subscriber or Publisher during synchronization always lead to compensating actions to undo the change;
however, one incorrectly configured Subscriber that generates an error can cause changes at other Subscribers
and Publishers to be undone. false disables these compensating actions, however, the errors are still logged as
with compensation and subsequent merges continues to attempt to apply the changes until successful.

IMPORTANT
Although data in the affected rows might appear to be out of convergence, as soon as you address any errors, changes can
be applied and data will converge. If the source table for an article is already published in another publication, then the
value of compensate_for_errors must be the same for both articles.

[ @stream_blob_columns= ] 'stream_blob_columns'
Specifies that a data stream optimization be used when replicating binary large object columns.
stream_blob_columns is nvarchar(5), with a default of FALSE. true means that the optimization will be
attempted. stream_blob_columns is set to true when FILESTREAM is enabled. This allows replication of
FILESTREAM data to perform optimally and reduce memory utilization. To force FILESTREAM table articles to not
use blob streaming, use sp_changemergearticle to set stream_blob_columns to false.

IMPORTANT
Enabling this memory optimization may reduce the performance of the Merge Agent during synchronization. This option
should only be used when replicating columns that contain megabytes of data.

NOTE
Certain merge replication functionalities, such as logical records, can still prevent the stream optimization from being used
when replicating binary large objects even with stream_blob_columns set to true.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addmergearticle is used in merge replication.
When you publish objects, their definitions are copied to Subscribers. If you are publishing a database object that
depends on one or more other objects, you must publish all referenced objects. For example, if you publish a view
that depends on a table, you must publish the table also.
If you specify a value of 3 for partition_options, there can be only a single subscription for each partition of data in
that article. If a second subscription is created in which the filtering criterion of the new subscription resolves to
the same partition as the existing subscription, the existing subscription is dropped.
When specifying a value of 3 for partition_options, metadata is cleaned-up whenever the Merge Agent runs and
the partitioned snapshot expires more quickly. When using this option, you should consider enabling subscriber
requested partitioned snapshot. For more information, see Snapshots for Merge Publications with Parameterized
Filters.
Adding an article with a static horizontal filter, using subset_filterclause, to an existing publication with articles that
have parameterized filters requires the subscriptions be reinitialized.
When specifying processing_order, we recommend leaving gaps between the article order values, which makes it
easier to set new values in the future. For example, if you have three articles Article1, Article2, and Article3, set
processing_order to 10, 20, and 30, rather than 1, 2, and 3. For more information, see Specify the Processing
Order of Merge Articles.

Default Schema Option Table


This table describes the default value that is set by the stored procedure if a NULL value is specified for
schema_option, which depends on article type.

ARTICLE TYPE SCHEMA OPTION VALUE

func schema only 0x01

indexed view schema only 0x01

proc schema only 0x01

table 0x0C034FD1 - SQL Server 2005 and later compatible


publications with a native mode snapshot.

0x08034FF1 - SQL Server 2005 and later compatible


publications with a character mode snapshot.

view schema only 0x01

NOTE
If the publication supports earlier versions of SQL Server, the default schema option for table is 0x30034FF1.

Valid Schema Option Table


The following table describes the allowed values schema_option depending on article type.

ARTICLE TYPE SCHEMA OPTION VALUES

func schema only 0x01 and 0x2000

indexed view schema only 0x01, 0x040, 0x0100, 0x2000, 0x40000, 0x1000000, and
0x200000

proc schema only 0x01 and 0x2000


ARTICLE TYPE SCHEMA OPTION VALUES

table All options.

view schema only 0x01, 0x040, 0x0100, 0x2000, 0x40000, 0x1000000, and
0x200000

Example
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @table3 AS sysname;
DECLARE @salesschema AS sysname;
DECLARE @hrschema AS sysname;
DECLARE @filterclause AS nvarchar(1000);
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesOrderHeader';
SET @table3 = N'SalesOrderDetail';
SET @salesschema = N'Sales';
SET @hrschema = N'HumanResources';
SET @filterclause = N'Employee.LoginID = HOST_NAME()';

-- Add a filtered article for the Employee table.


EXEC sp_addmergearticle
@publication = @publication,
@article = @table1,
@source_object = @table1,
@type = N'table',
@source_owner = @hrschema,
@schema_option = 0x0004CF1,
@description = N'article for the Employee table',
@subset_filterclause = @filterclause;

-- Add an article for the SalesOrderHeader table that is filtered


-- based on Employee and horizontally filtered.
EXEC sp_addmergearticle
@publication = @publication,
@article = @table2,
@source_object = @table2,
@type = N'table',
@source_owner = @salesschema,
@vertical_partition = N'true',
@schema_option = 0x0034EF1,
@description = N'article for the SalesOrderDetail table';

-- Add an article for the SalesOrderDetail table that is filtered


-- based on SaledOrderHeader.
EXEC sp_addmergearticle
@publication = @publication,
@article = @table3,
@source_object = @table3,
@source_owner = @salesschema,
@description = 'article for the SalesOrderHeader table',
@identityrangemanagementoption = N'auto',
@pub_identity_range = 100000,
@identity_range = 100,
@threshold = 80,
@schema_option = 0x0004EF1;

-- Add all columns to the SalesOrderHeader article.


EXEC sp_mergearticlecolumn
@publication = @publication,
@article = @table2,
@article = @table2,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Remove the credit card Approval Code column.


EXEC sp_mergearticlecolumn
@publication = @publication,
@article = @table2,
@column = N'CreditCardApprovalCode',
@operation = N'drop',
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Add a merge join filter between Employee and SalesOrderHeader.


EXEC sp_addmergefilter
@publication = @publication,
@article = @table2,
@filtername = N'SalesOrderHeader_Employee',
@join_articlename = @table1,
@join_filterclause = N'Employee.BusinessEntityID = SalesOrderHeader.SalesPersonID',
@join_unique_key = 1,
@filter_type = 1,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Add a merge join filter between SalesOrderHeader and SalesOrderDetail.


EXEC sp_addmergefilter
@publication = @publication,
@article = @table3,
@filtername = N'SalesOrderDetail_SalesOrderHeader',
@join_articlename = @table2,
@join_filterclause = N'SalesOrderHeader.SalesOrderID = SalesOrderDetail.SalesOrderID',
@join_unique_key = 1,
@filter_type = 1,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;
GO

Permissions
Requires membership in the sysadmin fixed server role or the db_owner fixed database role.

See Also
Define an Article
Publish Data and Database Objects
Replicate Identity Columns
sp_changemergearticle (Transact-SQL)
sp_dropmergearticle (Transact-SQL)
sp_helpmergearticle (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_addmergefilter (Transact-SQL)
11/21/2017 • 6 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a new merge filter to create a partition based on a join with another table. This stored procedure is executed
at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_addmergefilter [ @publication = ] 'publication'
, [ @article = ] 'article'
, [ @filtername = ] 'filtername'
, [ @join_articlename = ] 'join_articlename'
, [ @join_filterclause = ] join_filterclause
[ , [ @join_unique_key = ] join_unique_key ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]
[ , [ @filter_type = ] filter_type ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication in which the merge filter is being added. publication is sysname, with no default.
[ @article= ] 'article'
Is the name of the article on which the merge filter is being added. article is sysname, with no default.
[ @filtername= ] 'filtername'
Is the name of the filter. filtername is a required parameter. filternameis sysname, with no default.
[ @join_articlename= ] 'join_articlename'
Is the parent article to which the child article, specified by article, must be joined using the join clause specified by
join_filterclause, in order to determine the rows in the child article that meet the filter criterion of the merge filter.
join_articlename is sysname, with no default. The article must be in the publication given by publication.
[ @join_filterclause= ] join_filterclause
Is the join clause that must be used to join the child article specified by articleand parent article specified by
join_article, in order to determine the rows qualifying the merge filter. join_filterclause is nvarchar(1000).
[ @join_unique_key= ] join_unique_key
Specifies if the join between child article articleand parent article join_articleis one-to-many, one-to-one, many-to-
one, or many-to-many. join_unique_key is int, with a default of 0. 0 indicates a many-to-one or many-to-many
join. 1 indicates a one-to-one or one-to-many join. This value is 1 when the joining columns form a unique key in
join_article, or if join_filterclause is between a foreign key in article and a primary key in join_article.
Cau t i on

Only set this parameter to 1 if you have a constraint on the joining column in the underlying table for the parent
article that guarantees uniqueness. If join_unique_key is set to 1 incorrectly, non-convergence of data may occur.
[ @force_invalidate_snapshot= ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure may invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default 0.
0 specifies that changes to the merge article will not cause the snapshot to be invalid. If the stored procedure
detects that the change does require a new snapshot, an error will occur and no changes will be made.
1 specifies that changes to the merge article may cause the snapshot to be invalid, and if there are existing
subscriptions that would require a new snapshot, gives permission for the existing snapshot to be marked as
obsolete and a new snapshot generated.
[ @force_reinit_subscription= ] force_reinit_subscription
Acknowledges that the action taken by this stored procedure may require existing subscriptions to be reinitialized.
force_reinit_subscription is a bit, with a default of 0.
0 specifies that changes to the merge article will not cause the subscription to be reinitialized. If the stored
procedure detects that the change would require subscriptions to be reinitialized, an error will occur and no
changes will be made.
1 specifies that changes to the merge article will cause existing subscriptions to be reinitialized, and gives
permission for the subscription reinitialization to occur.
[ @filter_type= ] filter_type
Specifies the type of filter being added. filter_type is tinyint, and can be one of the following values.

VALUE DESCRIPTION

1 Join filter only. Required to support SQL Server Compact


Subscribers.

2 Logical record relationship only.

3 Both join filter and logical record relationship.

For more information, see Group Changes to Related Rows with Logical Records.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addmergefilter is used in merge replication.
sp_addmergefilter can only be used with table articles. View and indexed view articles are not supported.
This procedure can also be used to add a logical relationship between two articles that may or may not have a join
filter between them. filter_type is used to specify if the merge filter being added is a join filter, a logical relation, or
both.
To use logical records, the publication and articles must meet a number of requirements. For more information,
see Group Changes to Related Rows with Logical Records.
Typically, this option is used for an article that has a foreign key reference to a published primary key table, and the
primary key table has a filter defined in its article. The subset of primary key rows is used to determine the foreign
key rows that are replicated to the Subscriber.
You cannot add a join filter between two published articles when the source tables for both articles share the same
table object name. In such a case, even if both tables are owned by different schemas and have unique article
names, creation of the join filter will fail.
When both a parameterized row filter and a join filter are used on a table article, replication determines whether a
row belongs in a Subscriber's partition. It does so by evaluating either the filtering function or the join filter (using
the OR operator), rather than evaluating the intersection of the two conditions (using the AND operator).

Example
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @table3 AS sysname;
DECLARE @salesschema AS sysname;
DECLARE @hrschema AS sysname;
DECLARE @filterclause AS nvarchar(1000);
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesOrderHeader';
SET @table3 = N'SalesOrderDetail';
SET @salesschema = N'Sales';
SET @hrschema = N'HumanResources';
SET @filterclause = N'Employee.LoginID = HOST_NAME()';

-- Add a filtered article for the Employee table.


EXEC sp_addmergearticle
@publication = @publication,
@article = @table1,
@source_object = @table1,
@type = N'table',
@source_owner = @hrschema,
@schema_option = 0x0004CF1,
@description = N'article for the Employee table',
@subset_filterclause = @filterclause;

-- Add an article for the SalesOrderHeader table that is filtered


-- based on Employee and horizontally filtered.
EXEC sp_addmergearticle
@publication = @publication,
@article = @table2,
@source_object = @table2,
@type = N'table',
@source_owner = @salesschema,
@vertical_partition = N'true',
@schema_option = 0x0034EF1,
@description = N'article for the SalesOrderDetail table';

-- Add an article for the SalesOrderDetail table that is filtered


-- based on SaledOrderHeader.
EXEC sp_addmergearticle
@publication = @publication,
@article = @table3,
@source_object = @table3,
@source_owner = @salesschema,
@description = 'article for the SalesOrderHeader table',
@identityrangemanagementoption = N'auto',
@pub_identity_range = 100000,
@identity_range = 100,
@threshold = 80,
@schema_option = 0x0004EF1;

-- Add all columns to the SalesOrderHeader article.


EXEC sp_mergearticlecolumn
@publication = @publication,
@article = @table2,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Remove the credit card Approval Code column.


EXEC sp_mergearticlecolumn
@publication = @publication,
@article = @table2,
@column = N'CreditCardApprovalCode',
@operation = N'drop',
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Add a merge join filter between Employee and SalesOrderHeader.


EXEC sp_addmergefilter
@publication = @publication,
@article = @table2,
@filtername = N'SalesOrderHeader_Employee',
@join_articlename = @table1,
@join_filterclause = N'Employee.EmployeeID = SalesOrderHeader.SalesPersonID',
@join_unique_key = 1,
@filter_type = 1,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Add a merge join filter between SalesOrderHeader and SalesOrderDetail.


EXEC sp_addmergefilter
@publication = @publication,
@article = @table3,
@filtername = N'SalesOrderDetail_SalesOrderHeader',
@join_articlename = @table2,
@join_filterclause = N'SalesOrderHeader.SalesOrderID = SalesOrderDetail.SalesOrderID',
@join_unique_key = 1,
@filter_type = 1,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addmergefilter.

See Also
Define an Article
Define and Modify a Join Filter Between Merge Articles
Join Filters
sp_changemergefilter (Transact-SQL)
sp_dropmergefilter (Transact-SQL)
sp_helpmergefilter (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_addmergepartition (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Creates a dynamically filtered partition for a subscription that is filtered by the values of HOST_NAME or
SUSER_SNAME at the Subscriber. This stored procedure is executed at the Publisher on the database that is being
published, and is used to manually generate partitions.
Transact-SQL Syntax Conventions

Syntax
sp_addmergepartition [ @publication = ] 'publication'
, [ @suser_sname = ] 'suser_sname'
, [ @host_name = ] 'host_name'

Arguments
[ @publication= ] 'publication'
Is the merge publication on which the partition is being created. publication is sysname, with no default. If
suser_sname is specified, the value of hostname must be NULL.
[ @suser_sname= ] 'suser_sname'
Is the value used when creating the partition for a subscription that is filtered by the value of the SUSER_SNAME
function at the Subscriber. suser_sname is sysname, with no default.
[ @host_name= ] 'host_name'
Is the value used when creating the partition for a subscription that is filtered by the value of the HOST_NAME
function at the Subscriber. host_name is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addmergepartition is used in merge replication.

Example
-- To avoid storing the login and password in the script file, the value
-- is passed into SQLCMD as a scripting variable. For information about
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

--Add a new merge publication.


DECLARE @publicationdb AS sysname;
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @filter AS sysname;
DECLARE @schema_hr AS sysname;
DECLARE @schema_sales AS sysname;

SET @publicationdb = N'AdventureWorks2012';


SET @publication = N'AdvWorksSalesPersonMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesPerson';
SET @filter = N'SalesPerson_Employee';
SET @schema_hr = N'HumanResources';
SET @schema_sales = N'Sales';

USE [AdventureWorks2012];

-- Enable AdventureWorks2012 for merge replication.


EXEC sp_replicationdboption
@dbname = @publicationdb,
@optname = N'merge publish',
@value = N'true';

-- Create new merge publication.


EXEC sp_addmergepublication
@publication = @publication,
@description = N'Merge publication of AdventureWorks2012.',
@allow_subscriber_initiated_snapshot = N'false';

-- Create a new snapshot job for the publication, using the


-- default schedule. Pass credentials at runtime using
-- sqlcmd scripting variables.
EXEC sp_addpublication_snapshot
@publication = @publication,
@job_login = $(Login),
@job_password = $(password);

-- Add an article for the Employee table,


-- which is horizontally partitioned using
-- a parameterized row filter.
EXEC sp_addmergearticle
@publication = @publication,
@article = @table1,
@source_owner = @schema_hr,
@source_object = @table1,
@type = N'table',
@description = 'contains employee information',
@subset_filterclause = N'[LoginID] = HOST_NAME()';

-- Add an article for the SalesPerson table,


-- which is partitioned based on a join filter.
EXEC sp_addmergearticle
@publication = @publication,
@article = @table2,
@source_owner = @schema_sales,
@source_object = @table2,
@type = N'table',
@description = 'contains customer information';

-- Add a join filter between the two articles.


EXEC sp_addmergefilter
@publication = @publication,
@article = @table1,
@filtername = @filter,
@join_articlename = @table2,
@join_filterclause = N'[Employee].[BusinessEntityID] = [SalesPerson].[SalesPersonID]',
@join_unique_key = 1,
@filter_type = 1;
GO

-- Start the snapshot agent job.


-- Start the snapshot agent job.
DECLARE @publication AS sysname;
SET @publication = N'AdvWorksSalesPersonMerge';

EXEC sp_startpublication_snapshot
@publication = @publication;
GO

PRINT '*** Waiting for the initial snapshot.';


GO

-- Create a temporary table to store the filtered data snapshot


-- job information.
CREATE TABLE #temp (id int,
job_name sysname,
job_id uniqueidentifier,
dynamic_filter_login sysname NULL,
dynamic_filter_hostname sysname NULL,
dynamic_snapshot_location nvarchar(255),
frequency_type int,
frequency_interval int,
frequency_subday_type int,
frequency_subday_interval int,
frequency_relative_interval int,
frequency_recurrence_factor int,
active_start_date int,
active_end_date int,
active_start_time int,
active_end_time int
)

-- Create each snapshot for a partition


-- The initial snapshot must already be generated.
DECLARE @publication AS sysname;
DECLARE @jobname AS sysname
DECLARE @hostname AS sysname
SET @publication = N'AdvWorksSalesPersonMerge';
SET @hostname = N'adventure-works\Fernando';

WHILE NOT EXISTS(SELECT * FROM sysmergepublications


WHERE [name] = @publication
AND snapshot_ready = 1)
BEGIN
WAITFOR DELAY '00:00:05'
END

-- Create a data partition by overriding HOST_NAME().


EXEC sp_addmergepartition
@publication = @publication,
@host_name = @hostname;

-- Create the filtered data snapshot job, and use the returned
-- information to start the job.
EXEC sp_adddynamicsnapshot_job
@publication = @publication,
@host_name = @hostname;

INSERT INTO #temp (id, job_name, job_id, dynamic_filter_login,


dynamic_filter_hostname, dynamic_snapshot_location,
frequency_type, frequency_interval, frequency_subday_type,
frequency_subday_interval, frequency_relative_interval,
frequency_recurrence_factor, active_start_date, active_end_date,
active_start_time,active_end_time)
EXEC sp_helpdynamicsnapshot_job;

SELECT @jobname = (SELECT DISTINCT job_name FROM #temp WHERE dynamic_filter_hostname = @hostname);

EXEC msdb..sp_start_job @job_name = @jobname;


DROP TABLE #temp;
GO
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addmergepartition.

See Also
Create a Snapshot for a Merge Publication with Parameterized Filters
Parameterized Row Filters
sp_addmergepublication (Transact-SQL)
11/21/2017 • 16 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a new merge publication. This stored procedure is executed at the Publisher on the database that is being
published.
Transact-SQL Syntax Conventions

Syntax
sp_addmergepublication [ @publication = ] 'publication'
[ , [ @description = ] 'description'
[ , [ @retention = ] retention ]
[ , [ @sync_mode = ] 'sync_mode' ]
[ , [ @allow_push = ] 'allow_push' ]
[ , [ @allow_pull = ] 'allow_pull' ]
[ , [ @allow_anonymous = ] 'allow_anonymous' ]
[ , [ @enabled_for_internet = ] 'enabled_for_internet' ]
[ , [ @centralized_conflicts = ] 'centralized_conflicts' ]
[ , [ @dynamic_filters = ] 'dynamic_filters' ]
[ , [ @snapshot_in_defaultfolder = ] 'snapshot_in_default_folder' ]
[ , [ @alt_snapshot_folder = ] 'alternate_snapshot_folder' ]
[ , [ @pre_snapshot_script = ] 'pre_snapshot_script' ]
[ , [ @post_snapshot_script = ] 'post_snapshot_script' ]
[ , [ @compress_snapshot = ] 'compress_snapshot' ]
[ , [ @ftp_address = ] 'ftp_address' ]
[ , [ @ftp_port = ] ftp_port ]
[ , [ @ftp_subdirectory = ] 'ftp_subdirectory' ]
[ , [ @ftp_login = ] 'ftp_login' ]
[ , [ @ftp_password = ] 'ftp_password' ]
[ , [ @conflict_retention = ] conflict_retention ]
[ , [ @keep_partition_changes = ] 'keep_partition_changes' ]
[ , [ @allow_subscription_copy = ] 'allow_subscription_copy' ]
[ , [ @allow_synctoalternate = ] 'allow_synctoalternate' ]
[ , [ @validate_subscriber_info = ] 'validate_subscriber_info' ]
[ , [ @add_to_active_directory = ] 'add_to_active_directory' ]
[ , [ @max_concurrent_merge = ] maximum_concurrent_merge ]
[ , [ @max_concurrent_dynamic_snapshots = ] max_concurrent_dynamic_snapshots ]
[ , [ @use_partition_groups = ] 'use_partition_groups' ]
[ , [ @publication_compatibility_level = ] 'backward_comp_level' ]
[ , [ @replicate_ddl = ] replicate_ddl ]
[ , [ @allow_subscriber_initiated_snapshot = ] 'allow_subscriber_initiated_snapshot' ]
[ , [ @allow_web_synchronization = ] 'allow_web_synchronization' ]
[ , [ @web_synchronization_url = ] 'web_synchronization_url' ]
[ , [ @allow_partition_realignment = ] 'allow_partition_realignment' ]
[ , [ @retention_period_unit = ] 'retention_period_unit' ]
[ , [ @generation_leveling_threshold = ] generation_leveling_threshold ]
[ , [ @automatic_reinitialization_policy = ] automatic_reinitialization_policy ]
[ , [ @conflict_logging = ] 'conflict_logging' ]

Arguments
[ @publication = ] 'publication'
Is the name of the merge publication to create. publication is sysname, with no default, and must not be the
keyword ALL. The name of the publication must be unique within the database.
[ @description = ] 'description'
Is the publication description. description is nvarchar(255), with a default of NULL.
[ @retention = ] retention
Is the retention period, in retention period units, for which to save changes for the given publication. retention is
int, with a default of 14 units. Retention period units are defined by retention_period_unit. If the subscription is not
synchronized within the retention period, and the pending changes it would have received have been removed by
a clean-up operation at the Distributor, the subscription expires and must be reinitialized. The maximum allowable
retention period is the number of days between Dec. 31, 9999 and the current date.

NOTE
The retention period for merge publications has a 24 hour grace period to accommodate Subscribers in different time zones.
If, for example, you set a retention period of one day, the actual retention period is 48 hours.

[ @sync_mode = ] 'sync_mode'
Is the mode of the initial synchronization of subscribers to the publication. sync_mode is nvarchar(10), and can be
one of the following values.

VALUE DESCRIPTION

native (default) Produces native-mode bulk copy program output of all tables.

character Produces character-mode bulk copy program output of all


tables. Required to support Microsoft SQL Server Compact
and non- SQL Server Subscribers.

[ @allow_push = ] 'allow_push'
Specifies if push subscriptions can be created for the given publication. allow_push is nvarchar(5), with a default
of TRUE, which allows push subscriptions on the publication.
[ @allow_pull = ] 'allow_pull'
Specifies if pull subscriptions can be created for the given publication. allow_pull is nvarchar(5), with a default of
TRUE, which allows pull subscriptions on the publication. You must specify true to support SQL Server Compact
Subscribers.
[ @allow_anonymous = ] 'allow_anonymous'
Specifies if anonymous subscriptions can be created for the given publication. allow_anonymous is nvarchar(5),
with a default of TRUE, which allows anonymous subscriptions on the publication. To support SQL Server Compact
Subscribers, you must specify true.
[ @enabled_for_internet = ] 'enabled_for_internet'
Specifies if the publication is enabled for the Internet, and determines if file transfer protocol (FTP) can be used to
transfer the snapshot files to a subscriber. enabled_for_internet is nvarchar(5), with a default of FALSE. If true, the
synchronization files for the publication are put into the C:\Program Files\Microsoft SQL
Server\MSSQL\MSSQL.x\Repldata\Ftp directory. The user must create the Ftp directory. If false, the publication is
not enabled for Internet access.
[ @centralized_conflicts =] 'centralized_conflicts'
This parameter has been deprecated and is only supported for the backward compatibility of scripts. Use
conflict_logging to specify the location where conflict records are stored.
[ @dynamic_filters =] 'dynamic_filters'
Enables the merge publication to use parameterized row filters. dynamic_filters is nvarchar(5), with a default of
FALSE.

NOTE
You should not specify this parameter but instead allow SQL Server to automatically determine if parameterized row filters
are being used. If you specify a value of true for dynamic_filters, you must define a parameterized row filter for the article.
For more information, see Define and Modify a Parameterized Row Filter for a Merge Article.

[ @snapshot_in_defaultfolder = ] 'snapshot_in_default_folder'
Specifies if the snapshot files are stored in the default folder. snapshot_in_default_folder is nvarchar(5), with a
default of TRUE. If true, snapshot files can be found in the default folder. If false, snapshot files will be stored in
the alternate location specified by alternate_snapshot_folder. Alternate locations can be on another server, on a
network drive, or on a removable media (such as CD-ROM or removable disks). You can also save the snapshot
files to a File Transfer Protocol (FTP) site, for retrieval by the Subscriber at a later time. Note that this parameter
can be true and still have a location specified by alt_snapshot_folder. This combination specifies that the snapshot
files will be stored in both the default and alternate locations.
[ @alt_snapshot_folder = ] 'alternate_snapshot_folder'
Specifies the location of the alternate folder for the snapshot. alternate_snapshot_folder is nvarchar(255), with a
default of NULL.
[ @pre_snapshot_script = ] 'pre_snapshot_script'
Specifies a pointer to an .sql file location. pre_snapshot_script is nvarchar(255), with a default of NULL. The
Merge Agent will run the pre-snapshot script before any of the replicated object scripts when applying the
snapshot at a Subscriber. The script is executed in the security context used by the Merge Agent when connecting
to the subscription database. Pre-snapshot scripts are not run on SQL Server Compact Subscribers.
[ @post_snapshot_script = ] 'post_snapshot_script'
Specifies a pointer to an .sql file location. post_snapshot_script is nvarchar(255), with a default of NULL. The
Merge Agent will run the post-snapshot script after all the other replicated object scripts and data have been
applied during an initial synchronization. The script is executed in the security context used by the Merge Agent
when connecting to the subscription database. Post-snapshot scripts are not run on SQL Server Compact
Subscribers.
[ @compress_snapshot = ] 'compress_snapshot'
Specifies that the snapshot written to the @alt_snapshot_folder location is to be compressed into the Microsoft
CAB format. compress_snapshot is nvarchar(5), with a default of FALSE. false specifies that the snapshot will not
be compressed; true specifies that the snapshot is to be compressed. Snapshot files that are larger than 2GB
cannot be compressed. Compressed snapshot files are uncompressed at the location where the Merge Agent runs;
pull subscriptions are typically used with compressed snapshots so that files are uncompressed at the Subscriber.
The snapshot in the default folder cannot be compressed. To support SQL Server Compact Subscribers, you must
specify false.
[ @ftp_address = ] 'ftp_address'
Is the network address of the FTP service for the Distributor. ftp_address is sysname, with a default of NULL.
Specifies where publication snapshot files are located for the Merge Agent of a subscriber to pick up. Since this
property is stored for each publication, each publication can have a different ftp_address. The publication must
support propagating snapshots using FTP.
[ @ftp_port= ] ftp_port
Is the port number of the FTP service for the Distributor. ftp_port is int, with a default of 21. Specifies where the
publication snapshot files are located for the Merge Agent of a subscriber to pick up. Since this property is stored
for each publication, each publication can have its own ftp_port.
[ @ftp_subdirectory = ] 'ftp_subdirectory'
Specifies where the snapshot files will be available for the Merge Agent of the subscriber to pick up if the
publication supports propagating snapshots using FTP. ftp_subdirectory is nvarchar(255), with a default of NULL.
Since this property is stored for each publication, each publication can have its own ftp_subdirctory or choose to
have no subdirectory, indicated with a NULL value.
When pre-generating snapshots for publications with parameterized filters, the data snapshot for each Subscriber
partition needs to be in its own folder. The directory structure for pre-generated snapshots using FTP must obey
the following structure:
alternate_snapshot_folder\ftp\publisher_publicationDB_publication\partitionID.

NOTE
The values above in italics will depend on the specifics of the publication and Subscriber partition.

[ @ftp_login = ] 'ftp_login'
Is the username used to connect to the FTP service. ftp_login is sysname, with a default of 'anonymous'.
[ @ftp_password = ] 'ftp_password'
Is the user password used to connect to the FTP service. ftp_password is sysname, with a default of NULL.

IMPORTANT
Do not use a blank password. Use a strong password.

[ @conflict_retention = ] conflict_retention
Specifies the retention period, in days, for which conflicts are retained. conflict_retention is int, with a default of 14
days before the conflict row is purged from the conflict table.
[ @keep_partition_changes = ] 'keep_partition_changes'
Specifies whether to enable partition change optimizations when precomputed partitions cannot be used.
keep_partition_changes is nvarchar(5), with a default of TRUE. false means that partition changes are not
optimized, and when precomputed partitions are not used, the partitions sent to all Subscribers will be verified
when data changes in a partition. true means that partition changes are optimized, and only Subscribers having
rows in the changed partitions are affected. When using precomputed partitions, set use_partition_groups to true
and set keep_partition_changes to false. For more information, see Optimize Parameterized Filter Performance
with Precomputed Partitions.

NOTE
If you specify a value of true for keep_partition_changes, specify a value of 1 for the Snapshot Agent parameter -
MaxNetworkOptimization. For more information about this parameter, see Replication Snapshot Agent. For information
about how to specify agent parameters, see Replication Agent Administration.

With SQL Server Compact subscribers, keep_partition_changes must be set to true to ensure that deletes are
correctly propagated. When set to false, the subscriber might have more rows than expected.
[ @allow_subscription_copy= ] 'allow_subscription_copy'
Enables or disables the ability to copy the subscription databases that subscribe to this publication.
allow_subscription_copy is nvarchar(5), with a default of FALSE. The size of the subscription database being
copied must be less than 2 gigabytes (GB).
[ @allow_synctoalternate = ] 'allow_synctoalternate'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @validate_subscriber_info = ] 'validate_subscriber_info'
Lists the functions that are used to define a Subscriber partition of the published data when parameterized row
filters are used. validate_subscriber_info is nvarchar(500), with a default of NULL. This information is used by the
Merge Agent to validate the Subscriber's partition. For example, if SUSER_SNAME is used in the parameterized
row filter, the parameter should be @validate_subscriber_info=N'SUSER_SNAME()' .

NOTE
You should not specify this parameter but instead allow SQL Server to automatically determine the filtering criterion.

[ @add_to_active_directory = ] 'add_to_active_directory'
This parameter has been deprecated and is only supported for the backward compatibility of scripts. You can no
longer add publication information to the Microsoft Active Directory.
[ @max_concurrent_merge = ] maximum_concurrent_merge
The maximum number of concurrent merge processes. maximum_concurrent_merge is int with a default of 0. A
value of 0 for this property means that there is no limit to the number of concurrent merge processes running at
any given time. This property sets a limit on the number of concurrent merge processes that can be run against a
merge publication at one time. If there are more merge processes scheduled at the same time than the value
allows to run, then the excess jobs will be put into a queue and wait until a currently-running merge process
finishes.
[ @max_concurrent_dynamic_snapshots =] max_concurrent_dynamic_snapshots
The maximum number of Snapshot Agent sessions that can be run concurrently to generate filtered data
snapshots for Subscriber partitions. maximum_concurrent_dynamic_snapshots is int with a default of 0. If 0, there
is no limit to the number snapshot sessions. If there are more snapshot processes scheduled at the same time than
the value allows to run, then the excess jobs will be put into a queue and wait until a currently-running snapshot
process finishes.
[ @use_partition_groups = ] 'use_partition_groups'
Specifies that precomputed partitions should be used to optimize the synchronization process.
use_partition_groups is nvarchar(5), and can be one of these values:

VALUE DESCRIPTION

true Publication uses precomputed partitions.

false Publication does not use precomputed partitions.

NULL(default) System decides on the partitioning strategy.

Precomputed partitions are used by default. To avoid using precomputed partitions, use_partition_groups must be
set to false. When NULL, the system will decide if precomputed partitions can be used. If precomputed partitions
cannot be used, then this value will effectively become false without generating any errors. In such cases,
keep_partition_changes can be set to true to provide some optimization. For more information, see Parameterized
Row Filters and Optimize Parameterized Filter Performance with Precomputed Partitions.
[ @publication_compatibility_level = ] backward_comp_level
Indicates the backward compatibility of the publication. backward_comp_level is nvarchar(6), and can be one of
these values:
VALUE VERSION

90RTM SQL Server 2005

100RTM SQL Server 2008

[ @replicate_ddl = ] replicate_ddl
Indicates if schema replication is supported for the publication. replicate_ddl is int, with a default of 1. 1 indicates
that data definition language (DDL) statements executed at the publisher are replicated, and 0 indicates that DDL
statements are not replicated. For more information, see Make Schema Changes on Publication Databases.
The @replicate_ddl parameter is honored when a DDL statement adds a column. The @replicate_ddl parameter is
ignored when a DDL statement alters or drops a column for the following reasons.
When a column is dropped, sysarticlecolumns must be updated to prevent new DML statements from
including the dropped column which would cause the distribution agent to fail. The @replicate_ddl
parameter is ignored because replication must always replicate the schema change.
When a column is altered, the source data type or nullability might have changed, causing DML statements
to contain a value that may not be compatible with the table at the subscriber. Such DML statements might
cause distribution agent to fail. The @replicate_ddl parameter is ignored because replication must always
replicate the schema change.
When a DDL statement adds a new column, sysarticlecolumns does not include the new column. DML
statements will not try to replicate data for the new column. The parameter is honored because either
replicating or not replicating the DDL is acceptable.
[ @allow_subscriber_initiated_snapshot = ] 'allow_subscriber_initiated_snapshot'
Indicates if Subscribers to this publication can initiate the snapshot process to generate the filtered
snapshot for their data partition. allow_subscriber_initiated_snapshot is nvarchar(5), with a default of
FALSE. true indicates that Subscribers can initiate the snapshot process.
[ @allow_web_synchronization = ] 'allow_web_synchronization'
Specifies if the publication is enabled for Web synchronization. allow_web_synchronization is nvarchar(5),
with a default of FALSE. true specifies that subscriptions to this publication can be synchronized over
HTTPS. For more information, see Web Synchronization for Merge Replication. To support SQL Server
Compact Subscribers, you must specify true.
[ @web_synchronization_url= ] 'web_synchronization_url'
Specifies the default value of the Internet URL used for Web synchronization. web_synchronization_url is
nvarchar(500), with a default of NULL. Defines the default Internet URL if one is not explicitly set when
sp_addmergepullsubscription_agent is executed.
[ @allow_partition_realignment = ] 'allow_partition_realignment'
Determines whether deletes are sent to the subscriber when modification of the row on the publisher
causes it to change its partition. allow_partition_realignment is nvarchar(5), with a default of TRUE. true
sends deletes to the Subscriber to reflect the results of a partition change by removing data that is no
longer part of the Subscriber's partition. false leaves the data from an old partition on the Subscriber,
where changes made to this data on the Publisher will not replicate to this Subscriber, but changes made
on the Subscriber will replicate to the Publisher. Setting allow_partition_realignment to false is used to
retain data in a subscription from an old partition when the data needs to be accessible for historical
purposes.
NOTE
Data that remains at the Subscriber as a result of setting allow_partition_realignment to false should be treated as if it
were read-only; however, this is not enforced by the replication system.

[ @retention_period_unit = ] 'retention_period_unit'
Specifies the units for the retention period set by retention. retention_period_unit is nvarchar(10), and can be one
of the following values.

VALUE VERSION

day (default) Retention period is specified in days.

week Retention period is specified in weeks.

month Retention period is specified in months.

year Retention period is specified in years.

[ @generation_leveling_threshold= ] generation_leveling_threshold
Specifies the number of changes that are contained in a generation. A generation is a collection of changes that
are delivered to a Publisher or Subscriber. generation_leveling_threshold is int, with a default value of 1000.
[ @automatic_reinitialization_policy = ] automatic_reinitialization_policy
Specifies whether changes are uploaded from the Subscriber before an automatic reinitialization required by a
change to the publication, where a value of 1 was specified for @force_reinit_subscription.
automatic_reinitialization_policy is bit, with a default value of 0. 1 means that changes are uploaded from the
Subscriber before an automatic reinitialization occurs.

IMPORTANT
If you add, drop, or change a parameterized filter, pending changes at the Subscriber cannot be uploaded to the Publisher
during reinitialization. If you want to upload pending changes, synchronize all subscriptions before changing the filter.

[ @conflict_logging = ] 'conflict_logging'
Specifies where conflict records are stored. conflict_logging is nvarchar(15), and can be one of the following
values:

VALUE DESCRIPTION

publisher Conflict records are stored at the Publisher.

subscriber Conflict records are stored at the Subscriber that caused the
conflict. Not supported for SQL Server Compact Subscribers.

both Conflict records are stored at both the Publisher and


Subscriber.

NULL (default) Replication automatically sets conflict_logging to both when


the value backward_comp_level is 90RTM and to publisher
in all other cases.
Return Code Values
0 (success) or 1 (failure)

Remarks
sp_addmergepublication is used in merge replication.
To list publication objects to the Active Directory using the @add_to_active_directory parameter, the SQL Server
object must already be created in the Active Directory.
If multiple publications exist that publish the same database object, only publications with a replicate_ddl value of
1 will replicate ALTER TABLE, ALTER VIEW, ALTER PROCEDURE, ALTER FUNCTION, and ALTER TRIGGER DDL
statements. However, an ALTER TABLE DROP COLUMN DDL statement will be replicated by all publications that
are publishing the dropped column.
For SQL Server Compact Subscribers, the value of alternate_snapshot_folder is only used when the value of
snapshot_in_default_folder is false.
With DDL replication enabled (replicate_ddl=1) for a publication, in order to make non-replicating DDL changes to
the publication, sp_changemergepublication (Transact-SQL) must first be executed to set replicate_ddl to 0. After
the non-replicating DDL statements have been issued, sp_changemergepublication can be run again to turn
DDL replication back on.

Example
-- To avoid storing the login and password in the script file, the value
-- is passed into SQLCMD as a scripting variable. For information about
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

--Declarations for adding a merge publication


DECLARE @publicationDB AS sysname;
DECLARE @publication AS sysname;
DECLARE @login AS sysname;
DECLARE @password AS sysname;
SET @publicationDB = N'AdventureWorks2012';
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @login = $(Login);
SET @password = $(Password);

-- Enable merge replication on the publication database, using defaults.


USE master
EXEC sp_replicationdboption
@dbname=@publicationDB,
@optname=N'merge publish',
@value = N'true'

-- Create a new merge publication, explicitly setting the defaults.


USE [AdventureWorks2012]
EXEC sp_addmergepublication
-- These parameters are optional.
@publication = @publication,
-- optional parameters
@description = N'Merge publication of AdventureWorks2012.',
@publication_compatibility_level = N'120RTM';

-- Create a new snapshot job for the publication.


EXEC sp_addpublication_snapshot
@publication = @publication,
@job_login = @login,
@job_password = @password;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addmergepublication.

See Also
Create a Publication
Publish Data and Database Objects
sp_changemergepublication (Transact-SQL)
sp_dropmergepublication (Transact-SQL)
sp_helpmergepublication (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_addmergepullsubscription (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a pull subscription to a merge publication. This stored procedure is executed at the Subscriber on the
subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_addmergepullsubscription [ @publication= ] 'publication'
[ , [ @publisher= ] 'publisher' ]
[ , [ @publisher_db = ] 'publisher_db' ]
[ , [ @subscriber_type= ] 'subscriber_type' ]
[ , [ @subscription_priority= ] subscription_priority ]
[ , [ @sync_type= ] 'sync_type' ]
[ , [ @description= ] 'description' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @publisher=] 'publisher'
Is the name of the Publisher. Publisher is sysname, with a default of the local server name. The Publisher must be
a valid server.
[ @publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default of NULL.
[ @subscriber_type=] 'subscriber_type'
Is the type of Subscriber. subscriber_type is nvarchar(15), and can be global, local or anonymous. In SQL Server
2005 and later versions, local subscriptions are referred to as client subscriptions and global subscriptions are
referred to as server subscriptions.
[ @subscription_priority=] subscription_priority
Is the subscription priority. subscription_priorityis real, with a default of NULL. For local and anonymous
subscriptions, the priority is 0.0. The priority is used by the default resolver to pick a winner when conflicts are
detected. For global subscribers, the subscription priority must be less than 100, which is the priority of the
publisher.
[ @sync_type=] 'sync_type'
Is the subscription synchronization type. sync_typeis nvarchar(15), with a default of automatic. Can be
automatic or none. If automatic, the schema and initial data for published tables are transferred to the
Subscriber first. If none, it is assumed the Subscriber already has the schema and initial data for published tables.
System tables and data are always transferred.
NOTE
We do not recommend specifying a value of none.

[ @description=] 'description'
Is a brief description of this pull subscription. descriptionis nvarchar(255), with a default of NULL. This value is
displayed by the Replication Monitor in the Friendly Name column, which can be used to sort the subscriptions
for a monitored publication.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addmergepullsubscription is used for merge replication.
If using SQL Server Agent to synchronize the subscription, the sp_addmergepullsubscription_agent stored
procedure must be run at the Subscriber to create an agent and job to synchronize with the Publication.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Execute this batch at the Subscriber.


DECLARE @publication AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB AS sysname;
DECLARE @hostname AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @publisher = $(PubServer);
SET @publicationDB = N'AdventureWorks2012';
SET @hostname = N'adventure-works\david8';

-- At the subscription database, create a pull subscription


-- to a merge publication.
USE [AdventureWorks2012Replica]
EXEC sp_addmergepullsubscription
@publisher = @publisher,
@publication = @publication,
@publisher_db = @publicationDB;

-- Add an agent job to synchronize the pull subscription.


EXEC sp_addmergepullsubscription_agent
@publisher = @publisher,
@publisher_db = @publicationDB,
@publication = @publication,
@distributor = @publisher,
@job_login = $(Login),
@job_password = $(Password),
@hostname = @hostname;
GO
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Publication must support anonymous Subscribers.


-- Execute this batch at the Subscriber.
DECLARE @publication AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB AS sysname;
DECLARE @websyncurl AS sysname;
DECLARE @security_mode AS int;
DECLARE @login AS sysname;
DECLARE @password AS nvarchar(512);
SET @publication = N'AdvWorksSalesOrdersMergeWebSync';
SET @publisher = $(PubServer);
SET @publicationDB = N'AdventureWorks2012';
SET @websyncurl = 'https://' + $(WebServer) + '/WebSync';
SET @security_mode = 0; -- Basic Authentication for IIS
SET @login = $(Login);
SET @password = $(Password);

-- At the subscription database, create a pull subscription


-- to a merge publication.
USE [AdventureWorks2012Replica]
EXEC sp_addmergepullsubscription
@publisher = @publisher,
@publication = @publication,
@publisher_db = @publicationDB,
@subscriber_type = N'anonymous';

-- Add an agent job to synchronize the pull subscription.


EXEC sp_addmergepullsubscription_agent
@publisher = @publisher,
@publisher_db = @publicationDB,
@publication = @publication,
@distributor = @publisher,
@job_login = @login,
@job_password = @password,
@use_web_sync = 1,
@internet_security_mode = @security_mode,
@internet_url = @websyncurl,
@internet_login = @login,
@internet_password = @password;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addmergepullsubscription.

See Also
Create a Pull Subscription
Subscribe to Publications
sp_addmergepullsubscription_agent (Transact-SQL)
sp_changemergepullsubscription (Transact-SQL)
sp_dropmergepullsubscription (Transact-SQL)
sp_helpmergepullsubscription (Transact-SQL)
sp_helpsubscription_properties (Transact-SQL)
sp_addmergepullsubscription_agent (Transact-SQL)
11/21/2017 • 11 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a new agent job used to schedule synchronization of a pull subscription to a merge publication. This stored
procedure is executed at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_addmergepullsubscription_agent [ [ @name = ] 'name' ]
, [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication =] 'publication'
[ , [ @publisher_security_mod e= ] publisher_security_mode ]
[ , [ @publisher_login = ] 'publisher_login' ]
[ , [ @publisher_password = ] 'publisher_password' ]
[ , [ @publisher_encrypted_password = ] publisher_encrypted_password ]
[ , [ @subscriber = ] 'subscriber' ]
[ , [ @subscriber_db = ] 'subscriber_db' ]
[ , [ @subscriber_security_mode = ] subscriber_security_mode ]
[ , [ @subscriber_login = ] 'subscriber_login' ]
[ , [ @subscriber_password= ] 'subscriber_password' ]
[ , [ @distributor = ] 'distributor' ]
[ , [ @distributor_security_mode = ] distributor_security_mode ]
[ , [ @distributor_login = ] 'distributor_login' ]
[ , [ @distributor_password = ] 'distributor_password' ]
[ , [ @encrypted_password = ] encrypted_password ]
[ , [ @frequency_type = ] frequency_type ]
[ , [ @frequency_interval = ] frequency_interval ]
[ , [ @frequency_relative_interval = ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor = ] frequency_recurrence_factor ]
[ , [ @frequency_subday = ] frequency_subday ]
[ , [ @frequency_subday_interval = ] frequency_subday_interval ]
[ , [ @active_start_time_of_day = ] active_start_time_of_day ]
[ , [ @active_end_time_of_day = ] active_end_time_of_day ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @optional_command_line = ] 'optional_command_line' ]
[ , [ @merge_jobid = ] merge_jobid ]
[ , [ @enabled_for_syncmgr = ] 'enabled_for_syncmgr' ]
[ , [ @ftp_address = ] 'ftp_address' ]
[ , [ @ftp_port = ] ftp_port ]
[ , [ @ftp_login = ] 'ftp_login' ]
[ , [ @ftp_password = ] 'ftp_password' ]
[ , [ @alt_snapshot_folder = ] 'alternate_snapshot_folder' ]
[ , [ @working_directory = ] 'working_directory' ]
[ , [ @use_ftp = ] 'use_ftp' ]
[ , [ @reserved = ] 'reserved' ]
[ , [ @use_interactive_resolver = ] 'use_interactive_resolver' ]
[ , [ @offloadagent = ] 'remote_agent_activation' ]
[ , [ @offloadserver = ] 'remote_agent_server_name']
[ , [ @job_name = ] 'job_name' ]
[ , [ @dynamic_snapshot_location = ] 'dynamic_snapshot_location' ]
[ , [ @use_web_sync = ] use_web_sync ]
[ , [ @internet_url = ] 'internet_url' ]
[ , [ @internet_login = ] 'internet_login' ]
[ , [ @internet_password = ] 'internet_password' ]
[ , [ @internet_security_mode = ] internet_security_mode ]
[ , [ @internet_timeout = ] internet_timeout ]
[ , [ @hostname = ] 'hostname' ]
[ , [ @job_login = ] 'job_login' ]
[ , [ @job_password = ] 'job_password' ]

Arguments
[ @name = ] 'name'
Is the name of the agent. name is sysname, with a default of NULL.
[ @publisher = ] 'publisher'
Is the name of the Publisher server. publisher is sysname, with no default.
[ @publisher_db = ] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @publisher_security_mode = ] publisher_security_mode
Is the security mode to use when connecting to a Publisher when synchronizing. publisher_security_mode is int,
with a default of 1. If 0, specifies SQL Server Authentication. If 1, specifies Windows Authentication.

IMPORTANT
When possible, use Windows Authentication.

[ @publisher_login = ] 'publisher_login'
Is the login to use when connecting to a Publisher when synchronizing. publisher_login is sysname, with a default
of NULL.
[ @publisher_password = ] 'publisher_password'
Is the password used when connecting to the Publisher. publisher_password is sysname, with a default of NULL.

IMPORTANT
Do not use a blank password. Use a strong password. When possible, prompt users to enter security credentials at runtime.
If you must store credentials in a script file, you must secure the file to prevent unauthorized access.

[ @publisher_encrypted_password = ]publisher_encrypted_password
Setting publisher_encrypted_password is no longer supported. Attempting to set this bit parameter to 1 will result
in an error.
[ @subscriber = ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[ @subscriber_db = ] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with a default of NULL.
[ @subscriber_security_mode = ] subscriber_security_mode
Is the security mode to use when connecting to a Subscriber when synchronizing. subscriber_security_mode is int,
with a default of 1. If 0, specifies SQL Server Authentication. If 1, specifies Windows Authentication.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The Merge Agent always
connects to the local Subscriber using Windows Authentication. If a value is specified for this parameter, a warning message
will be returned, but the value will be ignored.

[ @subscriber_login = ] 'subscriber_login'
Is the Subscriber login to use when connecting to a Subscriber when synchronizing. subscriber_login is required if
subscriber_security_mode is set to 0. subscriber_login is sysname, with a default of NULL.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. If a value is specified for this
parameter, a warning message will be returned, but the value will be ignored.
[ @subscriber_password = ] 'subscriber_password'
Is the Subscriber password for SQL Server Authentication. subscriber_password is required if
subscriber_security_mode is set to 0. subscriber_password is sysname, with a default of NULL.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. If a value is specified for this
parameter, a warning message will be returned, but the value will be ignored.

[ @distributor = ] 'distributor'
Is the name of the Distributor. distributor is sysname, with a default of publisher; that is, the Publisher is also the
Distributor.
[ @distributor_security_mode = ] distributor_security_mode
Is the security mode to use when connecting to a Distributor when synchronizing. distributor_security_mode is int,
with a default of 0. 0 specifies SQL Server Authentication. 1 specifies Windows Authentication.

IMPORTANT
When possible, use Windows Authentication.

[ @distributor_login = ] 'distributor_login'
Is the Distributor login to use when connecting to a Distributor when synchronizing. distributor_login is required if
distributor_security_mode is set to 0. distributor_login is sysname, with a default of NULL.
[ @distributor_password = ] 'distributor_password'
Is the Distributor password. distributor_password is required if distributor_security_mode is set to 0.
distributor_password is sysname, with a default of NULL.

IMPORTANT
Do not use a blank password. Use a strong password. When possible, prompt users to enter security credentials at runtime.
If you must store credentials in a script file, you must secure the file to prevent unauthorized access.

[ @encrypted_password = ] encrypted_password
Setting encrypted_password is no longer supported. Attempting to set this bit parameter to 1 will result in an
error.
[ @frequency_type = ] frequency_type
Is the frequency with which to schedule the Merge Agent. frequency_type is int, and can be one of the following
values.

VALUE DESCRIPTION

1 One time

2 On demand

4 Daily

8 Weekly

16 Monthly
VALUE DESCRIPTION

32 Monthly relative

64 Autostart

128 Recurring

NULL (default)

NOTE
Specifying a value of 64 causes the Merge Agent to run in continuous mode. This corresponds to setting the -Continuous
parameter for the agent. For more information, see Replication Merge Agent.

[ @frequency_interval = ] frequency_interval
The day or days that the Merge Agent runs. frequency_interval is int, and can be one of these values.

VALUE DESCRIPTION

1 Sunday

2 Monday

3 Tuesday

4 Wednesday

5 Thursday

6 Friday

7 Saturday

8 Day

9 Weekdays

10 Weekend days

NULL (default)

[ @frequency_relative_interval = ] frequency_relative_interval
Is the date of the Merge Agent. This parameter is used when frequency_type is set to 32 (monthly relative).
frequency_relative_interval is int, and can be one of these values.

VALUE DESCRIPTION

1 First

2 Second
VALUE DESCRIPTION

4 Third

8 Fourth

16 Last

NULL (default)

[ @frequency_recurrence_factor = ] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of NULL.
[ @frequency_subday = ] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of these values.

VALUE DESCRIPTION

1 Once

2 Second

4 Minute

8 Hour

NULL (default)

[ @frequency_subday_interval = ] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of NULL.
[ @active_start_time_of_day=] active_start_time_of_day
Is the time of day when the Merge Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is int,
with a default of NULL.
[ @active_end_time_of_day = ] active_end_time_of_day
Is the time of day when the Merge Agent stops being scheduled, formatted as HHMMSS. active_end_time_of_day
is int, with a default of NULL.
[ @active_start_date = ] active_start_date
Is the date when the Merge Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of NULL.
[ @active_end_date = ] active_end_date
Is the date when the Merge Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a
default of NULL.
[ @optional_command_line = ] 'optional_command_line'
Is an optional command prompt that is supplied to the Merge Agent. optional_command_line is nvarchar(255),
with a default of ' '. Can be used to supply additional parameters to the Merge Agent, such as in the following
example that increases the default query time-out to 600 seconds:

@optional_command_line = N'-QueryTimeOut 600'


[ @merge_jobid = ] merge_jobid
Is the output parameter for the job ID. merge_jobid is binary(16), with a default of NULL.
[ @enabled_for_syncmgr = ] 'enabled_for_syncmgr'
Specifies if the subscription can be synchronized through Windows Synchronization Manager.
enabled_for_syncmgr is nvarchar(5), with a default of FALSE. If false, the subscription is not registered with
Synchronization Manager. If true, the subscription is registered with Synchronization Manager and can be
synchronized without starting SQL Server Management Studio.
[ @ftp_address = ] 'ftp_address'
For backward compatibility only.
[ @ftp_port = ] ftp_port
For backward compatibility only.
[ @ftp_login = ] 'ftp_login'
For backward compatibility only.
[ @ftp_password = ] 'ftp_password'
For backward compatibility only.
[ @alt_snapshot_folder = ] 'alternate_snapshot_folder'
Specifies the location from which to pick up the snapshot files. alternate_snapshot_folder is nvarchar(255), with a
default of NULL. If NULL, the snapshot files will be picked up from the default location specified by the Publisher.
[ @working_directory = ] 'working_directory'
Is the name of the working directory used to temporarily store data and schema files for the publication when FTP
is used to transfer snapshot files. working_directory is nvarchar(255), with a default of NULL.
[ @use_ftp = ] 'use_ftp'
Specifies the use of FTP instead of the typical protocol to retrieve snapshots. use_ftp is nvarchar(5), with a default
of FALSE.
[ @reserved = ] 'reserved'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @use_interactive_resolver = ] 'use_interactive_resolver' ]
Uses interactive resolver to resolve conflicts for all articles that allow interactive resolution.
use_interactive_resolver is nvarchar(5), with a default of FALSE.
[ @offloadagent = ] 'remote_agent_activation'

NOTE
Remote agent activation has been deprecated and is no longer supported. This parameter is supported only to maintain
backward compatibility of scripts. Setting remote_agent_activation to a value other than false will generate an error.

[ @offloadserver = ] 'remote_agent_server_name'

NOTE
Remote agent activation has been deprecated and is no longer supported. This parameter is supported only to maintain
backward compatibility of scripts. Setting remote_agent_server_name to any non-NULL value will generate an error.

[ @job_name = ] 'job_name' ]
Is the name of an existing agent job. job_name is sysname, with a default value of NULL. This parameter is only
specified when the subscription will be synchronized using an existing job instead of a newly created job (the
default). If you are not a member of the sysadmin fixed server role, you must specify job_login and job_password
when you specify job_name.
[ @dynamic_snapshot_location = ] 'dynamic_snapshot_location' ]
The path to the folder where the snapshot files will be read from if a filtered data snapshot is to be used.
dynamic_snapshot_location is nvarchar(260), with a default of NULL. For more information, see Parameterized
Row Filters.
[ @use_web_sync = ] use_web_sync
Indicates that Web synchronization is enabled. use_web_sync is bit, with a default of 0. 1 specifies that the pull
subscription can be synchronized over the internet using HTTP.
[ @internet_url = ] 'internet_url'
Is the location of the replication listener (REPLISAPI.DLL) for Web synchronization. internet_url is nvarchar(260),
with a default of NULL. internet_url is a fully qualified URL, in the format
http://server.domain.com/directory/replisapi.dll . If the server is configured to listen on a port other than port
80, the port number must also be supplied in the format
http://server.domain.com:portnumber/directory/replisapi.dll , where portnumber represents the port.

[ @internet_login = ] 'internet_login'
Is the login that the Merge Agent uses when connecting to the Web server that is hosting Web synchronization
using HTTP Basic Authentication. internet_login is sysname, with a default of NULL.
[ @internet_password = ] 'internet_password'
Is the password that the Merge Agent uses when connecting to the Web server that is hosting Web
synchronization using HTTP Basic Authentication. internet_password is nvarchar(524), with a default value of
NULL.

IMPORTANT
Do not use a blank password. Use a strong password.

[ @internet_security_mode = ] internet_security_mode
Is the authentication method used by the Merge Agent when connecting to the Web server during Web
synchronization using HTTPS. internet_security_mode is int and can be one of these values.

VALUE DESCRIPTION

0 Basic Authentication is used.

1 (default) Windows Integrated Authentication is used.

NOTE
We recommend using Basic Authentication with Web synchronization. To use Web synchronization, you must make an SSL
connection to the Web server. For more information, see Configure Web Synchronization.

[ @internet_timeout = ] internet_timeout
Is the length of time, in seconds, before a Web synchronization request expires. internet_timeout is int, with a
default of 300 seconds.
[ @hostname = ] 'hostname'
Overrides the value of HOST_NAME() when this function is used in the WHERE clause of a parameterized filter.
hostname is sysname, with a default of NULL.
[ @job_login = ] 'job_login'
Is the login for the Windows account under which the agent runs. job_login is nvarchar(257), with no default. This
Windows account is always used for agent connections to the Subscriber and for connections to the Distributor
and Publisher when using Windows Integrated authentication.
[ @job_password = ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with no default.

IMPORTANT
Do not store authentication information in script files. For best security, login names and passwords should be supplied at
runtime.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addmergepullsubscription_agent is used in merge replication and uses functionality similar to
sp_addpullsubscription_agent.
For an example of how to correctly specify security settings when executing
sp_addmergepullsubscription_agent, see Create a Pull Subscription.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Execute this batch at the Subscriber.


DECLARE @publication AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB AS sysname;
DECLARE @hostname AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @publisher = $(PubServer);
SET @publicationDB = N'AdventureWorks2012';
SET @hostname = N'adventure-works\david8';

-- At the subscription database, create a pull subscription


-- to a merge publication.
USE [AdventureWorks2012Replica]
EXEC sp_addmergepullsubscription
@publisher = @publisher,
@publication = @publication,
@publisher_db = @publicationDB;

-- Add an agent job to synchronize the pull subscription.


EXEC sp_addmergepullsubscription_agent
@publisher = @publisher,
@publisher_db = @publicationDB,
@publication = @publication,
@distributor = @publisher,
@job_login = $(Login),
@job_password = $(Password),
@hostname = @hostname;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addmergepullsubscription_agent.

See Also
Create a Pull Subscription
Subscribe to Publications
sp_addmergepullsubscription (Transact-SQL)
sp_changemergepullsubscription (Transact-SQL)
sp_dropmergepullsubscription (Transact-SQL)
sp_helpmergepullsubscription (Transact-SQL)
sp_helpsubscription_properties (Transact-SQL)
sp_addmergepushsubscription_agent (Transact-SQL)
11/21/2017 • 6 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a new agent job used to schedule synchronization of a push subscription to a merge publication. This stored
procedure is executed at the Publisher on the publication database.

IMPORTANT
When configuring a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and
job_password, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its
remote Distributor before executing this stored procedure. For more information, see Enable Encrypted Connections to the
Database Engine (SQL Server Configuration Manager).

Transact-SQL Syntax Conventions

Syntax
sp_addmergepushsubscription_agent [ @publication =] 'publication'
[ , [ @subscriber = ] 'subscriber' ]
[ , [ @subscriber_db = ] 'subscriber_db' ]
[ , [ @subscriber_security_mode = ] subscriber_security_mode ]
[ , [ @subscriber_login = ] 'subscriber_login' ]
[ , [ @subscriber_password = ] 'subscriber_password' ]
[ , [ @publisher_security_mode = ] publisher_security_mode ]
[ , [ @publisher_login = ] 'publisher_login' ]
[ , [ @publisher_password = ] 'publisher_password' ]
[ , [ @job_login = ] 'job_login' ]
[ , [ @job_password = ] 'job_password' ]
[ , [ @job_name = ] 'job_name' ]
[ , [ @frequency_type = ] frequency_type ]
[ , [ @frequency_interval = ] frequency_interval ]
[ , [ @frequency_relative_interval = ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor = ] frequency_recurrence_factor ]
[ , [ @frequency_subday = ] frequency_subday ]
[ , [ @frequency_subday_interval = ] frequency_subday_interval ]
[ , [ @active_start_time_of_day = ] active_start_time_of_day ]
[ , [ @active_end_time_of_day = ] active_end_time_of_day ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @enabled_for_syncmgr = ] 'enabled_for_syncmgr' ]

Arguments
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @subscriber = ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[ @subscriber_db = ] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with a default of NULL.
[ @subscriber_security_mode = ] subscriber_security_mode
Is the security mode to use when connecting to a Subscriber when synchronizing. subscriber_security_mode is int,
with a default of 1. If 0, specifies SQL Server Authentication. If 1, specifies Windows Authentication.
[ @subscriber_login = ] 'subscriber_login'
Is the Subscriber login to use when connecting to a Subscriber when synchronizing. subscriber_login is required if
subscriber_security_mode is set to 0. subscriber_login is sysname, with a default of NULL.
[ @subscriber_password = ] 'subscriber_password'
Is the Subscriber password for SQL Server Authentication. subscriber_password is required if
subscriber_security_mode is set to 0. subscriber_password is sysname, with a default of NULL. If a subscriber
password is used, it is automatically encrypted.

IMPORTANT
When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must
secure the file to prevent unauthorized access.

[ @publisher_security_mode = ] publisher_security_mode
Is the security mode to use when connecting to a Publisher when synchronizing. publisher_security_mode is int,
with a default of 1. If 0, specifies SQL Server Authentication. If 1, specifies Windows Authentication.
[ @publisher_login = ] 'publisher_login'
Is the login to use when connecting to a Publisher when synchronizing. publisher_login is sysname, with a default
of NULL.
[ @publisher_password = ] 'publisher_password'
Is the password used when connecting to the Publisher. publisher_password is sysname, with a default of NULL.

IMPORTANT
When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must
secure the file to prevent unauthorized access.

[ @job_login = ] 'job_login'
Is the login for the Windows account under which the agent runs. job_login is nvarchar(257), with a default value
of NULL. This Windows account is always used for agent connections to the Distributor and for connections to the
Subscriber and Publisher when using Windows Integrated authentication.
[ @job_password = ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with no default.

IMPORTANT
When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must
secure the file to prevent unauthorized access.

[ @job_name = ] 'job_name'
Is the name of an existing agent job. job_name is sysname, with a default value of NULL. This parameter is only
specified when the subscription is synchronized using an existing job instead of a newly created job (the default). If
you are not a member of the sysadmin fixed server role, you must specify job_login and job_password when you
specify job_name.
[ @frequency_type = ] frequency_type
Is the frequency with which to schedule the Merge Agent. frequency_type is int, and can be one of the following
values.

VALUE DESCRIPTION

1 One time

2 On demand

4 Daily

8 Weekly

16 Monthly

32 Monthly relative

64 Autostart

128 Recurring

NULL (default)

NOTE
Specifying a value of 64 causes the Merge Agent to run in continuous mode. This corresponds to setting the -Continuous
parameter for the agent. For more information, see Replication Merge Agent.

[ @frequency_interval = ] frequency_interval
The days that the Merge Agent runs. frequency_interval is int, and can be one of the following values.

VALUE DESCRIPTION

1 Sunday

2 Monday

3 Tuesday

4 Wednesday

5 Thursday

6 Friday

7 Saturday

8 Day

9 Weekdays

10 Weekend days
VALUE DESCRIPTION

NULL (default)

[ @frequency_relative_interval = ] frequency_relative_interval
Is the date of the Merge Agent. This parameter is used when frequency_type is set to 32 (monthly relative).
frequency_relative_interval is int, and can be one of the following values.

VALUE DESCRIPTION

1 First

2 Second

4 Third

8 Fourth

16 Last

NULL (default)

[ @frequency_recurrence_factor = ] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of NULL.
[ @frequency_subday = ] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of the following
values.

VALUE DESCRIPTION

1 Once

2 Second

4 Minute

8 Hour

NULL (default)

[ @frequency_subday_interval = ] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of NULL.
[ @active_start_time_of_day = ] active_start_time_of_day
Is the time of day when the Merge Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is int,
with a default of NULL.
[ @active_end_time_of_day = ] active_end_time_of_day
Is the time of day when the Merge Agent stops being scheduled, formatted as HHMMSS. active_end_time_of_day
is int, with a default of NULL.
[ @active_start_date = ] active_start_date
Is the date when the Merge Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of NULL.
[ @active_end_date = ] active_end_date
Is the date when the Merge Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a
default of NULL.
[ @enabled_for_syncmgr = ] 'enabled_for_syncmgr'
Specifies if the subscription can be synchronized through Windows Synchronization Manager.
enabled_for_syncmgr is nvarchar(5), with a default of FALSE. If false, the subscription is not registered with
Synchronization Manager. If true, the subscription is registered with Synchronization Manager and can be
synchronized without starting SQL Server Management Studio.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addmergepushsubscription_agent is used in merge replication and uses functionality similar to
sp_addpushsubscription_agent.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @publication AS sysname;


DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
DECLARE @hostname AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorksReplica';
SET @hostname = N'adventure-works\david8'

-- Add a push subscription to a merge publication.


USE [AdventureWorks2012];
EXEC sp_addmergesubscription
@publication = @publication,
@subscriber = @subscriber,
@subscriber_db = @subscriptionDB,
@subscription_type = N'push',
@hostname = @hostname;

--Add an agent job to synchronize the push subscription.


EXEC sp_addmergepushsubscription_agent
@publication = @publication,
@subscriber = @subscriber,
@subscriber_db = @subscriptionDB,
@job_login = $(Login),
@job_password = $(Password);
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addmergepushsubscription_agent.
See Also
Create a Push Subscription
Subscribe to Publications
sp_addmergesubscription (Transact-SQL)
sp_changemergesubscription (Transact-SQL)
sp_dropmergesubscription (Transact-SQL)
sp_helpmergesubscription (Transact-SQL)
sp_addmergesubscription (Transact-SQL)
11/21/2017 • 6 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a push or pull merge subscription. This stored procedure is executed at the Publisher on the publication
database.
Transact-SQL Syntax Conventions

Syntax
sp_addmergesubscription [ @publication= ] 'publication'
[ , [ @subscriber = ] 'subscriber' ]
[ , [ @subscriber_db= ] 'subscriber_db' ]
[ , [ @subscription_type= ] 'subscription_type' ]
[ , [ @subscriber_type= ] 'subscriber_type' ]
[ , [ @subscription_priority= ] subscription_priority ]
[ , [ @sync_type= ] 'sync_type' ]
[ , [ @frequency_type= ] frequency_type ]
[ , [ @frequency_interval= ] frequency_interval ]
[ , [ @frequency_relative_interval= ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor= ] frequency_recurrence_factor ]
[ , [ @frequency_subday= ] frequency_subday ]
[ , [ @frequency_subday_interval= ] frequency_subday_interval ]
[ , [ @active_start_time_of_day= ] active_start_time_of_day ]
[ , [ @active_end_time_of_day= ] active_end_time_of_day ]
[ , [ @active_start_date= ] active_start_date ]
[ , [ @active_end_date= ] active_end_date ]
[ , [ @optional_command_line= ] 'optional_command_line' ]
[ , [ @description= ] 'description' ]
[ , [ @enabled_for_syncmgr= ] 'enabled_for_syncmgr' ]
[ , [ @offloadagent= ] remote_agent_activation]
[ , [ @offloadserver= ] 'remote_agent_server_name' ]
[ , [ @use_interactive_resolver= ] 'use_interactive_resolver' ]
[ , [ @merge_job_name= ] 'merge_job_name' ]
[ , [ @hostname = ] 'hostname'

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with no default. The publication must already exist.
[ @subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[ @subscriber_db=] 'subscriber_db'
Is the name of the subscription database. subscriber_dbis sysname, with a default of NULL.
[ @subscription_type=] 'subscription_type'
Is the type of subscription. subscription_typeis nvarchar(15), with a default of PUSH. If push, a push subscription
is added and the Merge Agent is added at the Distributor. If pull, a pull subscription is added without adding a
Merge Agent at the Distributor.
NOTE
Anonymous subscriptions do not need to use this stored procedure.

[ @subscriber_type=] 'subscriber_type'
Is the type of Subscriber. subscriber_typeis nvarchar(15), and can be one of the following values.

VALUE DESCRIPTION

local (default) Subscriber known only to the Publisher.

global Subscriber known to all servers.

In SQL Server 2005 and later versions, local subscriptions are referred to as client subscriptions, and global
subscriptions are referred to as server subscriptions
[ @subscription_priority=] subscription_priority
Is a number indicating the priority for the subscription. subscription_priorityis real, with a default of NULL. For
local and anonymous subscriptions, the priority is 0.0. For global subscriptions, the priority must be less than
100.0.
[ @sync_type=] 'sync_type'
Is the subscription synchronization type. sync_typeis nvarchar(15), with a default of automatic. Can be
automatic or none. If automatic, the schema and initial data for published tables are transferred to the
Subscriber first. If none, it is assumed the Subscriber already has the schema and initial data for published tables.
System tables and data are always transferred.

NOTE
We recommend to not specifying a value of none.

[ @frequency_type=] frequency_type
Is a value indicating when the Merge Agent will run. frequency_type is int, and can be one of the following values.

VALUE DESCRIPTION

1 Once

4 Daily

8 Weekly

10 Monthly

20 Monthly, relative to the frequency interval

40 When SQL Server Agent starts

NULL (default)

[ @frequency_interval=] frequency_interval
The day or days that the Merge Agent runs. frequency_interval is int, and can be one of the following values.
VALUE DESCRIPTION

1 Sunday

2 Monday

3 Tuesday

4 Wednesday

5 Thursday

6 Friday

7 Saturday

8 Day

9 Weekdays

10 Weekend days

NULL (default)

[ @frequency_relative_interval=] frequency_relative_interval
Is the scheduled merge occurrence of the frequency interval in each month. frequency_relative_interval is int, and
can be one of these values.

VALUE DESCRIPTION

1 First

2 Second

4 Third

8 Fourth

16 Last

NULL (default)

[ @frequency_recurrence_factor=] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factoris int, with a default of NULL.
[ @frequency_subday=] frequency_subday
Is the unit for frequency_subday_interval. frequency_subday is int, and can be one of the following values.

VALUE DESCRIPTION

1 Once

2 Second
VALUE DESCRIPTION

4 Minute

8 Hour

NULL (default)

[ @frequency_subday_interval=] frequency_subday_interval
Is the frequency for frequency_subday to occur between each merge. frequency_subday_interval is int, with a
default of NULL.
[ @active_start_time_of_day=] active_start_time_of_day
Is the time of day when the Merge Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is int,
with a default of NULL.
[ @active_end_time_of_day=] active_end_time_of_day
Is the time of day when the Merge Agent stops being scheduled, formatted as HHMMSS. active_end_time_of_day
is int, with a default of NULL.
[ @active_start_date=] active_start_date
Is the date when the Merge Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of NULL.
[ @active_end_date=] active_end_date
Is the date when the Merge Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a
default of NULL.
[ @optional_command_line=] 'optional_command_line'
Is the optional command prompt to execute. optional_command_lineis nvarchar(4000), with a default of NULL.
This parameter is used to add a command that captures the output and saves it to a file or to specify a
configuration file or attribute.
[ @description=] 'description'
Is a brief description of this merge subscription. descriptionis nvarchar(255), with a default of NULL. This value is
displayed by the Replication Monitor in the Friendly Name column, which can be used to sort the subscriptions
for a monitored publication.
[ @enabled_for_syncmgr=] 'enabled_for_syncmgr'
Specifies if the subscription can be synchronized through Microsoft Windows Synchronization Manager.
enabled_for_syncmgr is nvarchar(5), with a default of FALSE. If false, the subscription is not registered with
Synchronization Manager. If true, the subscription is registered with Synchronization Manager and can be
synchronized without starting Microsoft SQL Server Management Studio.
[ @offloadagent= ] remote_agent_activation
Specifies that the agent can be activated remotely. remote_agent_activation is bit with a default of 0.

NOTE
This parameter has been deprecated and is only maintained for backward compatibility of scripts.

[ @offloadserver= ] 'remote_agent_server_name'
Specifies the network name of server to be used for remote agent activation. remote_agent_server_nameis
sysname, with a default of NULL.
[ @use_interactive_resolver= ] 'use_interactive_resolver'
Allows conflicts to be resolved interactively for all articles that allow interactive resolution. use_interactive_resolver
is nvarchar(5), with a default of FALSE.
[ @merge_job_name= ] 'merge_job_name'
The @merge_job_name parameter is deprecated and cannot be set. merge_job_name is sysname, with a default
of NULL.
[ @hostname= ] 'hostname'
Overrides the value returned by HOST_NAME when this function is used in the WHERE clause of a parameterized
filter. Hostname is sysname, with a default of NULL.

IMPORTANT
For performance reasons, we recommend that you not apply functions to column names in parameterized row filter clauses,
such as LEFT([MyColumn]) = SUSER_SNAME() . If you use HOST_NAME in a filter clause and override the HOST_NAME
value, it might be necessary to convert data types using CONVERT. For more information about best practices for this case,
see the section "Overriding the HOST_NAME() Value" in the topic Parameterized Row Filters.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addmergesubscription is used in merge replication.
When sp_addmergesubscription is executed by a member of the sysadmin fixed server role to create a push
subscription, the Merge Agent job is implicitly created and runs under the SQL Server Agent service account. We
recommend that you execute sp_addmergepushsubscription_agent and specify the credentials of a different,
agent-specific Windows account for @job_login and @job_password. For more information, see Replication
Agent Security Model.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @publication AS sysname;


DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
DECLARE @hostname AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorksReplica';
SET @hostname = N'adventure-works\david8'

-- Add a push subscription to a merge publication.


USE [AdventureWorks2012];
EXEC sp_addmergesubscription
@publication = @publication,
@subscriber = @subscriber,
@subscriber_db = @subscriptionDB,
@subscription_type = N'push',
@hostname = @hostname;

--Add an agent job to synchronize the push subscription.


EXEC sp_addmergepushsubscription_agent
@publication = @publication,
@subscriber = @subscriber,
@subscriber_db = @subscriptionDB,
@job_login = $(Login),
@job_password = $(Password);
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addmergesubscription.

See Also
Create a Push Subscription
Create a Pull Subscription
Interactive Conflict Resolution
Subscribe to Publications
sp_changemergesubscription (Transact-SQL)
sp_dropmergesubscription (Transact-SQL)
sp_helpmergesubscription (Transact-SQL)
sp_addpublication (Transact-SQL)
11/21/2017 • 17 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates a snapshot or transactional publication. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_addpublication [ @publication = ] 'publication'
[ , [ @taskid = ] tasked ]
[ , [ @restricted = ] 'restricted' ]
[ , [ @sync_method = ] 'sync_method' ]
[ , [ @repl_freq = ] 'repl_freq' ]
[ , [ @description = ] 'description' ]
[ , [ @status = ] 'status' ]
[ , [ @independent_agent = ] 'independent_agent' ]
[ , [ @immediate_sync = ] 'immediate_sync' ]
[ , [ @enabled_for_internet = ] 'enabled_for_internet' ]
[ , [ @allow_push = ] 'allow_push'
[ , [ @allow_pull = ] 'allow_pull' ]
[ , [ @allow_anonymous = ] 'allow_anonymous' ]
[ , [ @allow_sync_tran = ] 'allow_sync_tran' ]
[ , [ @autogen_sync_procs = ] 'autogen_sync_procs' ]
[ , [ @retention = ] retention ]
[ , [ @allow_queued_tran= ] 'allow_queued_updating' ]
[ , [ @snapshot_in_defaultfolder= ] 'snapshot_in_default_folder' ]
[ , [ @alt_snapshot_folder= ] 'alternate_snapshot_folder' ]
[ , [ @pre_snapshot_script= ] 'pre_snapshot_script' ]
[ , [ @post_snapshot_script= ] 'post_snapshot_script' ]
[ , [ @compress_snapshot= ] 'compress_snapshot' ]
[ , [ @ftp_address = ] 'ftp_address' ]
[ , [ @ftp_port= ] ftp_port ]
[ , [ @ftp_subdirectory = ] 'ftp_subdirectory' ]
[ , [ @ftp_login = ] 'ftp_login' ]
[ , [ @ftp_password = ] 'ftp_password' ]
[ , [ @allow_dts = ] 'allow_dts' ]
[ , [ @allow_subscription_copy = ] 'allow_subscription_copy' ]
[ , [ @conflict_policy = ] 'conflict_policy' ]
[ , [ @centralized_conflicts = ] 'centralized_conflicts' ]
[ , [ @conflict_retention = ] conflict_retention ]
[ , [ @queue_type = ] 'queue_type' ]
[ , [ @add_to_active_directory = ] 'add_to_active_directory' ]
[ , [ @logreader_job_name = ] 'logreader_agent_name' ]
[ , [ @qreader_job_name = ] 'queue_reader_agent_name' ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @allow_initialize_from_backup = ] 'allow_initialize_from_backup' ]
[ , [ @replicate_ddl = ] replicate_ddl ]
[ , [ @enabled_for_p2p = ] 'enabled_for_p2p' ]
[ , [ @publish_local_changes_only = ] 'publish_local_changes_only' ]
[ , [ @enabled_for_het_sub = ] 'enabled_for_het_sub' ]
[ , [ @p2p_conflictdetection = ] 'p2p_conflictdetection' ]
[ , [ @p2p_originator_id = ] p2p_originator_id
[ , [ @p2p_continue_onconflict = ] 'p2p_continue_onconflict'
[ , [ @allow_partition_switch = ] 'allow_partition_switch'
[ , [ @replicate_partition_switch = ]'replicate_partition_switch'

Arguments
[ @publication=] 'publication'
Is the name of the publication to create. publication is sysname, with no default. The name must be unique within
the database.
[ @taskid=] taskid
Supported for backward compatibility only; use sp_addpublication_snapshot (Transact-SQL).
[ @restricted=] 'restricted'
Supported for backward compatibility only; use default_access.
[ @sync_method=] 'sync_method'
Is the synchronization mode. sync_method is nvarchar(13), and can be one of the following values.
VALUE DESCRIPTION

native Produces native-mode bulk copy program output of all


tables. Not supported for Oracle Publishers.

character Produces character-mode bulk copy program output of all


tables. For an Oracle Publisher, character is valid only for
snapshot replication.

concurrent Produces native-mode bulk copy program output of all tables


but does not lock tables during the snapshot. Only supported
for transactional publications. Not supported for Oracle
Publishers.

concurrent_c Produces character-mode bulk copy program output of all


tables but does not lock tables during the snapshot. Only
supported for transactional publications.

database snapshot Produces native-mode bulk copy program output of all tables
from a database snapshot. Database snapshots are not
available in every edition of Microsoft SQL Server. For a list of
features that are supported by the editions of SQL Server, see
Features Supported by the Editions of SQL Server 2016.

database snapshot character Produces character-mode bulk copy program output of all
tables from a database snapshot. Database snapshots are not
available in every edition of Microsoft SQL Server. For a list of
features that are supported by the editions of SQL Server, see
Features Supported by the Editions of SQL Server 2016.

NULL (default) Defaults to native for Microsoft SQL Server Publishers. For
non- SQL Server Publishers, defaults to character when the
value of repl_freq is Snapshot and to concurrent_c for all
other cases.

[ @repl_freq=] 'repl_freq'
Is the type of replication frequency, repl_freq is nvarchar(10), and can be one of the following values.

VALUE DESCRIPTION

continuous (default) Publisher provides output of all log-based transactions. For


non- SQL Server Publishers, this requires that sync_method
be set to concurrent_c.

snapshot Publisher produces only scheduled synchronization events.


For non- SQL Server Publishers, this requires that
sync_method be set to character.

[ @description=] 'description'
Is an optional description for the publication. description is nvarchar(255), with a default of NULL.
[ @status=] 'status'
Specifies if publication data is available. status is nvarchar(8), and can be one of the following values.

VALUE DESCRIPTION

active Publication data is available for Subscribers immediately.


VALUE DESCRIPTION

inactive (default) Publication data is not available for Subscribers when the
publication is first created (they can subscribe, but the
subscriptions are not processed).

Not supported for Oracle Publishers.


[ @independent_agent=] 'independent_agent'
Specifies if there is a stand-alone Distribution Agent for this publication. independent_agent is nvarchar(5), with
a default of FALSE. If true, there is a stand-alone Distribution Agent for this publication. If false, the publication
uses a shared Distribution Agent, and each Publisher database/Subscriber database pair has a single, shared
Agent.
[ @immediate_sync=] 'immediate_synchronization'
Specifies if the synchronization files for the publication are created each time the Snapshot Agent runs.
immediate_synchronization is nvarchar(5), with a default of FALSE. If true, the synchronization files are created
or re-created each time the Snapshot Agent runs. Subscribers are able to get the synchronization files
immediately if the Snapshot Agent has completed before the subscription is created. New subscriptions get the
newest synchronization files generated by the most recent execution of the Snapshot Agent. independent_agent
must be true for immediate_synchronization to be true. If false, the synchronization files are created only if there
are new subscriptions. You must call sp_addsubscription for each subscription when you incrementally add a new
article to an existing publication. Subscribers cannot receive the synchronization files after the subscription until
the Snapshot Agents are started and completed.
[ @enabled_for_internet=] 'enabled_for_internet'
Specifies if the publication is enabled for the Internet, and determines if file transfer protocol (FTP) can be used to
transfer the snapshot files to a subscriber. enabled_for_internet is nvarchar(5), with a default of FALSE. If true,
the synchronization files for the publication are put into the C:\Program Files\Microsoft SQL
Server\MSSQL\MSSQL.x\Repldata\Ftp directory. The user must create the Ftp directory.
[ @allow_push=] 'allow_push'
Specifies if push subscriptions can be created for the given publication. allow_push is nvarchar(5), with a default
of TRUE, which allows push subscriptions on the publication.
[ @allow_pull=] 'allow_pull'
Specifies if pull subscriptions can be created for the given publication. allow_pull is nvarchar(5), with a default of
FALSE. If false, pull subscriptions are not allowed on the publication.
[ @allow_anonymous=] 'allow_anonymous'
Specifies if anonymous subscriptions can be created for the given publication. allow_anonymous is nvarchar(5),
with a default of FALSE. If true, immediate_synchronization must also be set to true. If false, anonymous
subscriptions are not allowed on the publication.
[ @allow_sync_tran=] 'allow_sync_tran'
Specifies if immediate-updating subscriptions are allowed on the publication. allow_sync_tran is nvarchar(5),
with a default of FALSE. true is Not supported for Oracle Publishers.
[ @autogen_sync_procs=] 'autogen_sync_procs'
Specifies if the synchronizing stored procedure for updating subscriptions is generated at the Publisher.
autogen_sync_procs is nvarchar(5), and can be one of the following values.

VALUE DESCRIPTION

true Set automatically when updating subscriptions is enabled.


VALUE DESCRIPTION

false Set automatically when updating subscriptions is not enabled


or for Oracle Publishers.

NULL (default) Defaults to true when updating subscriptions is enabled and


to false when updating subscriptions is not enabled.

NOTE
The user supplied value for autogen_sync_procswill be overridden depending on the values specified for allow_queued_tran
and allow_sync_tran.

[ @retention=] retention
Is the retention period in hours for subscription activity. retention is int, with a default of 336 hours. If a
subscription is not active within the retention period, it expires and is removed. The value can be greater than the
maximum retention period of the distribution database used by the Publisher. If 0, well-known subscriptions to
the publication will never expire and be removed by the Expired Subscription Cleanup Agent.
[ @allow_queued_tran= ] 'allow_queued_updating'
Enables or disables queuing of changes at the Subscriber until they can be applied at the Publisher.
allow_queued_updating is nvarchar(5) with a default of FALSE. If false, changes at the Subscriber are not
queued. true is Not supported for Oracle Publishers.
[ @snapshot_in_defaultfolder= ] 'snapshot_in_default_folder'
Specifies if snapshot files are stored in the default folder. snapshot_in_default_folder is nvarchar(5) with a default
of TRUE. If true, snapshot files can be found in the default folder. If false, snapshot files have been stored in the
alternate location specified by alternate_snapshot_folder. Alternate locations can be on another server, on a
network drive, or on removable media (such as CD-ROM or removable disks). You can also save the snapshot files
to an FTP site, for retrieval by the Subscriber at a later time. Note that this parameter can be true and still have a
location in the @alt_snapshot_folder parameter. This combination specifies that the snapshot files will be stored
in both the default and alternate locations.
[ @alt_snapshot_folder= ] 'alternate_snapshot_folder'
Specifies the location of the alternate folder for the snapshot. alternate_snapshot_folder is nvarchar(255) with a
default of NULL.
[ @pre_snapshot_script= ] 'pre_snapshot_script'
Specifies a pointer to an .sql file location. pre_snapshot_script is nvarchar(255),with a default of NULL. The
Distribution Agent will run the pre-snapshot script before running any of the replicated object scripts when
applying a snapshot at a Subscriber. The script is executed in the security context used by the Distribution Agent
when connecting to the subscription database.
[ @post_snapshot_script= ] 'post_snapshot_script'
Specifies a pointer to an .sql file location. post_snapshot_script is nvarchar(255), with a default of NULL. The
Distribution Agent will run the post-snapshot script after all the other replicated object scripts and data have been
applied during an initial synchronization. The script is executed in the security context used by the Distribution
Agent when connecting to the subscription database.
[ @compress_snapshot= ] 'compress_snapshot'
Specifies that the snapshot that is written to the @alt_snapshot_folder location is to be compressed into the
Microsoft CAB format. compress_snapshot is nvarchar(5), with a default of FALSE. false specifies that the
snapshot will not be compressed; true specifies that the snapshot will be compressed. Snapshot files that are
larger than 2 gigabytes (GB) cannot be compressed. Compressed snapshot files are uncompressed at the location
where the Distribution Agent runs; pull subscriptions are typically used with compressed snapshots so that files
are uncompressed at the Subscriber. The snapshot in the default folder cannot be compressed.
[ @ftp_address = ] 'ftp_address'
Is the network address of the FTP service for the Distributor. ftp_address is sysname, with a default of NULL.
Specifies where publication snapshot files are located for the Distribution Agent or Merge Agent of a subscriber to
pick up. Since this property is stored for each publication, each publication can have a different ftp_address. The
publication must support propagating snapshots using FTP.
[ @ftp_port= ] ftp_port
Is the port number of the FTP service for the Distributor. ftp_port is int, with a default of 21. Specifies where the
publication snapshot files are located for the Distribution Agent or Merge Agent of a subscriber to pick up. Since
this property is stored for each publication, each publication can have its own ftp_port.
[ @ftp_subdirectory = ] 'ftp_subdirectory'
Specifies where the snapshot files will be available for the Distribution Agent or Merge Agent of subscriber to pick
up if the publication supports propagating snapshots using FTP. ftp_subdirectory is nvarchar(255), with a default
of NULL. Since this property is stored for each publication, each publication can have its own ftp_subdirctory or
choose to have no subdirectory, indicated with a NULL value.
[ @ftp_login = ] 'ftp_login'
Is the username used to connect to the FTP service. ftp_login is sysname, with a default of ANONYMOUS.
[ @ftp_password = ] 'ftp_password'
Is the user password used to connect to the FTP service. ftp_password is sysname, with a default of NULL.
[ @allow_dts = ] 'allow_dts'
Specifies that the publication allows data transformations. You can specify a DTS package when creating a
subscription. allow_transformable_subscriptions is nvarchar(5) with a default of FALSE, which does not allow DTS
transformations. When allow_dts is true, sync_method must be set to either character or concurrent_c.
true is not supported for Oracle Publishers.
[ @allow_subscription_copy = ] 'allow_subscription_copy'
Enables or disables the ability to copy the subscription databases that subscribe to this publication.
allow_subscription_copy isnvarchar(5), with a default of FALSE.
[ @conflict_policy = ] 'conflict_policy'
Specifies the conflict resolution policy followed when the queued updating subscriber option is used.
conflict_policy is nvarchar(100) with a default of NULL, and can be one of the following values.

VALUE DESCRIPTION

pub wins Publisher wins the conflict.

sub reinit Reinitialize the subscription.

sub wins Subscriber wins the conflict.

NULL (default) If NULL, and the publication is a snapshot publication, the


default policy becomes sub reinit. If NULL and the
publication is not a snapshot publication, the default becomes
pub wins.

Not supported for Oracle Publishers.


[ @centralized_conflicts = ] 'centralized_conflicts'
Specifies if conflict records are stored on the Publisher. centralized_conflicts is nvarchar(5), with a default of
TRUE. If true, conflict records are stored at the Publisher. If false, conflict records are stored at both the publisher
and at the subscriber that caused the conflict. Not supported for Oracle Publishers.
[ @conflict_retention = ] conflict_retention
Specifies the conflict retention period, in days. This is the period of time that conflict metadata is stored for peer-
to-peer transactional replication and queued updating subscriptions. conflict_retention is int, with a default of 14.
Not supported for Oracle Publishers.
[ @queue_type = ] 'queue_type'
Specifies which type of queue is used. queue_type is nvarchar(10), with a default of NULL, and can be one of
these values.

VALUE DESCRIPTION

sql Use SQL Server to store transactions.

NULL (default) Defaults to sql, which specifies to use SQL Server to store
transactions.

NOTE
Support for using Microsoft Message Queuing has been discontinued. Specifying a value of msmq will result in a warning,
and replication will automatically set the value to sql.

Not supported for Oracle Publishers.


[ @add_to_active_directory = ] 'add_to_active_directory'
This parameter has been deprecated and is only supported for the backward compatibility of scripts. You can no
longer add publication information to the Microsoft Active Directory.
[ @logreader_job_name = ] 'logreader_agent_name'
Is the name of an existing agent job. logreader_agent_name is sysname, with a default value of NULL. This
parameter is only specified when the Log Reader Agent will use an existing job instead of a new one being
created.
[ @qreader_job_name = ] 'queue_reader_agent_name'
Is the name of an existing agent job. queue_reader_agent_name is sysname, with a default value of NULL. This
parameter is only specified when the Queue Reader Agent will use an existing job instead of a new one being
created.
[ @publisher = ] 'publisher'
Specifies a non- SQL Server publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when adding a publication to a SQL Server Publisher.

[ @allow_initialize_from_backup = ] 'allow_initialize_from_backup'
Indicates if Subscribers can initialize a subscription to this publication from a backup rather than an initial
snapshot. allow_initialize_from_backup is nvarchar(5), and can be one of these values:
VALUE DESCRIPTION

true Enables initialization from a backup.

false Disables initialization from a backup.

NULL (default) Defaults to true for a publication in a peer-to-peer replication


topology and false for all other publications.

For more information, see Initialize a Transactional Subscription Without a Snapshot.

WARNING
To avoid missing subscriber data, when using sp_addpublication with @allow_initialize_from_backup = N'true' ,
always use @immediate_sync = N'true' .

[ @replicate_ddl = ] replicate_ddl
Indicates if schema replication is supported for the publication. replicate_ddl is int, with a default of 1 for SQL
Server Publishers and 0 for non- SQL Server Publishers. 1 indicates that data definition language (DDL)
statements executed at the publisher are replicated, and 0 indicates that DDL statements are not replicated.
Schema replication is not supported for Oracle Publishers. For more information, see Make Schema Changes on
Publication Databases.
The @replicate_ddl parameter is honored when a DDL statement adds a column. The @replicate_ddl parameter is
ignored when a DDL statement alters or drops a column for the following reasons.
When a column is dropped, sysarticlecolumns must be updated to prevent new DML statements from
including the dropped column which would cause the distribution agent to fail. The @replicate_ddl
parameter is ignored because replication must always replicate the schema change.
When a column is altered, the source data type or nullability might have changed, causing DML statements
to contain a value that may not be compatible with the table at the subscriber. Such DML statements might
cause distribution agent to fail. The @replicate_ddl parameter is ignored because replication must always
replicate the schema change.
When a DDL statement adds a new column, sysarticlecolumns does not include the new column. DML
statements will not try to replicate data for the new column. The parameter is honored because either
replicating or not replicating the DDL is acceptable.
[ @enabled_for_p2p = ] 'enabled_for_p2p'
Enables the publication to be used in a peer-to-peer replication topology. enabled_for_p2p is nvarchar(5),
with a default of FALSE. true indicates that the publication supports peer-to-peer replication. When setting
enabled_for_p2p to true, the following restrictions apply:
allow_anonymous must be false.
allow_dts must be false.
allow_initialize_from_backup must be true.
allow_queued_tran must be false.
allow_sync_tran must be false.
conflict_policy must be false.
independent_agent must be true.
repl_freq must be continuous.
replicate_ddl must be 1.
For more information, see Peer-to-Peer Transactional Replication.
[ @publish_local_changes_only = ] 'publish_local_changes_only'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @enabled_for_het_sub= ] 'enabled_for_het_sub'
Enables the publication to support non- SQL Server Subscribers. enabled_for_het_sub is nvarchar(5) with
a default value of FALSE. A value of true means that the publication supports non- SQL Server Subscribers.
When enabled_for_het_sub is true, the following restrictions apply:
allow_initialize_from_backup must be false.
allow_push must be true.
allow_queued_tran must be false.
allow_subscription_copy must be false.
allow_sync_tran must be false.
autogen_sync_procs must be false.
conflict_policy must be NULL.
enabled_for_internet must be false.
enabled_for_p2p must be false.
ftp_address must be NULL.
ftp_subdirectory must be NULL.
ftp_password must be NULL.
pre_snapshot_script must be NULL.
post_snapshot_script must be NULL.
replicate_ddl must be 0.
qreader_job_name must be NULL.
queue_type must be NULL.
sync_method cannot be native or concurrent.
For more information, see Non-SQL Server Subscribers.
[ @p2p_conflictdetection= ] 'p2p_conflictdetection'
Enables the Distribution Agent to detect conflicts if the publication is enabled for peer-to-peer replication.
p2p_conflictdetection is nvarchar(5) with a default value of TRUE. For more information, see Conflict
Detection in Peer-to-Peer Replication.
[ @p2p_originator_id= ] p2p_originator_id
Specifies an ID for a node in a peer-to-peer topology. p2p_originator_id is int, with a default of NULL. This
ID is used for conflict detection if p2p_conflictdetection is set to TRUE. Specify a positive, non-zero ID that
has never been used in the topology. For a list of IDs that have already been used, execute
sp_help_peerconflictdetection.
[ @p2p_continue_onconflict= ] 'p2p_continue_onconflict'
Determines whether the Distribution Agent continues to process changes after a conflict is detected.
p2p_continue_onconflict is nvarchar(5) with a default value of FALSE.
Cau t i on

We recommend that you use the default value of FALSE. When this option is set to TRUE, the Distribution Agent
tries to converge data in the topology by applying the conflicting row from the node that has the highest
originator ID. This method does not guarantee convergence. You should make sure that the topology is consistent
after a conflict is detected. For more information, see "Handling Conflicts" in Conflict Detection in Peer-to-Peer
Replication.
[ @allow_partition_switch= ] 'allow_partition_switch'
Specifies whether ALTER TABLE…SWITCH statements can be executed against the published database.
allow_partition_switch is nvarchar(5) with a default value of FALSE. For more information, see Replicate
Partitioned Tables and Indexes.
[ @replicate_partition_switch= ] 'replicate_partition_switch'
Specifies whether ALTER TABLE…SWITCH statements that are executed against the published database should be
replicated to Subscribers. replicate_partition_switch is nvarchar(5) with a default value of FALSE. This option is
valid only if allow_partition_switch is set to TRUE.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addpublication is used in snapshot replication and transactional replication.
If multiple publications exist that publish the same database object, only publications with a replicate_ddl value of
1 will replicate ALTER TABLE, ALTER VIEW, ALTER PROCEDURE, ALTER FUNCTION, and ALTER TRIGGER DDL
statements. However, an ALTER TABLE DROP COLUMN DDL statement will be replicated by all publications that
are publishing the dropped column.
With DDL replication enabled (replicate_ddl = 1) for a publication, in order to make non-replicating DDL changes
to the publication, sp_changepublication must first be executed to set replicate_ddl to 0. After the non-replicating
DDL statements have been issued, sp_changepublication can be run again to turn DDL replication back on.

Example
-- To avoid storing the login and password in the script file, the values
-- are passed into SQLCMD as scripting variables. For information about
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

DECLARE @publicationDB AS sysname;


DECLARE @publication AS sysname;
DECLARE @login AS sysname;
DECLARE @password AS sysname;
SET @publicationDB = N'AdventureWorks';
SET @publication = N'AdvWorksProductTran';
-- Windows account used to run the Log Reader and Snapshot Agents.
SET @login = $(Login);
-- This should be passed at runtime.
SET @password = $(Password);

-- Enable transactional or snapshot replication on the publication database.


EXEC sp_replicationdboption
@dbname=@publicationDB,
@optname=N'publish',
@value = N'true';

-- Execute sp_addlogreader_agent to create the agent job.


EXEC sp_addlogreader_agent
@job_login = @login,
@job_password = @password,
-- Explicitly specify the use of Windows Integrated Authentication (default)
-- when connecting to the Publisher.
@publisher_security_mode = 1;

-- Create a new transactional publication with the required properties.


EXEC sp_addpublication
@publication = @publication,
@status = N'active',
@allow_push = N'true',
@allow_pull = N'true',
@independent_agent = N'true';

-- Create a new snapshot job for the publication, using a default schedule.
EXEC sp_addpublication_snapshot
@publication = @publication,
@job_login = @login,
@job_password = @password,
-- Explicitly specify the use of Windows Integrated Authentication (default)
-- when connecting to the Publisher.
@publisher_security_mode = 1;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addpublication. Windows authentication logins must have a user account in the database representing their
Windows user account. A user account representing a Windows group is not sufficient.

See Also
sp_addlogreader_agent (Transact-SQL)
sp_addpublication_snapshot (Transact-SQL)
sp_changepublication (Transact-SQL)
sp_droppublication (Transact-SQL)
sp_helppublication (Transact-SQL)
sp_replicationdboption (Transact-SQL)
Publish Data and Database Objects
Replication Stored Procedures (Transact-SQL)
sp_addpublication_snapshot (Transact-SQL)
11/21/2017 • 6 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates the Snapshot Agent for the specified publication. This stored procedure is executed at the Publisher on the
publication database.

IMPORTANT
When configuring a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and
job_password, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its
remote Distributor before executing this stored procedure. For more information, see Enable Encrypted Connections to the
Database Engine (SQL Server Configuration Manager).

Transact-SQL Syntax Conventions

Syntax
sp_addpublication_snapshot [ @publication= ] 'publication'
[ , [ @frequency_type= ] frequency_type ]
[ , [ @frequency_interval= ] frequency_interval ]
[ , [ @frequency_subday= ] frequency_subday ]
[ , [ @frequency_subday_interval= ] frequency_subday_interval ]
[ , [ @frequency_relative_interval= ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor= ] frequency_recurrence_factor ]
[ , [ @active_start_date= ] active_start_date ]
[ , [ @active_end_date= ] active_end_date ]
[ , [ @active_start_time_of_day= ] active_start_time_of_day ]
[ , [ @active_end_time_of_day= ] active_end_time_of_day ]
[ , [ @snapshot_job_name = ] 'snapshot_agent_name' ]
[ , [ @publisher_security_mode = ] publisher_security_mode ]
[ , [ @publisher_login = ] 'publisher_login' ]
[ , [ @publisher_password = ] 'publisher_password' ]
[ , [ @job_login = ] 'job_login' ]
[ , [ @job_password = ] 'job_password' ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @frequency_type=] frequency_type
Is the frequency with which the Snapshot Agent is executed. frequency_type is int, and can be one of the following
values.

VALUE DESCRIPTION

1 Once.
VALUE DESCRIPTION

4 (default) Daily.

8 Weekly.

16 Monthly.

32 Monthly, relative to the frequency interval.

64 When SQL Server Agent starts.

128 Run when the computer is idle

[ @frequency_interval=] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, and can be one of the
following values.

VALUE OF FREQUENCY_TYPE EFFECT ON FREQUENCY_INTERVAL

1 frequency_interval is unused.

4 (default) Every frequency_interval days, with a default of daily.

8 frequency_interval is one or more of the following (combined


with a | (Bitwise OR) logical operator):

1 = Sunday |

2 = Monday |

4 = Tuesday |

8 = Wednesday |

16 = Thursday |

32 = Friday |

64 = Saturday

16 On the frequency_interval day of the month.


VALUE OF FREQUENCY_TYPE EFFECT ON FREQUENCY_INTERVAL

32 frequency_interval is one of the following:

1 = Sunday |

2 = Monday |

3 = Tuesday |

4 = Wednesday |

5 = Thursday |

6 = Friday |

7 = Saturday |

8 = Day |

9 = Weekday |

10 = Weekend day

64 frequency_interval is unused.

128 frequency_interval is unused.

[ @frequency_subday=] frequency_subday
Is the unit for freq_subday_interval. frequency_subday is int, and can be one of these values.

VALUE DESCRIPTION

1 Once

2 Second

4 (default) Minute

8 Hour

[ @frequency_subday_interval=] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of 5, which means every 5
minutes.
[ @frequency_relative_interval=] frequency_relative_interval
Is the date the Snapshot Agent runs. frequency_relative_interval is int, with a default of 1.
[ @frequency_recurrence_factor=] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 0.
[ @active_start_date=] active_start_date
Is the date when the Snapshot Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of 0.
[ @active_end_date=] active_end_date
Is the date when the Snapshot Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int,
with a default of 99991231, which means December 31, 9999.
[ @active_start_time_of_day=] active_start_time_of_day
Is the time of day when the Snapshot Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is
int, with a default of 0.
[ @active_end_time_of_day=] active_end_time_of_day
Is the time of day when the Snapshot Agent stops being scheduled, formatted as HHMMSS.
active_end_time_of_day is int, with a default of 235959, which means 11:59:59 P.M. as measured on a 24-hour
clock.
[ @snapshot_job_name = ] 'snapshot_agent_name'
Is the name of an existing Snapshot Agent job name if an existing job is being used. snapshot_agent_name is
nvarchar(100) with a default value of NULL. This parameter is for internal use and should not be specified when
creating a new publication. If snapshot_agent_name is specified, then job_login and job_password must be NULL.
[ @publisher_security_mode= ] publisher_security_mode
Is the security mode used by the agent when connecting to the Publisher. publisher_security_mode is smallint,
with a default of 1. 0 specifies SQL Server Authentication, and 1 specifies Windows Authentication. A value of 0
must be specified for non- SQL Server Publishers. When possible, use Windows Authentication.
[ @publisher_login= ] 'publisher_login'
Is the login used when connecting to the Publisher. publisher_login is sysname, with a default of NULL.
publisher_login must be specified when publisher_security_mode is 0. If publisher_login is NULL and
publisher_security_mode is 1, then the Windows account specified in job_login will be used when connecting to
the Publisher.
[ @publisher_password= ] 'publisher_password'
Is the password used when connecting to the Publisher. publisher_password is sysname, with a default of NULL.

IMPORTANT
Do not store authentication information in script files. To help improve security, we recommend that you provide login
names and passwords at run time.

[ @job_login= ] 'job_login'
Is the login for the Windows account under which the agent runs. job_login is nvarchar(257), with a default of
NULL. This Windows account is always used for agent connections to the Distributor. You must supply this
parameter when creating a new Snapshot Agent job.

NOTE
For non- SQL Server Publishers, this must be the same login specified in sp_adddistpublisher (Transact-SQL).

[ @job_password= ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with no default.
You must supply this parameter when creating a new Snapshot Agent job.

IMPORTANT
Do not store authentication information in script files. To help improve security, we recommend that you provide login
names and passwords at run time.

[ @publisher= ] 'publisher'
Specifies a non- SQL Server Publisher. publisher is sysname, with a default of NULL.
NOTE
publisher should not be used when creating a Snapshot Agent at a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addpublication_snapshot is used in snapshot replication, transactional replication, and merge replication.

Example
-- To avoid storing the login and password in the script file, the values
-- are passed into SQLCMD as scripting variables. For information about
-- how to use scripting variables on the command line and in SQL Server
-- Management Studio, see the "Executing Replication Scripts" section in
-- the topic "Programming Replication Using System Stored Procedures".

DECLARE @publicationDB AS sysname;


DECLARE @publication AS sysname;
DECLARE @login AS sysname;
DECLARE @password AS sysname;
SET @publicationDB = N'AdventureWorks';
SET @publication = N'AdvWorksProductTran';
-- Windows account used to run the Log Reader and Snapshot Agents.
SET @login = $(Login);
-- This should be passed at runtime.
SET @password = $(Password);

-- Enable transactional or snapshot replication on the publication database.


EXEC sp_replicationdboption
@dbname=@publicationDB,
@optname=N'publish',
@value = N'true';

-- Execute sp_addlogreader_agent to create the agent job.


EXEC sp_addlogreader_agent
@job_login = @login,
@job_password = @password,
-- Explicitly specify the use of Windows Integrated Authentication (default)
-- when connecting to the Publisher.
@publisher_security_mode = 1;

-- Create a new transactional publication with the required properties.


EXEC sp_addpublication
@publication = @publication,
@status = N'active',
@allow_push = N'true',
@allow_pull = N'true',
@independent_agent = N'true';

-- Create a new snapshot job for the publication, using a default schedule.
EXEC sp_addpublication_snapshot
@publication = @publication,
@job_login = @login,
@job_password = @password,
-- Explicitly specify the use of Windows Integrated Authentication (default)
-- when connecting to the Publisher.
@publisher_security_mode = 1;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addpublication_snapshot.

See Also
Create a Publication
Create and Apply the Snapshot
sp_addpublication (Transact-SQL)
sp_changepublication_snapshot (Transact-SQL)
sp_startpublication_snapshot (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_addpullsubscription (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a pull subscription to a snapshot or transactional publication. This stored procedure is executed at the
Subscriber on the database where the pull subscription is to be created.
Transact-SQL Syntax Conventions

Syntax
sp_addpullsubscription [ @publisher= ] 'publisher'
[ , [ @publisher_db= ] 'publisher_db' ]
, [ @publication= ] 'publication'
[ , [ @independent_agent= ] 'independent_agent' ]
[ , [ @subscription_type= ] 'subscription_type' ]
[ , [ @description= ] 'description' ]
[ , [ @update_mode= ] 'update_mode' ]
[ , [ @immediate_sync = ] immediate_sync ]

Arguments
[ @publisher=] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default of NULL. publisher_db is ignored
by Oracle Publishers.
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @independent_agent=] 'independent_agent'
Specifies if there is a stand-alone Distribution Agent for this publication. independent_agent is nvarchar(5), with a
default of TRUE. If true, there is a stand-alone Distribution Agent for this publication. If false, there is one
Distribution Agent for each Publisher database/Subscriber database pair. independent_agent is a property of the
publication and must have the same value here as it has at the Publisher.
[ @subscription_type=] 'subscription_type'
Is the type of subscription. subscription_type is nvarchar(9), with a default of anonymous. You must specify a
value of pull for subscription_type, unless you want to create a subscription without registering the subscription at
the Publisher. In this case, you must specify a value of anonymous. This is necessary for cases in which you
cannot establish a SQL Server connection to the Publisher during subscription configuration.
[ @description=] 'description'
Is the description of the publication. description is nvarchar(100), with a default of NULL.
[ @update_mode=] 'update_mode'
Is the type of update. update_mode is nvarchar(30), and can be one of the following values.
VALUE DESCRIPTION

read only (default) The subscription is read-only. Any changes at the Subscriber
will not be sent back to the Publisher. Should be used when
updates will not be made at the Subscriber.

synctran Enables support for immediate updating subscriptions.

queued tran Enables the subscription for queued updating. Data


modifications can be made at the Subscriber, stored in a
queue, and then propagated to the Publisher.

failover Enables the subscription for immediate updating with queued


updating as a failover. Data modifications can be made at the
Subscriber and propagated to the Publisher immediately. If
the Publisher and Subscriber are not connected, data
modifications made at the Subscriber can be stored in a
queue until the Subscriber and Publisher are reconnected.

queued failover Enables the subscription as a queued updating subscription


with the ability to change to immediate updating mode. Data
modifications can be made at the Subscriber and stored in a
queue until a connection is established between the
Subscriber and Publisher. When a continuous connection is
established the updating mode can be changed to immediate
updating. Not supported for Oracle Publishers.

[ @immediate_sync =] immediate_sync
Is whether the synchronization files are created or re-created each time the Snapshot Agent runs. immediate_sync
is bit with a default of 1, and must be set to the same value as immediate_sync in
sp_addpublication.immediate_sync is a property of the publication and must have the same value here as it has
at the Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addpullsubscription is used in snapshot replication and transactional replication.

IMPORTANT
For queued updating subscriptions, use SQL Server Authentication for connections to Subscribers, and specify a different
account for the connection to each Subscriber. When creating a pull subscription that supports queued updating, replication
always sets the connection to use Windows Authentication (for pull subscriptions, replication cannot access metadata at the
Subscriber required to use SQL Server Authentication). In this case, you should execute sp_changesubscription to change the
connection to use SQL Server Authentication after the subscription is configured.

If the MSreplication_subscriptions (Transact-SQL) table does not exist at the Subscriber, sp_addpullsubscription
creates it. It also adds a row to the MSreplication_subscriptions (Transact-SQL) table. For pull subscriptions,
sp_addsubscription (Transact-SQL) should be called at the Publisher first.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Execute this batch at the Subscriber.


DECLARE @publication AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @publisher = $(PubServer);
SET @publicationDB = N'AdventureWorks2012';

-- At the subscription database, create a pull subscription


-- to a transactional publication.
USE [AdventureWorks2012Replica]
EXEC sp_addpullsubscription
@publisher = @publisher,
@publication = @publication,
@publisher_db = @publicationDB;

-- Add an agent job to synchronize the pull subscription.


EXEC sp_addpullsubscription_agent
@publisher = @publisher,
@publisher_db = @publicationDB,
@publication = @publication,
@distributor = @publisher,
@job_login = $(Login),
@job_password = $(Password);
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addpullsubscription.

See Also
Create a Pull Subscription
Create an Updatable Subscription to a Transactional Publication Subscribe to Publications
sp_addpullsubscription_agent (Transact-SQL)
sp_change_subscription_properties (Transact-SQL)
sp_droppullsubscription (Transact-SQL)
sp_helppullsubscription (Transact-SQL)
sp_helpsubscription_properties (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addpullsubscription_agent (Transact-SQL)
1/2/2018 • 8 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a new scheduled agent job used to synchronize a pull subscription to a transactional publication. This stored
procedure is executed at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_addpullsubscription_agent [ @publisher = ] 'publisher'
[ , [ @publisher_db = ] 'publisher_db' ] , [ @publication = ] 'publication'
[ , [ @subscriber = ] 'subscriber' ]
[ , [ @subscriber_db = ] 'subscriber_db' ]
[ , [ @subscriber_security_mode = ] subscriber_security_mode ]
[ , [ @subscriber_login = ] 'subscriber_login' ]
[ , [ @subscriber_password = ] 'subscriber_password' ]
[ , [ @distributor = ] 'distributor' ]
[ , [ @distribution_db = ] 'distribution_db' ]
[ , [ @distributor_security_mode = ] distributor_security_mode ]
[ , [ @distributor_login = ] 'distributor_login' ]
[ , [ @distributor_password = ] 'distributor_password' ]
[ , [ @optional_command_line = ] 'optional_command_line' ]
[ , [ @frequency_type = ] frequency_type ]
[ , [ @frequency_interval = ] frequency_interval ]
[ , [ @frequency_relative_interval = ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor = ] frequency_recurrence_factor ]
[ , [ @frequency_subday = ] frequency_subday ]
[ , [ @frequency_subday_interval = ] frequency_subday_interval ]
[ , [ @active_start_time_of_day = ] active_start_time_of_day ]
[ , [ @active_end_time_of_day = ] active_end_time_of_day ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @distribution_jobid = ] distribution_jobid OUTPUT ]
[ , [ @encrypted_distributor_password = ] encrypted_distributor_password ]
[ , [ @enabled_for_syncmgr = ] 'enabled_for_syncmgr' ]
[ , [ @ftp_address = ] 'ftp_address' ]
[ , [ @ftp_port = ] ftp_port ]
[ , [ @ftp_login = ] 'ftp_login' ]
[ , [ @ftp_password = ] 'ftp_password' ]
[ , [ @alt_snapshot_folder = ] 'alternate_snapshot_folder' ]
[ , [ @working_directory = ] 'working_directory' ]
[ , [ @use_ftp = ] 'use_ftp' ]
[ , [ @publication_type = ] publication_type ]
[ , [ @dts_package_name = ] 'dts_package_name' ]
[ , [ @dts_package_password = ] 'dts_package_password' ]
[ , [ @dts_package_location = ] 'dts_package_location' ]
[ , [ @reserved = ] 'reserved' ]
[ , [ @offloadagent = ] 'remote_agent_activation' ]
[ , [ @offloadserver = ] 'remote_agent_server_name']
[ , [ @job_name = ] 'job_name' ]
[ , [ @job_login = ] 'job_login' ]
[ , [ @job_password = ] 'job_password' ]
Arguments
[ @publisher=] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default value of NULL. publisher_db is
ignored by Oracle Publishers.
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @subscriber=] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts.

[ @subscriber_db=] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with a default of NULL.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts.

[ @subscriber_security_mode=] subscriber_security_mode
Is the security mode to use when connecting to a Subscriber when synchronizing. subscriber_security_mode is int,
with a default of NULL. 0 specifies SQL Server Authentication. 1 specifies Windows Authentication.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The Distribution Agent always
connects to the local Subscriber using Windows Authentication. If a value other than NULL or 1 is specified for this
parameter, a warning message is returned.

[ @subscriber_login =] 'subscriber_login'
Is the Subscriber login to use when connecting to a Subscriber when synchronizing.subscriber_login is sysname,
with a default of NULL.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. If a value is specified for this
parameter, a warning message is returned, but the value is ignored.

[ @subscriber_password=] 'subscriber_password'
Is the Subscriber password. subscriber_password is required if subscriber_security_mode is set to 0.
subscriber_password is sysname, with a default of NULL. If a subscriber password is used, it is automatically
encrypted.
NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. If a value is specified for this
parameter, a warning message is returned, but the value is ignored.

[ @distributor=] 'distributor'
Is the name of the Distributor. distributor is sysname, with a default of the value specified by publisher.
[ @distribution_db=] 'distribution_db'
Is the name of the distribution database. distribution_db is sysname, with a default value of NULL.
[ @distributor_security_mode=] distributor_security_mode
Is the security mode to use when connecting to a Distributor when synchronizing. distributor_security_mode is int,
with a default of 1. 0 specifies SQL Server Authentication. 1 specifies Windows Authentication.

IMPORTANT
When possible, use Windows Authentication.

[ @distributor_login=] 'distributor_login'
Is the Distributor login to use when connecting to a Distributor when synchronizing. distributor_login is required if
distributor_security_mode is set to 0. distributor_login is sysname, with a default of NULL.
[ @distributor_password =] 'distributor_password'
Is the Distributor password. distributor_password is required if distributor_security_mode is set to 0.
distributor_password is sysname, with a default of NULL.

IMPORTANT
Do not use a blank password. Use a strong password. When possible, prompt users to enter security credentials at runtime.
If you must store credentials in a script file, you must secure the file to prevent unauthorized access.

[ @optional_command_line=] 'optional_command_line'
Is an optional command prompt supplied to the Distribution Agent. For example, -DefinitionFile C:\Distdef.txt or
-CommitBatchSize 10. optional_command_line is nvarchar(4000), with a default of empty string.
[ @frequency_type=] frequency_type
Is the frequency with which to schedule the Distribution Agent. frequency_type is int, and can be one of the
following values.

VALUE DESCRIPTION

1 One time

2 (default) On demand

4 Daily

8 Weekly

16 Monthly

32 Monthly relative
VALUE DESCRIPTION

64 Autostart

128 Recurring

NOTE
Specifying a value of 64 causes the Distribution Agent to run in continuous mode. This corresponds to setting the -
Continuous parameter for the agent. For more information, see Replication Distribution Agent.

[ @frequency_interval=] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of 1.
[ @frequency_relative_interval=] frequency_relative_interval
Is the date of the Distribution Agent. This parameter is used when frequency_type is set to 32 (monthly relative).
frequency_relative_interval is int, and can be one of the following values.

VALUE DESCRIPTION

1 (default) First

2 Second

4 Third

8 Fourth

16 Last

[ @frequency_recurrence_factor=] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 1.
[ @frequency_subday=] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of the following
values.

VALUE DESCRIPTION

1 (default) Once

2 Second

4 Minute

8 Hour

[ @frequency_subday_interval=] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of 1.
[ @active_start_time_of_day=] active_start_time_of_day
Is the time of day when the Distribution Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day
is int, with a default of 0.
[ @active_end_time_of_day=] active_end_time_of_day
Is the time of day when the Distribution Agent stops being scheduled, formatted as HHMMSS.
active_end_time_of_day is int, with a default of 0.
[ @active_start_date=] active_start_date
Is the date when the Distribution Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of 0.
[ @active_end_date=] active_end_date
Is the date when the Distribution Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int,
with a default of 0.
[ @distribution_jobid =] distribution_jobidOUTPUT
Is the ID of the Distribution Agent for this job. distribution_jobid is binary(16), with a default of NULL, and it is an
OUTPUT parameter.
[ @encrypted_distributor_password=] encrypted_distributor_password
Setting encrypted_distributor_password is no longer supported. Attempting to set this bit parameter to 1 will
result in an error.
[ @enabled_for_syncmgr=] 'enabled_for_syncmgr'
Is whether the subscription can be synchronized through Microsoft Synchronization Manager.
enabled_for_syncmgr is nvarchar(5), with a default of FALSE. If false, the subscription is not registered with
Synchronization Manager. If true, the subscription is registered with Synchronization Manager and can be
synchronized without starting SQL Server Management Studio.
[ @ftp_address=] 'ftp_address'
For backward compatibility only.
[ @ftp_port=] ftp_port
For backward compatibility only.
[ @ftp_login=] 'ftp_login'
For backward compatibility only.
[ @ftp_password=] 'ftp_password'
For backward compatibility only.
[ @alt_snapshot_folder= ] 'alternate_snapshot_folder'
Specifies the location of the alternate folder for the snapshot. alternate_snapshot_folder is nvarchar(255), with a
default of NULL.
[ @working_directory= ] 'working_director'
Is the name of the working directory used to store data and schema files for the publication. working_directory is
nvarchar(255), with a default of NULL. The name should be specified in UNC format.
[ @use_ftp= ] 'use_ftp'
Specifies the use of FTP instead of the regular protocol to retrieve snapshots. use_ftp is nvarchar(5), with a default
of FALSE.
[ @publication_type= ] publication_type
Specifies the replication type of the publication. publication_type is a tinyint with a default of 0. If 0, publication is
a transaction type. If 1, publication is a snapshot type. If 2, publication is a merge type.
[ @dts_package_name= ] 'dts_package_name'
Specifies the name of the DTS package. dts_package_name is a sysname with a default of NULL. For example, to
specify a package of DTSPub_Package , the parameter would be @dts_package_name = N'DTSPub_Package' .
[ @dts_package_password= ] 'dts_package_password'
Specifies the password on the package, if there is one. dts_package_password is sysname with a default of NULL,
which means a password is not on the package.

NOTE
You must specify a password if dts_package_name is specified.

[ @dts_package_location= ] 'dts_package_location'
Specifies the package location. dts_package_location is a nvarchar(12), with a default of subscriber. The location
of the package can be distributor or subscriber.
[ @reserved= ] 'reserved'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @offloadagent= ] 'remote_agent_activation'

NOTE
Remote agent activation has been deprecated and is no longer supported. This parameter is supported only to maintain
backward compatibility of scripts. Setting remote_agent_activation to a value other than false will generate an error.

[ @offloadserver= ] 'remote_agent_server_name'

NOTE
Remote agent activation has been deprecated and is no longer supported. This parameter is supported only to maintain
backward compatibility of scripts. Setting remote_agent_server_name to any non-NULL value will generate an error.

[ @job_name= ] 'job_name'
Is the name of an existing agent job. job_name is sysname, with a default value of NULL. This parameter is only
specified when the subscription will be synchronized using an existing job instead of a newly created job (the
default). If you are not a member of the sysadmin fixed server role, you must specify job_login and job_password
when you specify job_name.
[ @job_login= ] 'job_login'
Is the login for the Windows account under which the agent runs. job_login is nvarchar(257), with no default. This
Windows account is always used for agent connections to the Subscriber.
[ @job_password= ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with no default.

IMPORTANT
When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must
secure the file to prevent unauthorized access.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addpullsubscription_agent is used in snapshot replication and transactional replication.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Execute this batch at the Subscriber.


DECLARE @publication AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @publisher = $(PubServer);
SET @publicationDB = N'AdventureWorks2012';

-- At the subscription database, create a pull subscription


-- to a transactional publication.
USE [AdventureWorks2012Replica]
EXEC sp_addpullsubscription
@publisher = @publisher,
@publication = @publication,
@publisher_db = @publicationDB;

-- Add an agent job to synchronize the pull subscription.


EXEC sp_addpullsubscription_agent
@publisher = @publisher,
@publisher_db = @publicationDB,
@publication = @publication,
@distributor = @publisher,
@job_login = $(Login),
@job_password = $(Password);
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addpullsubscription_agent.

See Also
Create a Pull Subscription
Subscribe to Publications
sp_addpullsubscription (Transact-SQL)
sp_change_subscription_properties (Transact-SQL)
sp_droppullsubscription (Transact-SQL)
sp_helppullsubscription (Transact-SQL)
sp_helpsubscription_properties (Transact-SQL)
sp_addpushsubscription_agent (Transact-SQL)
11/21/2017 • 7 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a new scheduled agent job used to synchronize a push subscription to a transactional publication. This stored
procedure is executed at the Publisher on the publication database.

IMPORTANT
When configuring a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and
job_password, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its
remote Distributor before executing this stored procedure. For more information, see Enable Encrypted Connections to the
Database Engine (SQL Server Configuration Manager).

Transact-SQL Syntax Conventions

Syntax
sp_addpushsubscription_agent [ @publication= ] 'publication'
[ , [ @subscriber = ] 'subscriber' ]
[ , [ @subscriber_db = ] 'subscriber_db' ]
[ , [ @subscriber_security_mode = ] subscriber_security_mode ]
[ , [ @subscriber_login = ] 'subscriber_login' ]
[ , [ @subscriber_password = ] 'subscriber_password' ]
[ , [ @job_login = ] 'job_login' ]
[ , [ @job_password = ] 'job_password' ]
[ , [ @job_name = ] 'job_name' ]
[ , [ @frequency_type = ] frequency_type ]
[ , [ @frequency_interval = ] frequency_interval ]
[ , [ @frequency_relative_interval = ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor = ] frequency_recurrence_factor ]
[ , [ @frequency_subday = ] frequency_subday ]
[ , [ @frequency_subday_interval = ] frequency_subday_interval ]
[ , [ @active_start_time_of_day = ] active_start_time_of_day ]
[ , [ @active_end_time_of_day = ] active_end_time_of_day ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @dts_package_name = ] 'dts_package_name' ]
[ , [ @dts_package_password = ] 'dts_package_password' ]
[ , [ @dts_package_location = ] 'dts_package_location' ]
[ , [ @enabled_for_syncmgr = ] 'enabled_for_syncmgr' ]
[ , [ @distribution_job_name = ] 'distribution_job_name' ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @subscriber_provider = ] 'subscriber_provider' ]
[ , [ @subscriber_datasrc = ] 'subscriber_datasrc' ]
[ , [ @subscriber_location = ] 'subscriber_location' ]
[ , [ @subscriber_provider_string = ] 'subscriber_provider_string' ]
[ , [ @subscriber_catalog = ] 'subscriber_catalog' ]

Arguments
[ @publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[ @subscriber_db =] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with a default of NULL. For a non-SQL Server
Subscriber, specify a value of (default destination) for subscriber_db.
[ @subscriber_security_mode =] subscriber_security_mode
Is the security mode to use when connecting to a Subscriber when synchronizing. subscriber_security_mode is int,
with a default of 1. 0 specifies SQL Server Authentication. 1 specifies Windows Authentication.

IMPORTANT
For queued updating subscriptions, use SQL Server Authentication for connections to Subscribers, and specify a different
account for the connection to each Subscriber. For all other subscriptions, use Windows Authentication.

[ @subscriber_login =] 'subscriber_login'
Is the Subscriber login to use when connecting to a Subscriber when synchronizing. subscriber_login is sysname,
with a default of NULL.
[ @subscriber_password =] 'subscriber_password'
Is the Subscriber password. subscriber_password is required if subscriber_security_mode is set to 0.
subscriber_password is sysname, with a default of NULL. If a subscriber password is used, it is automatically
encrypted.

IMPORTANT
Do not use a blank password. Use a strong password. When possible, prompt users to enter security credentials at runtime.
If you must store credentials in a script file, you must secure the file to prevent unauthorized access.

[ @job_login = ] 'job_login'
Is the login for the Windows account under which the agent runs. job_login is nvarchar(257), with a default value
of NULL. This Windows account is always used for agent connections to the Distributor and for connections to the
Subscriber when using Windows Integrated authentication.
[ @job_password = ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with no default.

IMPORTANT
When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must
secure the file to prevent unauthorized access.

[ @job_name = ] 'job_name'
Is the name of an existing agent job. job_name is sysname, with a default value of NULL. This parameter is only
specified when the subscription will be synchronized using an existing job instead of a newly created job (the
default). If you are not a member of the sysadmin fixed server role, you must specify job_login and job_password
when you specify job_name.
[ @frequency_type = ] frequency_type
Is the frequency with which to schedule the Distribution Agent. frequency_type is int, and can be one of the
following values.
VALUE DESCRIPTION

1 One time

2 On demand

4 Daily

8 Weekly

16 Monthly

32 Monthly relative

64 (default) Autostart

128 Recurring

NOTE
Specifying a value of 64 causes the Distribution Agent to run in continuous mode. This corresponds to setting the -
Continuous parameter for the agent. For more information, see Replication Distribution Agent.

[ @frequency_interval = ] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of 1.
[ @frequency_relative_interval = ] frequency_relative_interval
Is the date of the Distribution Agent. This parameter is used when frequency_type is set to 32 (monthly relative).
frequency_relative_interval is int, and can be one of the following values.

VALUE DESCRIPTION

1 (default) First

2 Second

4 Third

8 Fourth

16 Last

[ @frequency_recurrence_factor = ] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 0.
[ @frequency_subday = ] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of the following
values.

VALUE DESCRIPTION

1 Once
VALUE DESCRIPTION

2 Second

4 (default) Minute

8 Hour

[ @frequency_subday_interval = ] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of 5.
[ @active_start_time_of_day = ] active_start_time_of_day
Is the time of day when the Distribution Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day
is int, with a default of 0.
[ @active_end_time_of_day = ] active_end_time_of_day
Is the time of day when the Distribution Agent stops being scheduled, formatted as HHMMSS.
active_end_time_of_day is int, with a default of 235959.
[ @active_start_date = ] active_start_date
Is the date when the Distribution Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of 0.
[ @active_end_date = ] active_end_date
Is the date when the Distribution Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int,
with a default of 99991231.
[ @dts_package_name = ] 'dts_package_name'
Specifies the name of the Data Transformation Services (DTS) package. dts_package_name is a sysname with a
default of NULL. For example, to specify a package name of DTSPub_Package , the parameter would be
@dts_package_name = N'DTSPub_Package' .

[ @dts_package_password = ] 'dts_package_password'
Specifies the password required to run the package. dts_package_password is sysname with a default of NULL.

NOTE
You must specify a password if dts_package_name is specified.

[ @dts_package_location = ] 'dts_package_location'
Specifies the package location. dts_package_location is a nvarchar(12), with a default of DISTRIBUTOR. The
location of the package can be distributor or subscriber.
[ @enabled_for_syncmgr = ] 'enabled_for_syncmgr'
Is whether the subscription can be synchronized through Microsoft Synchronization Manager.
enabled_for_syncmgr is nvarchar(5), with a default of FALSE. If false, the subscription is not registered with
Synchronization Manager. If true, the subscription is registered with Synchronization Manager and can be
synchronized without starting SQL Server Management Studio.
[ @distribution_job_name = ] 'distribution_job_name'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default value of NULL.
[ @subscriber_provider= ] 'subscriber_provider'
Is the unique programmatic identifier (PROGID) with which the OLE DB provider for the non- SQL Server data
source is registered. subscriber_provider is sysname, with default value of NULL. subscriber_provider must be
unique for the OLE DB provider installed on the Distributor. subscriber_provider is only supported for non- SQL
Server Subscribers.
[ @subscriber_datasrc= ] 'subscriber_datasrc'
Is the name of the data source as understood by the OLE DB provider. subscriber_datasrc is nvarchar(4000), with
a default value of NULL. subscriber_datasrc is passed as the DBPROP_INIT_DATASOURCE property to initialize the
OLE DB provider. subscriber_datasrc is only supported for non- SQL Server Subscribers.
[ @subscriber_location= ] 'subscriber_location'
Is the location of the database as understood by the OLE DB provider. subscriber_location is nvarchar(4000), with
a default value of NULL. subscriber_location is passed as the DBPROP_INIT_LOCATION property to initialize the
OLE DB provider. subscriber_location is only supported for non- SQL Server Subscribers.
[ @subscriber_provider_string= ] 'subscriber_provider_string'
Is the OLE DB provider-specific connection string that identifies the data source. subscriber_provider_string is
nvarchar(4000), with a default value of NULL. subscriber_provider_string is passed to IDataInitialize or set as the
DBPROP_INIT_PROVIDERSTRING property to initialize the OLE DB provider. subscriber_provider_string is only
supported for non- SQL Server Subscribers.
[ @subscriber_catalog= ] 'subscriber_catalog'
Is the catalog to be used when making a connection to the OLE DB provider. subscriber_catalog is sysname, with
default value of NULL. subscriber_catalog is passed as the DBPROP_INIT_CATALOG property to initialize the OLE
DB provider. subscriber_catalog is only supported for non- SQL Server Subscribers.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addpushsubscription_agent is used in snapshot replication and transactional replication.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @publication AS sysname;


DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorks2012Replica';

--Add a push subscription to a transactional publication.


USE [AdventureWorks2012]
EXEC sp_addsubscription
@publication = @publication,
@subscriber = @subscriber,
@destination_db = @subscriptionDB,
@subscription_type = N'push';

--Add an agent job to synchronize the push subscription.


EXEC sp_addpushsubscription_agent
@publication = @publication,
@subscriber = @subscriber,
@subscriber_db = @subscriptionDB,
@job_login = $(Login),
@job_password = $(Password);
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addpushsubscription_agent.

See Also
Create a Push Subscription
Create a Subscription for a Non-SQL Server Subscriber
Subscribe to Publications
Replication Stored Procedures (Transact-SQL)
sp_addsubscription (Transact-SQL)
sp_changesubscription (Transact-SQL)
sp_dropsubscription (Transact-SQL)
sp_helpsubscription (Transact-SQL)
sp_addqreader_agent (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adds a Queue Reader agent for a given Distributor. This stored procedure is executed at the Distributor on the
distribution database or at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_addqreader_agent [ @job_login = ] 'job_login'
, [ @job_password = ] 'job_password'
[ , [ @job_name = ] 'job_name'
[ , [ @frompublisher = ] frompublisher

Arguments
[ @job_login= ] 'job_login'
Is the login for the Microsoft Windows account under which the agent runs. job_login is nvarchar(257), with no
default. This Windows account is always used for agent connections to the Distributor.
[ @job_password= ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with no default.

IMPORTANT
Do not store authentication information in script files. For best security, login names and passwords should be supplied at
runtime.

[ @job_name= ] 'job_name'
Is the name of an existing agent job. job_name is sysname, with a default value of NULL. This parameter is only
specified when the agent is created using an existing job instead of a newly created job (the default).
[ @frompublisher= ] frompublisher
Specifies whether the procedure is being executed at the Publisher. frompublisher is bit, with a default value of 0. A
value of 1 means that the procedure is being executed from the Publisher on the publication database.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addqreader_agent is used in transactional replication.
sp_addqreader_agent must be executed at least once at a Distributor that supports queued updating after
sp_adddistributiondb but before sp_addpublication.
The Queue Reader Agent job is removed when you execute sp_dropdistributiondb.

Permissions
Only members of the sysadmin fixed server role can execute sp_addqreader_agent.

See Also
Enable Updating Subscriptions for Transactional Publications
Upgrade Replication Scripts (Replication Transact-SQL Programming)
Updatable Subscriptions for Transactional Replication
sp_changeqreader_agent (Transact-SQL)
sp_helpqreader_agent (Transact-SQL)
sp_addqueued_artinfo (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse

IMPORTANT
The sp_script_synctran_commands procedure should be used instead of sp_addqueued_artinfo.
sp_script_synctran_commands generates a script that contains the sp_addqueued_artinfo and sp_addsynctrigger calls.

Creates the MSsubscription_articles table at the Subscriber that is used to track article subscription information
(Queued Updating and Immediate Updating with Queued Updating as Failover). This stored procedure is executed
at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_addqueued_artinfo [ @artid= ] 'artid'
, [ @article= ] 'article'
, [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
, [ @dest_table= ] 'dest_table'
, [ @owner = ] 'owner'
, [ @cft_table= ] 'cft_table'

Arguments
[ @artid= ] 'artid'
Is the name of the article ID. artid is int, with no default
[ @article=] 'article'
Is the name of the article to be scripted. article is sysname, with no default
[ @publisher=] 'publisher'
Is the name of the Publisher server. publisher is sysname, with no default.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[ @publication=] 'publication'
Is the name of the publication to be scripted. publication is sysname, with no default.
[ @dest_table= ] 'dest_table'
Is the name of the destination table. dest_table is sysname, with no default.
[@owner = ] 'owner'
Is the owner of the subscription. owner is sysname, with no default.
[ @cft_table= ] 'cft_table'
Name of the queued updating conflict table for this article. cft_tableis sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addqueued_artinfo is used by the Distribution Agent as part of subscription initialization. This stored
procedure is not commonly run by users, but may be useful if the user needs to manually set up a subscription.
sp_script_synctran_commands instead of sp_addqueued_artinfo.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addqueued_artinfo.

See Also
Updatable Subscriptions for Transactional Replication
sp_script_synctran_commands (Transact-SQL)
MSsubscription_articles (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addscriptexec (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Posts a SQL script (.sql file) to all Subscribers of a publication. This stored procedure is executed at the Publisher on
the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_addscriptexec [ @publication = ] publication
[ , [ @scriptfile = ] 'scriptfile' ]
[ , [ @skiperror = ] 'skiperror' ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @scriptfile= ] 'scriptfile'
Is the full path to the SQL script file. scriptfile is nvarchar(4000), with no default.
[ @skiperror= ] 'skiperror'
Indicates whether the Distribution Agent or Merge Agent should stop when an error is encountered during script
processing. SkipError is bit, with a default of 0.
0 = the agent will stop.
1 = the agent continues the script and ignores the error.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when publishing from a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addscriptexec is used in transactional replication and merge replication.
sp_addscriptexec is not used for snapshot replication.
To use sp_addscriptexec, the SQL Server service account must have read and write permissions on the snapshot
location and read permissions on the location where any scripts are stored.
The sqlcmd utility is used to execute the script at the Subscriber, and the script is executed in the security context
used by the Distribution Agent or Merge Agent when connecting to the subscription database. When the agent is
run on a previous version of SQL Server, the osql utility is used instead of sqlcmd.
sp_addscriptexec is useful in applying scripts to subscribers, and uses sqlcmd to apply the contents of the script
to the Subscriber. However, because Subscriber configurations can vary, scripts tested prior to posting to the
Publisher may still cause errors on a Subscriber. skiperror provides the ability to have the Distribution Agent or
Merge Agent ignore errors and continue on. Use sqlcmd to test scripts prior to running sp_addscriptexec.

NOTE
Skipped errors will continue to be logged in the Agent history for reference.

Using sp_addscriptexec to post a script file for publications using FTP for snapshot delivery is only supported for
Microsoft SQL Server Subscribers.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addscriptexec.

See Also
Execute Scripts During Synchronization (Replication Transact-SQL Programming)
Synchronize Data
System Stored Procedures (Transact-SQL)
sp_addsubscriber (Transact-SQL)
11/21/2017 • 7 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a new Subscriber to a Publisher, enabling it to receive publications. This stored procedure is executed at the
Publisher on the publication database for snapshot and transactional publications; and for merge publications
using a remote Distributor, this stored procedure is executed at the Distributor.

IMPORTANT
This stored procedure has been deprecated. You are no longer required to explicitly register a Subscriber at the Publisher.

Transact-SQL Syntax Conventions

Syntax
sp_addsubscriber [ @subscriber = ] 'subscriber'
[ , [ @type = ] type ]
[ , [ @login = ] 'login' ]
[ , [ @password = ] 'password' ]
[ , [ @commit_batch_size = ] commit_batch_size ]
[ , [ @status_batch_size = ] status_batch_size ]
[ , [ @flush_frequency = ] flush_frequency ]
[ , [ @frequency_type = ] frequency_type ]
[ , [ @frequency_interval = ] frequency_interval ]
[ , [ @frequency_relative_interval = ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor = ] frequency_recurrence_factor ]
[ , [ @frequency_subday = ] frequency_subday ]
[ , [ @frequency_subday_interval = ] frequency_subday_interval ]
[ , [ @active_start_time_of_day = ] active_start_time_of_day ]
[ , [ @active_end_time_of_day = ] active_end_time_of_day ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @description = ] 'description' ]
[ , [ @security_mode = ] security_mode ]
[ , [ @encrypted_password = ] encrypted_password ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @subscriber=] 'subscriber'
Is the name of the server to be added as a valid Subscriber to the publications on this server. subscriber is
sysname, with no default.
[ @type=] type
Is the type of Subscriber. type is tinyint, and can be one of these values.

VALUE DESCRIPTION

0 (default) Microsoft SQL Server Subscriber


VALUE DESCRIPTION

1 ODBC data source server

2 Microsoft Jet database

3 OLE DB provider

[ @login=] 'login'
Is the login ID for SQL Server Authentication. login is sysname, with a default of NULL.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[ @password=] 'password'
Is the password for SQL Server Authentication. password is nvarchar(524), with a default of NULL.

IMPORTANT
Do not use a blank password. Use a strong password.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[ @commit_batch_size=] commit_batch_size
This parameter has been deprecated and is maintained for backward compatibility of scripts.

NOTE
When a value is specified, it will be used as a default when creating subscriptions at this Subscriber and a warning message
will be returned.

[ @status_batch_size=] status_batch_size
This parameter has been deprecated and is maintained for backward compatibility of scripts.

NOTE
When a value is specified, it will be used as a default when creating subscriptions at this Subscriber and a warning message
will be returned.

[ @flush_frequency=] flush_frequency
This parameter has been deprecated and is maintained for backward compatibility of scripts.
NOTE
When a value is specified, it will be used as a default when creating subscriptions at this Subscriber and a warning message
will be returned.

[ @frequency_type=] frequency_type
Is the frequency with which to schedule the replication agent. frequency_type is int, and can be one of these
values.

VALUE DESCRIPTION

1 One time

2 On demand

4 Daily

8 Weekly

16 Monthly

32 Monthly relative

64 (default) Autostart

128 Recurring

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[@frequency_interval= ] frequency_interval
Is the value applied to the frequency set by frequency_type. frequency_interval is int, with a default of 1.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[ @frequency_relative_interval=] frequency_relative_interval
Is the date of the replication agent. This parameter is used when frequency_type is set to 32 (monthly relative).
frequency_relative_interval is int, and can be one of these values.

VALUE DESCRIPTION

1 (default) First

2 Second
VALUE DESCRIPTION

4 Third

8 Fourth

16 Last

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[ @frequency_recurrence_factor=] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 0.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[ @frequency_subday=] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of these values.

VALUE DESCRIPTION

1 Once

2 Second

4 (default) Minute

8 Hour

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[ @frequency_subday_interval=] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of 5.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.
[ @active_start_time_of_day=] active_start_time_of_day
Is the time of day when the replication agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is
int, with a default of 0.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[ @active_end_time_of_day=] active_end_time_of_day
Is the time of day when the replication agent stops being scheduled, formatted as HHMMSS.
active_end_time_of_dayis int, with a default of 235959, which means 11:59:59 P.M. as measured on a 24-hour
clock.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[ @active_start_date=] active_start_date
Is the date when the replication agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of 0.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[ @active_end_date=] active_end_date
Is the date when the replication agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int,
with a default of 99991231, which means December 31, 9999.

NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[ @description=] 'description'
Is a text description of the Subscriber. description is nvarchar(255), with a default of NULL.
[ @security_mode=] security_mode
Is the implemented security mode. security_mode is int, with a default of 1. 0 specifies SQL Server Authentication.
1 specifies Windows Authentication.
NOTE
This parameter has been deprecated and is maintained for backward compatibility of scripts. The property is now specified
on a per-subscription basis when executing sp_addsubscription. When a value is specified, it will be used as a default when
creating subscriptions at this Subscriber and a warning message will be returned.

[ @encrypted_password=] encrypted_password
This parameter has been deprecated and is provided for backward-compatibility only Setting encrypted_password
to any value but 0 will result in an error.
[ @publisher= ] 'publisher'
Specifies a non- SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when publishing from a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addsubscriber is used in snapshot replication, transactional replication, and merge replication.
sp_addsubscriber is not required when the Subscriber will only have anonymous subscriptions to merge
publications.
sp_addsubscriber writes to the MSsubscriber_info table in the distribution database.

Permissions
Only members of the sysadmin fixed server role can execute sp_addsubscriber.

See Also
Create a Push Subscription
Create a Pull Subscription
sp_changesubscriber (Transact-SQL)
sp_dropsubscriber (Transact-SQL)
sp_helpsubscriberinfo (Transact-SQL)
sp_addsubscriber_schedule (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adds a schedule for the Distribution Agent and Merge Agent. This stored procedure is executed at the Publisher on
any database.
Transact-SQL Syntax Conventions

Syntax
sp_addsubscriber_schedule [ @subscriber = ] 'subscriber'
[ , [ @agent_type = ] agent_type ]
[ , [ @frequency_type = ] frequency_type ]
[ , [ @frequency_interval = ] frequency_interval ]
[ , [ @frequency_relative_interval = ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor = ] frequency_recurrence_factor ]
[ , [ @frequency_subday = ] frequency_subday ]
[ , [ @frequency_subday_interval = ] frequency_subday_interval ]
[ , [ @active_start_time_of_day = ] active_start_time_of_day ]
[ , [ @active_end_time_of_day = ] active_end_time_of_day ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @subscriber = ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname. The name of the Subscriber must be unique in the database,
must not already exist, and cannot be NULL.
[ @agent_type = ] agent_type
Is the type of agent. agent_type is smallint, and can be one of these values.

VALUE DESCRIPTION

0 (default) Distribution Agent

1 Merge Agent

[ @frequency_type = ] frequency_type
Is the frequency with which to schedule the Distribution Agent. frequency_type is int, and can be one of these
values.

VALUE DESCRIPTION

1 One time

2 On demand
VALUE DESCRIPTION

4 Daily

8 Weekly

16 Monthly

32 Monthly relative

64 (default) Autostart

128 Recurring

[ @frequency_interval = ] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of 1.
[ @frequency_relative_interval = ] frequency_relative_interval
Is the date of the Distribution Agent. This parameter is used when frequency_type is set to 32 (monthly relative).
frequency_relative_interval is int, and can be one of these values.

VALUE DESCRIPTION

1 (default) First

2 Second

4 Third

8 Fourth

16 Last

[ @frequency_recurrence_factor = ] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 0.
[ @frequency_subday = ] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of these values.

VALUE DESCRIPTION

1 Once

2 Second

4 (default) Minute

8 Hour

[ @frequency_subday_interval = ] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of 5.
[ @active_start_time_of_day = ] active_start_time_of_day
Is the time of day when the Distribution Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day
is int, with a default of 0.
[ @active_end_time_of_day = ] active_end_time_of_day
Is the time of day when the Distribution Agent stops being scheduled, formatted as HHMMSS.
active_end_time_of_dayis int, with a default of 235959, which means 11:59:59 P.M. as measured on a 24-hour
clock.
[ @active_start_date = ] active_start_date
Is the date when the Distribution Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of 0.
[ @active_end_date = ] active_end_date
Is the date when the Distribution Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int,
with a default of 99991231, which means December 31, 9999.
[ @publisher = ] 'publisher'
Specifies a non- Microsoft SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be specified for a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addsubscriber_schedule is used in snapshot replication, transactional replication, and merge replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_addsubscriber_schedule.

See Also
sp_changesubscriber_schedule (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addsubscription (Transact-SQL)
11/21/2017 • 12 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a subscription to a publication and sets the Subscriber status. This stored procedure is executed at the
Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_addsubscription [ @publication = ] 'publication'
[ , [ @article = ] 'article']
[ , [ @subscriber = ] 'subscriber' ]
[ , [ @destination_db = ] 'destination_db' ]
[ , [ @sync_type = ] 'sync_type' ]
[ , [ @status = ] 'status'
[ , [ @subscription_type = ] 'subscription_type' ]
[ , [ @update_mode = ] 'update_mode' ]
[ , [ @loopback_detection = ] 'loopback_detection' ]
[ , [ @frequency_type = ] frequency_type ]
[ , [ @frequency_interval = ] frequency_interval ]
[ , [ @frequency_relative_interval = ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor = ] frequency_recurrence_factor ]
[ , [ @frequency_subday = ] frequency_subday ]
[ , [ @frequency_subday_interval = ] frequency_subday_interval ]
[ , [ @active_start_time_of_day = ] active_start_time_of_day ]
[ , [ @active_end_time_of_day = ] active_end_time_of_day ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @optional_command_line = ] 'optional_command_line' ]
[ , [ @reserved = ] 'reserved' ]
[ , [ @enabled_for_syncmgr= ] 'enabled_for_syncmgr' ]
[ , [ @offloadagent= ] remote_agent_activation]
[ , [ @offloadserver= ] 'remote_agent_server_name' ]
[ , [ @dts_package_name= ] 'dts_package_name' ]
[ , [ @dts_package_password= ] 'dts_package_password' ]
[ , [ @dts_package_location= ] 'dts_package_location' ]
[ , [ @distribution_job_name= ] 'distribution_job_name' ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @backupdevicetype = ] 'backupdevicetype' ]
[ , [ @backupdevicename = ] 'backupdevicename' ]
[ , [ @mediapassword = ] 'mediapassword' ]
[ , [ @password = ] 'password' ]
[ , [ @fileidhint = ] fileidhint ]
[ , [ @unload = ] unload ]
[ , [ @subscriptionlsn = ] subscriptionlsn ]
[ , [ @subscriptionstreams = ] subscriptionstreams ]
[ , [ @subscriber_type = ] subscriber_type ]
[ , [ @memory_optimized = ] memory_optimized ]

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @article=] 'article'
Is the article to which the publication is subscribed. article is sysname, with a default of all. If all, a subscription
is added to all articles in that publication. Only values of all or NULL are supported for Oracle Publishers.
[ @subscriber=] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[ @destination_db=] 'destination_db'
Is the name of the destination database in which to place replicated data. destination_db is sysname, with a
default of NULL. When NULL, destination_db is set to the name of the publication database. For Oracle
Publishers, destination_db must be specified. For a non-SQL Server Subscriber, specify a value of (default
destination) for destination_db.
[ @sync_type=] 'sync_type'
Is the subscription synchronization type. sync_type is nvarchar(255), and can be one of the following values:

VALUE DESCRIPTION

none Subscriber already has the schema and initial data for
published tables.

Note: This option has been deprecated. Use replication


support only instead.

automatic (default) Schema and initial data for published tables are transferred
to the Subscriber first.

replication support only Provides automatic generation at the Subscriber of article


custom stored procedures and triggers that support
updating subscriptions, if appropriate. Assumes that the
Subscriber already has the schema and initial data for
published tables. When configuring a peer-to-peer
transactional replication topology, ensure that the data at
all nodes in the topology is identical. For more information,
see Peer-to-Peer Transactional Replication.

Not supported for subscriptions to non-SQL Server


publications.

initialize with backup Schema and initial data for published tables are obtained
from a backup of the publication database. Assumes that
the Subscriber has access to a backup of the publication
database. The location of the backup and media type for
the backup are specified by backupdevicename and
backupdevicetype. When using this option, a peer-to-peer
transactional replication topology need not be quiesced
during configuration.

Not supported for subscriptions to non-SQL Server


publications.

initialize from lsn Used when you are adding a node to a peer-to-peer
transactional replication topology. Used with
@subscriptionlsn to make sure that all relevant transactions
are replicated to the new node. Assumes that the
Subscriber already has the schema and initial data for
published tables. For more information, see Peer-to-Peer
Transactional Replication.
NOTE
System tables and data are always transferred.

[ @status=] 'status'
Is the subscription status. status is sysname, with a default value of NULL. When this parameter is not
explicitly set, replication automatically sets it to one of these values.

VALUE DESCRIPTION

active Subscription is initialized and ready to accept changes. This


option is set when the value of sync_type is none, initialize
with backup, or replication support only.

subscribed Subscription needs to be initialized. This option is set when


the value of sync_type is automatic.

[ @subscription_type=] 'subscription_type'
Is the type of subscription. subscription_type is nvarchar(4), with a default of push. Can be push or pull. The
Distribution Agents of push subscriptions reside at the Distributor, and the Distribution Agents of pull
subscriptions reside at the Subscriber. subscription_type can be pull to create a named pull subscription that is
known to the Publisher. For more information, see Subscribe to Publications.

NOTE
Anonymous subscriptions do not need to use this stored procedure.

[ @update_mode=] 'update_mode'
Is the type of update.update_mode is nvarchar(30), and can be one of these values.

VALUE DESCRIPTION

read only (default) The subscription is read-only. The changes at the


Subscriber are not sent to the Publisher.

sync tran Enables support for immediate updating subscriptions. Not


supported for Oracle Publishers.

queued tran Enables the subscription for queued updating. Data


modifications can be made at the Subscriber, stored in a
queue, and then propagated to the Publisher. Not
supported for Oracle Publishers.

failover Enables the subscription for immediate updating with


queued updating as a failover. Data modifications can be
made at the Subscriber and propagated to the Publisher
immediately. If the Publisher and Subscriber are not
connected, the updating mode can be changed so that
data modifications made at the Subscriber are stored in a
queue until the Subscriber and Publisher are reconnected.
Not supported for Oracle Publishers.
VALUE DESCRIPTION

queued failover Enables the subscription as a queued updating subscription


with the ability to change to immediate updating mode.
Data modifications can be made at the Subscriber and
stored in a queue until a connection is established between
the Subscriber and Publisher. When a continuous
connection is established the updating mode can be
changed to immediate updating. Not supported for Oracle
Publishers.

Note that the values synctran and queued tran are not allowed if the publication being subscribed to allows
DTS.
[ @loopback_detection=] 'loopback_detection'
Specifies if the Distribution Agent sends transactions that originated at the Subscriber back to the Subscriber.
loopback_detection is nvarchar(5), and can be one of these values.

VALUE DESCRIPTION

true Distribution Agent does not send transactions originated at


the Subscriber back to the Subscriber. Used with
bidirectional transactional replication. For more information,
see Bidirectional Transactional Replication.

false Distribution Agent sends transactions that originated at the


Subscriber back to the Subscriber.

NULL (default) Automatically set to true for a SQL Server Subscriber and
false for a non- SQL Server Subscriber.

[ @frequency_type=] frequency_type
Is the frequency with which to schedule the distribution task. frequency_type is int, and can be one of these
values.

VALUE DESCRIPTION

1 One time

2 On demand

4 Daily

8 Weekly

16 Monthly

32 Monthly relative

64 (default) Autostart

128 Recurring

[ @frequency_interval=] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of NULL.
[ @frequency_relative_interval=] frequency_relative_interval
Is the date of the Distribution Agent. This parameter is used when frequency_type is set to 32 (monthly
relative). frequency_relative_interval is int, and can be one of these values.

VALUE DESCRIPTION

1 First

2 Second

4 Third

8 Fourth

16 Last

NULL (default)

[ @frequency_recurrence_factor=] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of NULL.
[ @frequency_subday=] frequency_subday
Is how often, in minutes, to reschedule during the defined period. frequency_subday is int, and can be one of
these values.

VALUE DESCRIPTION

1 Once

2 Second

4 Minute

8 Hour

NULL

[ @frequency_subday_interval=] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of NULL.
[ @active_start_time_of_day=] active_start_time_of_day
Is the time of day when the Distribution Agent is first scheduled, formatted as HHMMSS.
active_start_time_of_day is int, with a default of NULL.
[ @active_end_time_of_day=] active_end_time_of_day
Is the time of day when the Distribution Agent stops being scheduled, formatted as HHMMSS.
active_end_time_of_day is int, with a default of NULL.
[ @active_start_date=] active_start_date
Is the date when the Distribution Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int,
with a default of NULL.
[ @active_end_date=] active_end_date
Is the date when the Distribution Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is
int, with a default of NULL.
[ @optional_command_line=] 'optional_command_line'
Is the optional command prompt to execute. optional_command_line is nvarchar(4000), with a default of
NULL.
[ @reserved=] 'reserved'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @enabled_for_syncmgr=] 'enabled_for_syncmgr'
Is whether the subscription can be synchronized through Microsoft Windows Synchronization Manager.
enabled_for_syncmgr is nvarchar(5), with a default of FALSE. If false, the subscription is not registered with
Windows Synchronization Manager. If true, the subscription is registered with Windows Synchronization
Manager and can be synchronized without starting SQL Server Management Studio. Not supported for Oracle
Publishers.
[ @offloadagent= ] 'remote_agent_activation'
Specifies that the agent can be activated remotely. remote_agent_activation is bit with a default of 0.

NOTE
This parameter has been deprecated and is only maintained for backward compatibility of scripts.

[ @offloadserver= ] 'remote_agent_server_name'
Specifies the network name of server to be used for remote activation. remote_agent_server_nameis
sysname, with a default of NULL.
[ @dts_package_name= ] 'dts_package_name'
Specifies the name of the Data Transformation Services (DTS) package. dts_package_name is a sysname with
a default of NULL. For example, to specify a package of DTSPub_Package, the parameter would be
@dts_package_name = N'DTSPub_Package' . This parameter is available for push subscriptions. To add DTS
package information to a pull subscription, use sp_addpullsubscription_agent.
[ @dts_package_password= ] 'dts_package_password'
Specifies the password on the package, if there is one. dts_package_password is sysname with a default of
NULL.

NOTE
You must specify a password if dts_package_name is specified.

[ @dts_package_location= ] 'dts_package_location'
Specifies the package location. dts_package_location is a nvarchar(12), with a default of DISTRIBUTOR. The
location of the package can be distributor or subscriber.
[ @distribution_job_name= ] 'distribution_job_name'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be specified for a SQL Server Publisher.

[ @backupdevicetype= ] 'backupdevicetype'
Specifies the type of backup device used when initializing a Subscriber from a backup. backupdevicetype is
nvarchar(20), and can be one of these values:

VALUE DESCRIPTION

logical (default) The backup device is a logical device.

disk The backup device is disk drive.

tape The backup device is a tape drive

backupdevicetype is only used when sync_methodis set to initialize_with_backup.


[ @backupdevicename= ] 'backupdevicename'
Specifies the name of the device used when initializing a Subscriber from a backup. backupdevicename is
nvarchar(1000), with a default of NULL.
[ @mediapassword= ] 'mediapassword'
Specifies a password for the media set if a password was set when the media was formatted. mediapassword
is sysname, with a default value of NULL.

NOTE
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development
work, and plan to modify applications that currently use this feature.

[ @password= ] 'password'
Specifies a password for the backup if a password was set when the backup was created. passwordis
sysname, with a default value of NULL.
[ @fileidhint= ] fileidhint
Identifies an ordinal value of the backup set to be restored. fileidhint is int, with a default value of NULL.
[ @unload= ] unload
Specifies if a tape backup device should be unloaded after the initialization from back is complete. unload is
bit, with a default value of 1. 1 specifies that the tape should be unloaded. unload is only used when
backupdevicetype is tape.
[ @subscriptionlsn= ] subscriptionlsn
Specifies the log sequence number (LSN) at which a subscription should start delivering changes to a node in
a peer-to-peer transactional replication topology. Used with a @sync_type value of initialize from lsn to make
sure that all relevant transactions are replicated to a new node. For more information, see Peer-to-Peer
Transactional Replication.
[ @subscriptionstreams= ] subscriptionstreams
Is the number of connections allowed per Distribution Agent to apply batches of changes in parallel to a
Subscriber, while maintaining many of the transactional characteristics present when using a single thread.
subscriptionstreams is tinyint, with a default value of NULL. A range of values from 1 to 64 is supported. This
parameter is not supported for non- SQL Server Subscribers, Oracle Publishers or peer-to-peer subscriptions.
Whenever subscription streams is used additional rows are added in the msreplication_subscriptions table (1
per stream) with an agent_id set to NULL.
NOTE
Subscriptionstreams do not work for articles configured to deliver Transact-SQL. To use subscriptionstreams, configure
articles to deliver stored procedure calls instead.

[ @subscriber_type=] subscriber_type
Is the type of Subscriber. subscriber_type is tinyint, and can be one of these values.

VALUE DESCRIPTION

0 (default) SQL Server Subscriber

1 ODBC data source server

2 Microsoft Jet database

3 OLE DB provider

[ @memory_optimized=] memory_optimized
Indicates that the subscription supports memory optimized tables. memory_optimized is bit, where 1 equals
true (the subscription supports memory optimized tables).

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addsubscription is used in snapshot replication and transactional replication.
When sp_addsubscription is executed by a member of the sysadmin fixed server role to create a push
subscription, the Distribution Agent job is implicitly created and runs under the SQL Server Agent service
account. We recommend that you execute sp_addpushsubscription_agent and specify the credentials of a
different, agent-specific Windows account for @job_login and @job_password. For more information, see
Replication Agent Security Model.
sp_addsubscription prevents ODBC and OLE DB Subscribers access to publications that:
Were created with the native sync_method in the call to sp_addpublication.
Contain articles that were added to the publication with the sp_addarticle stored procedure that had a
pre_creation_cmd parameter value of 3 (truncate).
Attempt to set update_mode to sync tran.
Have an article configured to use parameterized statements.
In addition, if a publication has the allow_queued_tran option set to true (which enables queuing of
changes at the Subscriber until they can be applied at the Publisher), the timestamp column in an
article is scripted out as timestamp, and changes on that column are sent to the Subscriber. The
Subscriber generates and updates the timestamp column value. For an ODBC or OLE DB Subscriber,
sp_addsubscription fails if an attempt is made to subscribe to a publication that has allow_queued_tran
set to true and articles with timestamp columns in it.
If a subscription does not use a DTS package, it cannot subscribe to a publication that is set to
allow_transformable_subscriptions. If the table from the publication needs to be replicated to both a
DTS subscription and non-DTS subscription, two separate publications have to be created: one for each
type of subscription.
When selecting the sync_type options replication support only, initialize with backup, or initialize from
lsn, the log reader agent must run after executing sp_addsubscription, so that the set-up scripts are
written to the distribution database. The log reader agent must be running under an account that is a
member of the sysadmin fixed server role. When the sync_type option is set to Automatic, no special
log reader agent actions are required.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addsubscription. For pull subscriptions, users with logins in the publication access list can execute
sp_addsubscription.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @publication AS sysname;


DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorks2012Replica';

--Add a push subscription to a transactional publication.


USE [AdventureWorks2012]
EXEC sp_addsubscription
@publication = @publication,
@subscriber = @subscriber,
@destination_db = @subscriptionDB,
@subscription_type = N'push';

--Add an agent job to synchronize the push subscription.


EXEC sp_addpushsubscription_agent
@publication = @publication,
@subscriber = @subscriber,
@subscriber_db = @subscriptionDB,
@job_login = $(Login),
@job_password = $(Password);
GO

See Also
Create a Push Subscription
Create a Subscription for a Non-SQL Server Subscriber
Subscribe to Publications
sp_addpushsubscription_agent (Transact-SQL)
sp_changesubstatus (Transact-SQL)
sp_dropsubscription (Transact-SQL)
sp_helpsubscription (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addsynctriggers (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Creates triggers at the Subscriber used with all types of updatable subscriptions (Immediate, Queued, and
Immediate Updating with Queued Updating as Failover). This stored procedure is executed at the Subscriber on the
subscription database.

IMPORTANT
The sp_script_synctran_commands procedure should be used instead of sp_addsynctrigger. sp_script_synctran_commands
generates a script that contains the sp_addsynctrigger calls.

Transact-SQL Syntax Conventions

Syntax
sp_addsynctriggers [ @sub_table = ] 'sub_table'
, [ @sub_table_owner = ] 'sub_table_owner'
, [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
, [ @ins_proc = ] 'ins_proc'
, [ @upd_proc = ] 'upd_proc'
, [ @del_proc = ] 'del_proc'
, [ @cftproc = ] 'cftproc'
, [ @proc_owner = ] 'proc_owner'
[ , [ @identity_col = ] 'identity_col' ]
[ , [ @ts_col = ] 'timestamp_col' ]
[ , [ @filter_clause = ] 'filter_clause' ]
, [ @primary_key_bitmap = ] 'primary_key_bitmap'
[ , [ @identity_support = ] identity_support ]
[ , [ @independent_agent = ] independent_agent ]
, [ @distributor = ] 'distributor'
[ , [ @pubversion = ] pubversion

Arguments
[ @sub_table=] 'sub_table'
Is the name of the Subscriber table. sub_table is sysname, with no default.
[ @sub_table_owner=] 'sub_table_owner'
Is the name of the owner of the Subscriber table. sub_table_owner is sysname, with no default.
[ @publisher=] 'publisher'
Is the name of the Publisher server. publisher is sysname, with no default.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default. If NULL, the current database is
used.
[ @publication=] 'publication'
Is the name of the publication. Publication is sysname, with no default.
[ @ins_proc=] 'ins_proc'
Is the name of the stored procedure that supports synchronous transaction inserts at the Publisher. ins_proc is
sysname, with no default.
[ @upd_proc=] 'upd_proc'
Is the name of the stored procedure that supports synchronous transaction updates at the Publisher. ins_proc is
sysname, with no default.
[ @del_proc=] 'del_proc'
Is the name of the stored procedure that supports synchronous transaction deletes at the Publisher. ins_proc is
sysname, with no default.
[ @cftproc = ] 'cftproc'
Is the name of the auto-generated procedure used by publications that allow queued updating. cftproc is sysname,
with no default. For publications that allow immediate updating, this value is NULL. This parameter applies to
publications that allow queued updating (Queued Updating and Immediate Updating with Queued Updating as
Failover).
[ @proc_owner = ] 'proc_owner'
Specifies the user account in the Publisher under which all the auto-generated stored procedures for updating
publication (queued and/or immediate) were created. proc_owner is sysname with no default.
[ @identity_col=] 'identity_col'
Is the name of the identity column at the Publisher. identity_col is sysname, with a default of NULL.
[ @ts_col=] 'timestamp_col'
Is the name of the timestamp column at the Publisher. timestamp_col is sysname, with a default of NULL.
[ @filter_clause=] 'filter_clause'
Is a restriction (WHERE) clause that defines a horizontal filter. When entering the restriction clause, omit the
keyword WHERE. filter_clauseis nvarchar(4000), with a default of NULL.
[ @primary_key_bitmap =] 'primary_key_bitmap'
Is a bit map of the primary key columns in the table. primary_key_bitmap is varbinary(4000), with no default.
[ @identity_support = ] identity_support
Enables and disables automatic identity range handling when queued updating is used. identity_support is a bit,
with a default of 0. 0 means that there is no identity range support, 1 enables automatic identity range handling.
[ @independent_agent = ] independent_agent
Indicates whether there is a single Distribution Agent (an independent agent) for this publication, or one
Distribution Agent per publication database and subscription database pair (a shared agent). This value reflects the
value of the independent_agent property of the publication defined at the Publisher. independent_agent is a bit
with a default of 0. If 0, the agent is a Shared Agent. If 1, the agent is an independent agent.
[ @distributor = ] 'distributor'
Is the name of the Distributor. distributor is sysname, with no default.
[ @pubversion= ] pubversion
Indicates the version of the Publisher. pubversion is int, with a default of 1. 1 means that the Publisher version is
Microsoft SQL Server 2000 Service Pack 2 or earlier; 2 means that the Publisher is SQL Server 2000 Service Pack 3
(SP3) or later. pubversion must be explicitly set to 2 when the Publisher version is SQL Server 2000 SP3 or later.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addsynctriggers is used by the Distribution Agent as part of subscription initialization. This stored procedure
is not commonly run by users, but may be useful if the user needs to set up a no-sync subscription manually.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addsynctriggers.

See Also
Updatable Subscriptions for Transactional Replication
sp_script_synctran_commands (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_addtabletocontents (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Inserts references into the merge tracking tables for any rows in a source table that are not currently included in
the tracking tables. Use this option if you have bulk-loaded a large amount of data using bcp, which will not fire
merge tracking triggers. This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_addtabletocontents [ @table_name = ] 'table_name'
[ , [ @owner_name = ] 'owner_name' ]
[ , [ @filter_clause = ] 'filter_clause' ]

Arguments
[ @table_name=] 'table_name'
Is the name of the table. table_name is sysname, with no default.
[ @owner_name=] 'owner_name'
Is the name of the owner of the table. owner_name is sysname, with a default of NULL.
[ @filter_clause= ] 'filter_clause'
Specifies a filter clause that controls which rows of the newly-loaded data should be added to the merge tracking
tables. filter_clause is nvarchar(4000), with a default value of NULL. If filter_clause is null, all bulk loaded rows are
added.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_addtabletocontents is used only in merge replication.
The rows in the table_name are referred to by their rowguidcol and the references are added to the merge
tracking tables. sp_addtabletocontents should be used after bulk copying data into a table that is published using
merge replication. The stored procedure initiates tracking of the rows that were copied and ensures that the new
rows will be included in the next synchronization.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_addtabletocontents.

See Also
System Stored Procedures (Transact-SQL)
sp_adjustpublisheridentityrange (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adjusts the identity range on a publication and reallocates new ranges based on the threshold value on the
publication. This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_adjustpublisheridentityrange [ [ @publication = ] 'publication' ]
[ , [ @table_name = ] 'table_name' ]
[ , [ @table_owner= ] 'table_owner' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication in which new identity ranges are reallocated. publication is sysname, with a default
of NULL.
[ @table_name=] 'table_name'
Is the name of the table in which new identity ranges are reallocated. table_name is sysname, with a default of
NULL.
[ @table_owner=] 'table_owner'
Is the owner of the table at the Publisher. table_owner is sysname, with a default of NULL. If table_owner is not
specified, the name of the current user is used.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_adjustpublisheridentityrange is used in all types of replication.
For a publication which has the auto identity range enabled, the Distribution Agent or Merge Agent is responsible
for automatically adjusting the identity range in a publication based on its threshold value. However, if for some
reason the Distribution Agent or Merge Agent has not been run for a period of time, and identity range resource
have been consumed heavily to the point of threshold, users can call sp_adjustpublisheridentityrange to
allocate a new range of values for a Publisher.
When executing sp_adjustpublisheridentityrange, either publication or table_name must be specified. If both or
neither are specified an error is returned.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_adjustpublisheridentityrange.

See Also
Replicate Identity Columns
System Stored Procedures (Transact-SQL)
sp_article_validation (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Initiates a data validation request for the specified article. This stored procedure is executed at the Publisher on the
publication database and at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_article_validation [ @publication = ] 'publication'
[ , [ @article = ] 'article' ]
[ , [ @rowcount_only = ] type_of_check_requested ]
[ , [ @full_or_fast = ] full_or_fast ]
[ , [ @shutdown_agent = ] shutdown_agent ]
[ , [ @subscription_level = ] subscription_level ]
[ , [ @reserved = ] reserved ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication in which the article exists. publication is sysname, with no default.
[ @article=] 'article'
Is the name of the article to validate. article is sysname, with no default.
[ @rowcount_only=] type_of_check_requested
Specifies if only the rowcount for the table is returned. type_of_check_requested is smallint, with a default of 1.
If 0, perform a rowcount and a Microsoft SQL Server 7.0 compatible checksum.
If 1, perform a rowcount check only.
If 2, perform a rowcount and binary checksum.
[ @full_or_fast=] full_or_fast
Is the method used to calculate the rowcount. full_or_fast is tinyint, and can be one of these values.

VALUE DESCRIPTION

0 Performs full count using COUNT(*).

1 Performs fast count from sysindexes.rows. Counting rows in


sysindexes is faster than counting rows in the actual table.
However, sysindexes is updated lazily, and the rowcount may
not be accurate.
VALUE DESCRIPTION

2 (default) Performs conditional fast counting by first trying the fast


method. If fast method shows differences, reverts to full
method. If expected_rowcount is NULL and the stored
procedure is being used to get the value, a full COUNT(*) is
always used.

[ @shutdown_agent=] shutdown_agent
Specifies if the Distribution agent should shut down immediately upon completion of the validation.
shutdown_agent is bit, with a default of 0. If 0, the Distribution Agent does not shut down. If 1, the Distribution
Agent shuts down after the article is validated.
[ @subscription_level=] subscription_level
Specifies whether or not the validation is picked up by a set of subscribers. subscription_level is bit, with a default
of 0. If 0, validation is applied to all Subscribers. If 1, validation is only applied to a subset of the Subscribers
specified by calls to sp_marksubscriptionvalidation in the current open transaction.
[ @reserved=] reserved
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when requesting validation on a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_article_validation is used in transactional replication.
sp_article_validation causes validation information to be gathered on the specified article and posts a validation
request to the transaction log. When the Distribution Agent receives this request, the Distribution Agent compares
the validation information in the request to the Subscriber table. The results of the validation are displayed in the
Replication Monitor and in SQL Server Agent alerts.

Permissions
Only users with SELECT ALL permissions on the source table for the article being validated can execute
sp_article_validation.

See Also
Validate Replicated Data
sp_marksubscriptionvalidation (Transact-SQL)
sp_publication_validation (Transact-SQL)
sp_table_validation (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_articlecolumn (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Used to specify columns included in an article to vertically filter data in a published table. This stored procedure is
executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_articlecolumn [ @publication = ] 'publication'
, [ @article = ] 'article'
[ , [ @column = ] 'column' ]
[ , [ @operation = ] 'operation' ]
[ , [ @refresh_synctran_procs = ] refresh_synctran_procs ]
[ , [ @ignore_distributor = ] ignore_distributor ]
[ , [ @change_active = ] change_actve ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @internal = ] 'internal' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication that contains this article. publication is sysname, with no default.
[ @article=] 'article'
Is the name of the article. article is sysname, with no default.
[ @column=] 'column'
Is the name of the column to be added or dropped. column is sysname, with a default of NULL. If NULL, all
columns are published.
[ @operation=] 'operation'
Specifies whether to add or drop columns in an article. operation is nvarchar(5), with a default of add. add
marks the column for replication. drop unmarks the column.
[ @refresh_synctran_procs=] refresh_synctran_procs
Specifies whether the stored procedures supporting immediate updating subscriptions are regenerated to match
the number of columns replicated. refresh_synctran_procs is bit, with a default of 1. If 1, the stored procedures
are regenerated.
[ @ignore_distributor =] ignore_distributor
Indicates if this stored procedure executes without connecting to the Distributor. ignore_distributor is bit, with a
default of 0. If 0, the database must be enabled for publishing, and the article cache should be refreshed to reflect
the new columns replicated by the article. If 1, allows article columns to be dropped for articles that reside in an
unpublished database; should be used only in recovery situations.
[ @change_active = ] change_active
Allows modifying the columns in publications that have subscriptions. change_active is an int with a default of 0.
If 0, columns are not modified. If 1, columns can be added or dropped from active articles that have
subscriptions.
[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure may invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default of 0.
0 specifies that changes to the article do not cause the snapshot to be invalid. If the stored procedure detects that
the change does require a new snapshot, an error occurs and no changes are made.
1 specifies that changes to the article may cause the snapshot to be invalid, and if there are existing subscriptions
that would require a new snapshot, gives permission for the existing snapshot to be marked as obsolete and a
new snapshot generated.
[@force_reinit_subscription = ] force_reinit_subscription
Acknowledges that the action taken by this stored procedure may require existing subscriptions to be
reinitialized. force_reinit_subscription is a bit, with a default of 0.
0 specifies that changes to the article do not cause the subscription to be reinitialized. If the stored procedure
detects that the change would require subscriptions to be reinitialized, an error occurs and no changes are made.
1 specifies that changes to the article cause existing subscriptions to be reinitialized, and gives permission for the
subscription reinitialization to occur.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used with a SQL Server Publisher.

[ @internal= ] 'internal'
Internal use only.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_articlecolumn is used in snapshot replication and transactional replication.
Only an unsubscribed article can be filtered using sp_articlecolumn.

Example
DECLARE @publication AS sysname;
DECLARE @table AS sysname;
DECLARE @filterclause AS nvarchar(500);
DECLARE @filtername AS nvarchar(386);
DECLARE @schemaowner AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @table = N'Product';
SET @filterclause = N'[DiscontinuedDate] IS NULL';
SET @filtername = N'filter_out_discontinued';
SET @schemaowner = N'Production';

-- Add a horizontally and vertically filtered article for the Product table.
-- Manually set @schema_option to ensure that the Production schema
-- is generated at the Subscriber (0x8000000).
EXEC sp_addarticle
@publication = @publication,
@article = @table,
@source_object = @table,
@source_owner = @schemaowner,
@schema_option = 0x80030F3,
@vertical_partition = N'true',
@type = N'logbased',
@filter_clause = @filterclause;

-- (Optional) Manually call the stored procedure to create the


-- horizontal filtering stored procedure. Since the type is
-- 'logbased', this stored procedures is executed automatically.
EXEC sp_articlefilter
@publication = @publication,
@article = @table,
@filter_clause = @filterclause,
@filter_name = @filtername;

-- Add all columns to the article.


EXEC sp_articlecolumn
@publication = @publication,
@article = @table;

-- Remove the DaysToManufacture column from the article


EXEC sp_articlecolumn
@publication = @publication,
@article = @table,
@column = N'DaysToManufacture',
@operation = N'drop';

-- (Optional) Manually call the stored procedure to create the


-- vertical filtering view. Since the type is 'logbased',
-- this stored procedures is executed automatically.
EXEC sp_articleview
@publication = @publication,
@article = @table,
@filter_clause = @filterclause;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_articlecolumn.

See Also
Define an Article
Define and Modify a Column Filter
Filter Published Data
sp_addarticle (Transact-SQL)
sp_articleview (Transact-SQL)
sp_changearticle (Transact-SQL)
sp_droparticle (Transact-SQL)
sp_helparticle (Transact-SQL)
sp_helparticlecolumns (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_articlefilter (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Filters data that are published based on a table article. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_articlefilter [ @publication = ] 'publication'
, [ @article = ] 'article'
[ , [ @filter_name = ] 'filter_name' ]
[ , [ @filter_clause = ] 'filter_clause' ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication that contains the article. publication is sysname, with no default.
[ @article=] 'article'
Is the name of the article. article is sysname, with no default.
[ @filter_name=] 'filter_name'
Is the name of the filter stored procedure to be created from the filter_name. filter_name is nvarchar(386), with a
default of NULL. You must specify a unique name for the article filter.
[ @filter_clause=] 'filter_clause'
Is a restriction (WHERE) clause that defines a horizontal filter. When entering the restriction clause, omit the
keyword WHERE. filter_clause is ntext, with a default of NULL.
[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure may invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default of 0.
0 specifies that changes to the article do not cause the snapshot to be invalid. If the stored procedure detects that
the change does require a new snapshot, an error occurs and no changes are made.
1 specifies that changes to the article may cause the snapshot to be invalid, and if there are existing subscriptions
that would require a new snapshot, gives permission for the existing snapshot to be marked as obsolete and a
new snapshot generated.
[ @force_reinit_subscription = ] force_reinit_subscription
Acknowledges that the action taken by this stored procedure may require existing subscriptions to be reinitialized.
force_reinit_subscription is a bit, with a default of 0.
0 specifies that changes to the article do not cause a need for subscriptions to be reinitialized. If the stored
procedure detects that the change would require subscriptions to be reinitialized, an error occurs and no changes
are made.
1 specifies that changes to the article causes existing subscriptions to be reinitialized, and gives permission for the
subscription reinitialization to occur.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used with a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_articlefilter is used in snapshot replication and transactional replication.
Executing sp_articlefilter for an article with existing subscriptions requires that those subscriptions to be
reinitialized.
sp_articlefilter creates the filter, inserts the ID of the filter stored procedure in the filter column of the sysarticles
(Transact-SQL) table, and then inserts the text of the restriction clause in the filter_clause column.
To create an article with a horizontal filter, execute sp_addarticle (Transact-SQL) with no filter parameter. Execute
sp_articlefilter, providing all parameters including filter_clause, and then execute sp_articleview (Transact-SQL),
providing all parameters including the identical filter_clause. If the filter already exists and if the type in
sysarticles is 1 (log-based article), the previous filter is deleted and a new filter is created.
If filter_name and filter_clause are not provided, the previous filter is deleted and the filter ID is set to 0.

Example
DECLARE @publication AS sysname;
DECLARE @table AS sysname;
DECLARE @filterclause AS nvarchar(500);
DECLARE @filtername AS nvarchar(386);
DECLARE @schemaowner AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @table = N'Product';
SET @filterclause = N'[DiscontinuedDate] IS NULL';
SET @filtername = N'filter_out_discontinued';
SET @schemaowner = N'Production';

-- Add a horizontally and vertically filtered article for the Product table.
-- Manually set @schema_option to ensure that the Production schema
-- is generated at the Subscriber (0x8000000).
EXEC sp_addarticle
@publication = @publication,
@article = @table,
@source_object = @table,
@source_owner = @schemaowner,
@schema_option = 0x80030F3,
@vertical_partition = N'true',
@type = N'logbased',
@filter_clause = @filterclause;

-- (Optional) Manually call the stored procedure to create the


-- horizontal filtering stored procedure. Since the type is
-- 'logbased', this stored procedures is executed automatically.
EXEC sp_articlefilter
@publication = @publication,
@article = @table,
@filter_clause = @filterclause,
@filter_name = @filtername;

-- Add all columns to the article.


EXEC sp_articlecolumn
@publication = @publication,
@article = @table;

-- Remove the DaysToManufacture column from the article


EXEC sp_articlecolumn
@publication = @publication,
@article = @table,
@column = N'DaysToManufacture',
@operation = N'drop';

-- (Optional) Manually call the stored procedure to create the


-- vertical filtering view. Since the type is 'logbased',
-- this stored procedures is executed automatically.
EXEC sp_articleview
@publication = @publication,
@article = @table,
@filter_clause = @filterclause;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_articlefilter.

See Also
Define an Article
Define and Modify a Static Row Filter
sp_addarticle (Transact-SQL)
sp_articleview (Transact-SQL)
sp_changearticle (Transact-SQL)
sp_droparticle (Transact-SQL)
sp_helparticle (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_articleview (Transact-SQL)
11/21/2017 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Creates the view that defines the published article when a table is filtered vertically or horizontally. This view is
used as the filtered source of the schema and data for the destination tables. Only unsubscribed articles can be
modified by this stored procedure. This stored procedure is executed at the Publisher on the publication
database.
Transact-SQL Syntax Conventions

Syntax
sp_articleview [ @publication = ] 'publication'
, [ @article = ] 'article'
[ , [ @view_name = ] 'view_name']
[ , [ @filter_clause = ] 'filter_clause']
[ , [ @change_active = ] change_active ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @refreshsynctranprocs = ] refreshsynctranprocs ]
[ , [ @internal = ] internal ]

Arguments
[ @publication=] 'publication'
Is the name of the publication that contains the article. publication is sysname, with no default.
[ @article=] 'article'
Is the name of the article. article is sysname, with no default.
[ @view_name=] 'view_name'
Is the name of the view that defines the published article. view_name is nvarchar(386), with a default of NULL.
[ @filter_clause=] 'filter_clause'
Is a restriction (WHERE) clause that defines a horizontal filter. When entering the restriction clause, omit the
WHERE keyword. filter_clause is ntext, with a default of NULL.
[ @change_active = ] change_active
Allows modifying the columns in publications that have subscriptions. change_active is an int, with a default of
0. If 0, columns are not changed. If 1, views can be created or re-created on active articles that have subscriptions.
[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure may invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default of 0.
0 specifies that changes to the article do not cause the snapshot to be invalid. If the stored procedure detects that
the change does require a new snapshot, an error occurs and no changes are made.
1 specifies that changes to the article may cause the snapshot to be invalid, and if there are existing subscriptions
that would require a new snapshot, gives permission for the existing snapshot to be marked as obsolete and a
new snapshot generated.
[ @force_reinit_subscription = ] force_reinit_subscription
Acknowledges that the action taken by this stored procedure may require existing subscriptions to be
reinitialized. force_reinit_subscription is a bit with a default of 0.
0 specifies that changes to the article do not cause the subscription to be reinitialized. If the stored procedure
detects that the change would require subscriptions to be reinitialized, an error occurs and no changes are made.
1 specifies that changes to the article causes existing subscription to be reinitialized, and gives permission for the
subscription reinitialization to occur.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when publishing from a SQL Server Publisher.

[ @refreshsynctranprocs = ] refreshsynctranprocs
Is if the stored procedures used to synchronize replication are automatically recreated. refreshsynctranprocs is
bit, with a default of 1.
1 means that the stored procedures are re-created.
0 means that the stored procedures are not re-created.
[ @internal= ] internal
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_articleview creates the view that defines the published article and inserts the ID of this view in the
sync_objid column of the sysarticles (Transact-SQL) table, and inserts the text of the restriction clause in the
filter_clause column. If all columns are replicated and there is no filter_clause, the sync_objid in the
sysarticles (Transact-SQL) table is set to the ID of the base table, and the use of sp_articleview is not required.
To publish a vertically filtered table (that is, to filter columns) first run sp_addarticle with no sync_object
parameter, run sp_articlecolumn (Transact-SQL) once for each column to be replicated (defining the vertical
filter), and then run sp_articleview to create the view that defines the published article.
To publish a horizontally filtered table (that is, to filter rows), run sp_addarticle (Transact-SQL) with no filter
parameter. Run sp_articlefilter (Transact-SQL), providing all parameters including filter_clause. Then run
sp_articleview, providing all parameters including the identical filter_clause.
To publish a vertically and horizontally filtered table, run sp_addarticle (Transact-SQL) with no sync_object or
filter parameters. Run sp_articlecolumn (Transact-SQL) once for each column to be replicated, and then run
sp_articlefilter (Transact-SQL) and sp_articleview.
If the article already has a view that defines the published article, sp_articleview drops the existing view and
creates a new one automatically. If the view was created manually (type in sysarticles (Transact-SQL) is 5), the
existing view is not dropped.
If you create a custom filter stored procedure and a view that defines the published article manually, do not run
sp_articleview. Instead, provide these as the filter and sync_object parameters to sp_addarticle (Transact-SQL),
along with the appropriate type value.

Example
DECLARE @publication AS sysname;
DECLARE @table AS sysname;
DECLARE @filterclause AS nvarchar(500);
DECLARE @filtername AS nvarchar(386);
DECLARE @schemaowner AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @table = N'Product';
SET @filterclause = N'[DiscontinuedDate] IS NULL';
SET @filtername = N'filter_out_discontinued';
SET @schemaowner = N'Production';

-- Add a horizontally and vertically filtered article for the Product table.
-- Manually set @schema_option to ensure that the Production schema
-- is generated at the Subscriber (0x8000000).
EXEC sp_addarticle
@publication = @publication,
@article = @table,
@source_object = @table,
@source_owner = @schemaowner,
@schema_option = 0x80030F3,
@vertical_partition = N'true',
@type = N'logbased',
@filter_clause = @filterclause;

-- (Optional) Manually call the stored procedure to create the


-- horizontal filtering stored procedure. Since the type is
-- 'logbased', this stored procedures is executed automatically.
EXEC sp_articlefilter
@publication = @publication,
@article = @table,
@filter_clause = @filterclause,
@filter_name = @filtername;

-- Add all columns to the article.


EXEC sp_articlecolumn
@publication = @publication,
@article = @table;

-- Remove the DaysToManufacture column from the article


EXEC sp_articlecolumn
@publication = @publication,
@article = @table,
@column = N'DaysToManufacture',
@operation = N'drop';

-- (Optional) Manually call the stored procedure to create the


-- vertical filtering view. Since the type is 'logbased',
-- this stored procedures is executed automatically.
EXEC sp_articleview
@publication = @publication,
@article = @table,
@filter_clause = @filterclause;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_articleview.
See Also
Define an Article
Define and Modify a Static Row Filter
sp_addarticle (Transact-SQL)
sp_articlefilter (Transact-SQL)
sp_changearticle (Transact-SQL)
sp_droparticle (Transact-SQL)
sp_helparticle (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_attachsubscription (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Attaches an existing subscription database to any Subscriber. This stored procedure is executed at the new
Subscriber on the master database.

IMPORTANT
This feature is deprecated and will be removed in a future release. This feature should not be used in new development work.
For merge publications that are partitioned using parameterized filters, we recommend using the new features of partitioned
snapshots, which simplify the initialization of a large number of subscriptions. For more information, see Snapshots for Merge
Publications with Parameterized Filters. For publications that are not partitioned, you can initialize a subscription with a
backup. For more information, see Initialize a Transactional Subscription Without a Snapshot.

Transact-SQL Syntax Conventions

Syntax
sp_attachsubscription [ @dbname = ] 'dbname'
, [ @filename = ] 'filename'
[ , [ @subscriber_security_mode = ] 'subscriber_security_mode' ]
[ , [ @subscriber_login = ] 'subscriber_login' ]
[ , [ @subscriber_password = ] 'subscriber_password' ]
[ , [ @distributor_security_mode = ] distributor_security_mode ]
[ , [ @distributor_login = ] 'distributor_login' ]
[ , [ @distributor_password = ] 'distributor_password' ]
[ , [ @publisher_security_mode = ] publisher_security_mode ]
[ , [ @publisher_login = ] 'publisher_login' ]
[ , [ @publisher_password = ] 'publisher_password' ]
[ , [ @job_login = ] 'job_login' ]
[ , [ @job_password = ] 'job_password' ]
[ , [ @db_master_key_password = ] 'db_master_key_password' ]

Arguments
[ @dbname= ] 'dbname'
Is the string that specifies the destination subscription database by name. dbname is sysname, with no default.
[ @filename= ] 'filename'
Is the name and physical location of the primary MDF (master data file). filename is nvarchar(260), with no
default.
[ @subscriber_security_mode= ] 'subscriber_security_mode'
Is the security mode of the Subscriber to use when connecting to a Subscriber when synchronizing.
subscriber_security_mode is int, with a default of NULL.
NOTE
Windows Authentication must be used. If subscriber_security_mode is not 1 (Windows Authentication), an error is returned.

[ @subscriber_login= ] 'subscriber_login'
Is the Subscriber login name to use when connecting to a Subscriber when synchronizing. subscriber_login is
sysname, with a default of NULL.

NOTE
This parameter has been deprecated and is maintained only backward-compatibility of scripts. If subscriber_security_mode is
not 1 and subscriber_login is specified, an error is returned.

[ @subscriber_password= ] 'subscriber_password'
Is the Subscriber password. subscriber_password is sysname, with a default of NULL.

NOTE
This parameter has been deprecated and is maintained only backward-compatibility of scripts. If subscriber_security_mode is
not 1 and subscriber_password is specified, an error is returned.

[ @distributor_security_mode= ] distributor_security_mode
Is the security mode to use when connecting to a Distributor when synchronizing. distributor_security_mode is int,
with a default of 0. 0 specifies SQL Server Authentication. 1 specifies Windows Authentication. When possible, use
Windows Authentication.
[ @distributor_login= ] 'distributor_login'
Is the Distributor login to use when connecting to a Distributor when synchronizing. distributor_login is required if
distributor_security_mode is set to 0. distributor_login is sysname, with a default of NULL.
[ @distributor_password= ] 'distributor_password'
Is the Distributor password. distributor_password is required if distributor_security_mode is set to 0.
distributor_password is sysname, with a default of NULL. The value of distributor_password must be less than 120
Unicode characters.

IMPORTANT
Do not use a blank password. Use a strong password. When possible, prompt users to enter security credentials at runtime.
If you must store credentials in a script file, you must secure the file to prevent unauthorized access.

[ @publisher_security_mode= ] publisher_security_mode
Is the security mode to use when connecting to a Publisher when synchronizing. publisher_security_mode is int,
with a default of 1. If 0, specifies SQL Server Authentication. If 1, specifies Windows Authentication. When possible,
use Windows Authentication.
[ @publisher_login= ] 'publisher_login'
Is the login to use when connecting to a Publisher when synchronizing. publisher_login is sysname, with a default
of NULL.
[ @publisher_password= ] 'publisher_password'
Is the password used when connecting to the Publisher. publisher_password is sysname, with a default of NULL.
The value of publisher_password must be less than 120 Unicode characters.
IMPORTANT
Do not use a blank password. Use a strong password. When possible, prompt users to enter security credentials at runtime.
If you must store credentials in a script file, you must secure the file to prevent unauthorized access.

[ @job_login= ] 'job_login'
Is the login for the Windows account under which the agent runs. job_login is nvarchar(257), with no default. This
Windows account is always used for agent connections to the Distributor.
[ @job_password= ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with no default.
The value of job_password must be less than 120 Unicode characters.

IMPORTANT
When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must
secure the file to prevent unauthorized access.

[ @db_master_key_password= ] 'db_master_key_password'
Is the password of a user-defined Database Master Key. db_master_key_password is nvarchar(524), with a default
value of NULL. If db_master_key_password is not specified, an existing Database Master Key will be dropped and
re-created.

IMPORTANT
When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must
secure the file to prevent unauthorized access.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_attachsubscription is used in snapshot replication, transactional replication, and merge replication.
A subscription cannot be attached to the publication if the publication retention period has expired. If a subscription
with an elapsed retention period is specified, an error occurs either when the subscription is attached or when it is
first synchronized. Publications with a publication retention period of 0 (never expire) are ignored.

Permissions
Only members of the sysadmin fixed server role can execute sp_attachsubscription.

See Also
System Stored Procedures (Transact-SQL)
sp_browsesnapshotfolder (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the complete path for the latest snapshot generated for a publication. This stored procedure is executed at
the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_browsesnapshotfolder [@publication= ] 'publication'
{ [ , [ @subscriber = ] 'subscriber' ]
[ , [ @subscriber_db = ] 'subscriber_db' ] }

Arguments
[ @publication=] 'publication'
Is the name of the publication that contains the article. publication is sysname, with no default.
[ @subscriber=] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[ @subscriber_db=] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

snapshot_folder nvarchar(512) Full path to the snapshot directory.

Remarks
sp_browsesnapshotfolder is used in snapshot replication and transactional replication.
If the subscriber and subscriber_db fields are left NULL, the stored procedure returns the snapshot folder of the
most recent snapshot it can find for the publication. If the subscriber and subscriber_db fields are specified, the
stored procedure returns the snapshot folder for the specified subscription. If a snapshot has not been generated
for the publication, an empty result set is returned.
If the publication is set up to generate snapshot files in both the Publisher working directory and Publisher
snapshot folder, the result set contains two rows. The first row contains the publication snapshot folder and the
second row contains the publisher working directory. sp_browsesnapshotfolder is useful for determining the
directory where snapshot files are generated.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_browsesnapshotfolder.

See Also
System Stored Procedures (Transact-SQL)
sp_browsemergesnapshotfolder (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the complete path for the latest snapshot generated for a merge publication. This stored procedure is
executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_browsemergesnapshotfolder [@publication= ] 'publication'

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

snapshot_folder nvarchar(2000) Full path to the snapshot directory.

Remarks
sp_browsemergesnapshotfolder is used in merge replication.
If the publication is set up to generate snapshot files in both the Publisher working directory and Publisher
snapshot folder, the result set contains two rows: the first row contains the publication snapshot folder, and the
second row contains the publisher working directory.
sp_browsemergesnapshotfolder is useful for determining the directory where the merge snapshot files are
generated. This folder/path and its contents can then be copied to removable media, and the snapshot used to
synchronize a subscription from an alternate snapshot location.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_browsemergesnapshotfolder.

See Also
System Stored Procedures (Transact-SQL)
sp_browsereplcmds (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a result set in a readable version of the replicated commands stored in the distribution database, and is
used as a diagnostic tool. This stored procedure is executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_browsereplcmds [ [ @xact_seqno_start = ] 'xact_seqno_start' ]
[ , [ @xact_seqno_end = ] 'xact_seqno_end' ]
[ , [ @originator_id = ] 'originator_id' ]
[ , [ @publisher_database_id = ] 'publisher_database_id' ]
[ , [ @article_id = ] 'article_id' ]
[ , [ @command_id= ] command_id ]
[ , [ @agent_id = ] agent_id ]
[ , [ @compatibility_level = ] compatibility_level ]

Arguments
[ @xact_seqno_start =] 'xact_seqno_start'
Specifies the lowest valued exact sequence number to return. xact_seqno_start is nchar(22), with a default of
0x00000000000000000000.
[ @xact_seqno_end =] 'xact_seqno_end'
Specifies the highest exact sequence number to return. xact_seqno_end is nchar(22), with a default of
0xFFFFFFFFFFFFFFFFFFFF.
[ @originator_id =] 'originator_id'
Specifies if commands with the specified originator_id are returned. originator_id is int, with a default of NULL.
[ @publisher_database_id =] 'publisher_database_id'
Specifies if commands with the specified publisher_database_id are returned. publisher_database_id is int, with a
default of NULL.
[ @article_id =] 'article_id'
Specifies if commands with the specified article_id are returned. article_id is int, with a default of NULL.
[ @command_id =] command_id
Is the location of the command in MSrepl_commands (Transact-SQL) to be decoded. command_id is int, with a
default of NULL. If specified, all other parameters must be specified also, and xact_seqno_startmust be identical to
xact_seqno_end.
[ @agent_id =] agent_id
Specifies that only commands for a specific replication agent are returned. agent_id is int, with a default value of
NULL.
[ @compatibility_level =] compatibility_level
Is the version of Microsoft SQL Server on which the compatibility_level is int, with a default value of 9000000.
Return Code Values
0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

xact_seqno varbinary(16) Sequence number of the command.

originator_srvname sysname Server where the transaction originated.

originator_db sysname Database where the transaction


originated.

article_id int ID of the article.

type int Type of command.

partial_command bit Indicates whether this is a partial


command.

hashkey int Internal use only.

originator_publication_id int ID of the publication where the


transaction originated.

originator_db_version int Version of the database where the


transaction originated.

originator_lsn varbinary(16) Identifies the log sequence number


(LSN) for the command in the
originating publication. Used in peer-to-
peer transactional replication.

command nvarchar(1024) Transact-SQL command.

command_id int ID of the command in


MSrepl_commands.

Long commands can be split across several rows in the result sets.

Remarks
sp_browsereplcmds is used in transactional replication.

Permissions
Only members of the sysadmin fixed server role or members of the db_owner or replmonitor fixed database
roles on the distribution database can execute sp_browsereplcmds.

See Also
sp_replcmds (Transact-SQL)
sp_replshowcmds (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_change_agent_parameter (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes a parameter of a replication agent profile stored in the MSagent_parameters system table. This stored
procedure is executed at the Distributor where the agent is running, on any database.
Transact-SQL Syntax Conventions

Syntax
sp_change_agent_parameter [ @profile_id= ] profile_id, [ @parameter_name= ] 'parameter_name', [
@parameter_value= ] 'parameter_value'

Arguments
[ @profile_id=] profile_id,
Is the ID of the profile. profile_id is int, with no default.
[ @parameter_name=] 'parameter_name'
Is the name of the parameter. parameter_name is sysname, with no default. For system profiles, the parameters
that can be changed depend on the type of agent. To find out what type of agent this profile_id represents, locate
the profile_id column in the Msagent_profiles table, and note the agent_type value.

NOTE
If a parameter is supported for a given agent_type, but has not been defined in the agent profile, an error is returned. To
add a parameter to an agent profile you must execute sp_add_agent_parameter.

For a Snapshot Agent (agent_type=1), if defined in the profile, the following properties can be changed:
70Subscribers
BcpBatchSize
HistoryVerboseLevel
LoginTimeout
MaxBcpThreads
MaxNetworkOptimization
Output
OutputVerboseLevel
PacketSize
QueryTimeout
StartQueueTimeout
UsePerArticleContentsView
For a Log Reader Agent (agent_type=2), if defined in the profile, the following properties can be changed:
HistoryVerboseLevel
LoginTimeout
MessageInterval
Output
OutputVerboseLevel
PacketSize
PollingInterval
QueryTimeout
ReadBatchSize
ReadBatchThreshold
For a Distribution Agent (agent_type=3), if defined in the profile, the following properties can be changed:
BcpBatchSize
CommitBatchSize
CommitBatchThreshold
FileTransferType
HistoryVerboseLevel
KeepAliveMessageInterval
LoginTimeout
MaxBcpThreads
MaxDeliveredTransactions
MessageInterval
Output
OutputVerboseLevel
PacketSize
PollingInterval
QueryTimeout
QuotedIdentifier
SkipErrors
TransactionsPerHistory
For a Merge Agent (agent_type=4), if defined in the profile, the following properties can be changed:
AltSnapshotFolder
BcpBatchSize
ChangesPerHistory
DestThreads
DownloadGenerationsPerBatch
DownloadReadChangesPerBatch
DownloadWriteChangesPerBatch
DynamicSnapshotLocation
ExchangeType
FastRowCount
FileTransferType
GenerationChangeThreshold
HistoryVerboseLevel
InputMessageFile
InteractiveResolution
InterruptOnMessagePattern
KeepAliveMessageInterval
LoginTimeout
MaxBcpThreads
MaxDownloadChanges
MaxUploadChanges
MetadataRetentionCleanup
NumDeadlockRetries
Output
OutputMessageFile
OutputVerboseLevel
PacketSize
ParallelUploadDownload
PauseOnMessagePattern
PauseTime
PollingInterval
ProcessMessagesAtPublisher
ProcessMessagesAtSubscriber
QueryTimeout
QueueSizeMultiplier
SrcThreads
StartQueueTimeout
SyncToAlternate
UploadGenerationsPerBatch
UploadReadChangesPerBatch
UploadWriteChangesPerBatch
UseInprocLoader
Validate
ValidateInterval
For a Queue Reader Agent (agent_type=9), if defined in the profile, the following properties can be
changed:
HistoryVerboseLevel
LoginTimeout
Output
OutputVerboseLevel
PollingInterval
QueryTimeout
ResolverState
SQLQueueMode
To see what parameters have been defined for a given profile, run sp_help_agent_profile and note the
profile_name associated with the profile_id. With the appropriate profile_id, next run
sp_help_agent_parameters using that profile_id to see the parameters associated with the profile.
Parameters can be added to a profile by executing sp_add_agent_parameter.
[ @parameter_value=] 'parameter_value'
Is the new value of the parameter. parameter_value is nvarchar(255), with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_change_agent_parameter is used in all types of replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_change_agent_parameter.
See Also
Replication Agent Profiles
Replication Distribution Agent
Replication Log Reader Agent
Replication Merge Agent
Replication Queue Reader Agent
Replication Snapshot Agent
sp_add_agent_parameter (Transact-SQL)
sp_drop_agent_parameter (Transact-SQL)
sp_help_agent_parameter (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_change_agent_profile (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes a parameter of a replication agent profile stored in the MSagent_profiles (Transact-SQL) table. This
stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_change_agent_profile [ @profile_id = ] profile_id
, [ @property = ] 'property'
, [ @value = ] 'value'

Arguments
[ @profile_id= ] profile_id
Is the ID of the profile. profile_id is int, with no default.
[ @property= ] 'property'
Is the name of the property. property is sysname, with no default.
[ @value= ] 'value'
Is the new value of the property. value is nvarchar(3000), with no default.
This table describes the profile properties that can be changed.

PROPERTY DESCRIPTION

description Description for the profile.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_change_agent_profile is used in all types of replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_change_agent_profile.

See Also
sp_add_agent_profile (Transact-SQL)
sp_drop_agent_profile (Transact-SQL)
sp_help_agent_profile (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_changearticle (Transact-SQL)
12/20/2017 • 12 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the properties of an article in a transactional or snapshot publication. This stored procedure is executed
at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_changearticle [ [@publication= ] 'publication' ]
[ , [ @article= ] 'article' ]
[ , [ @property= ] 'property' ]
[ , [ @value= ] 'value' ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication that contains the article. publication is sysname, with a default of NULL.
[ @article=] 'article'
Is the name of the article whose property is to be changed. article is sysname, with a default of NULL.
[ @property=] 'property'
Is an article property to change. property is nvarchar(100).
[ @value=] 'value'
Is the new value of the article property. value is nvarchar(255).
This table describes the properties of articles and the values for those properties.

PROPERTY VALUES DESCRIPTION

creation_script Path and name of an article schema


script used to create target tables. The
default is NULL.

del_cmd DELETE statement to execute;


otherwise, it is constructed from the
log.

description New descriptive entry for the article.

dest_object Provided for backward compatibility.


Use dest_table.
PROPERTY VALUES DESCRIPTION

dest_table New destination table.

destination_owner Name of the owner of the destination


object.

filter New stored procedure to be used to


filter the table (horizontal filtering). The
default is NULL. Cannot be changed for
publications in peer-to-peer replication.

fire_triggers_on_snapshot true Replicated user triggers are executed


when the initial snapshot is applied.

Note: For triggers to be replicated, the


bitmask value of schema_option must
include the value 0x100.

false Replicated user triggers are not


executed when the initial snapshot is
applied.

identity_range Controls the size of assigned identity


ranges assigned at the Subscriber. Not
supported for peer-to-peer replication.

ins_cmd INSERT statement to execute;


otherwise, it is constructed from the
log.

pre_creation_cmd Pre-creation command that can drop,


delete, or truncate the destination table
before synchronization is applied.

none Does not use a command.

drop Drops the destination table.

delete Deletes the destination table.

truncate Truncates the destination table.

pub_identity_range Controls the size of assigned identity


ranges assigned at the Subscriber. Not
supported for peer-to-peer replication.

schema_option Specifies the bitmap of the schema


generation option for the given article.
schema_option is binary(8). For more
information, see the Remarks section
later in this topic.

0x00 Disables scripting by the Snapshot


Agent.
PROPERTY VALUES DESCRIPTION

0x01 Generates the object creation (CREATE


TABLE, CREATE PROCEDURE, and so
on).

0x02 Generates the stored procedures that


propagate changes for the article, if
defined.

0x04 Identity columns are scripted using the


IDENTITY property.

0x08 Replicate timestamp columns. If not


set, timestamp columns are replicated
as binary.

0x10 Generates a corresponding clustered


index.

0x20 Converts user-defined data types


(UDT) to base data types at the
Subscriber. This option cannot be used
when there is a CHECK or DEFAULT
constraint on a UDT column, if a UDT
column is part of the primary key, or if
a computed column references a UDT
column. Not supported for Oracle
Publishers.

0x40 Generates corresponding nonclustered


indexes.

0x80 Includes declared referential integrity


on the primary keys.

0x100 Replicates user triggers on a table


article, if defined.

0x200 Replicates FOREIGN KEY constraints. If


the referenced table is not part of a
publication, all FOREIGN KEY
constraints on a published table are
not replicated.

0x400 Replicates CHECK constraints.

0x800 Replicates defaults.

0x1000 Replicates column-level collation.

0x2000 Replicates extended properties


associated with the published article
source object.

0x4000 Replicates unique keys if defined on a


table article.
PROPERTY VALUES DESCRIPTION

0x8000 Replicates primary key and unique keys


on a table article as constraints using
ALTER TABLE statements.

Note: This option has been deprecated.


Use 0x80 and 0x4000 instead.

0x10000 Replicates CHECK constraints as NOT


FOR REPLICATION so that the
constraints are not enforced during
synchronization.

0x20000 Replicates FOREIGN KEY constraints as


NOT FOR REPLICATION so that the
constraints are not enforced during
synchronization.

0x40000 Replicates filegroups associated with a


partitioned table or index.

0x80000 Replicates the partition scheme for a


partitioned table.

0x100000 Replicates the partition scheme for a


partitioned index.

0x200000 Replicates table statistics.

0x400000 Default Bindings

0x800000 Rule Bindings

0x1000000 Full-text index

0x2000000 XML schema collections bound to xml


columns are not replicated.

0x4000000 Replicates indexes on xml columns.

0x8000000 Create any schemas not already


present on the subscriber.

0x10000000 Converts xml columns to ntext on the


Subscriber.

0x20000000 Converts large object data types


(nvarchar(max), varchar(max), and
varbinary(max)) that were introduced
in SQL Server 2005 to data types that
are supported on SQL Server 2000.

0x40000000 Replicate permissions.


PROPERTY VALUES DESCRIPTION

0x80000000 Attempt to drop dependencies to any


objects that are not part of the
publication.

0x100000000 Use this option to replicate the


FILESTREAM attribute if it is specified
on varbinary(max) columns. Do not
specify this option if you are replicating
tables to SQL Server 2005 Subscribers.
Replicating tables that have
FILESTREAM columns to SQL Server
2000 Subscribers is not supported,
regardless of how this schema option is
set.

See related option 0x800000000.

0x200000000 Converts date and time data types


(date, time, datetimeoffset, and
datetime2) that were introduced in
SQL Server 2008 to data types that are
supported on earlier versions of SQL
Server.

0x400000000 Replicates the compression option for


data and indexes. For more
information, see Data Compression.

0x800000000 Set this option to store FILESTREAM


data on its own filegroup at the
Subscriber. If this option is not set,
FILESTREAM data is stored on the
default filegroup. Replication does not
create filegroups; therefore, if you set
this option, you must create the
filegroup before you apply the
snapshot at the Subscriber. For more
information about how to create
objects before you apply the snapshot,
see Execute Scripts Before and After the
Snapshot Is Applied.

See related option 0x100000000.

0x1000000000 Converts common language runtime


(CLR) user-defined types (UDTs) larger
than 8000 bytes to varbinary(max)
so that columns of type UDT can be
replicated to Subscribers that are
running SQL Server 2005.

0x2000000000 Converts the hierarchyid data type to


varbinary(max) so that columns of
type hierarchyid can be replicated to
Subscribers that are running SQL
Server 2005. For more information
about how to use hierarchyid
columns in replicated tables, see
hierarchyid (Transact-SQL).
PROPERTY VALUES DESCRIPTION

0x4000000000 Replicates any filtered indexes on the


table. For more information about
filtered indexes, see Create Filtered
Indexes.

0x8000000000 Converts the geography and


geometry data types to
varbinary(max) so that columns of
these types can be replicated to
Subscribers that are running SQL
Server 2005.

0x10000000000 Replicates indexes on columns of type


geography and geometry.

0x20000000000 Replicates the SPARSE attribute for


columns. For more information about
this attribute, see Use Sparse Columns.

0x40000000000 Enable scripting by the snapshot agent


to create memory optimized table on
the subscriber.

0x80000000000 Converts clustered index to


nonclustered index for memory-
optimized articles.

status Specifies the new status of the


property.

dts horizontal partitions Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.

include column names Column names are included in the


replicated INSERT statement.

no column names Column names are not included in the


replicated INSERT statement.

no dts horizontal partitions The horizontal partition for the article is


not defined by a transformable
subscription.

none Clears all status options in the


sysarticles table and marks the article
as inactive.

parameters Changes are propagated to the


Subscriber using parameterized
commands. This is the default setting
for a new article.

string literals Changes are propagated to the


Subscriber using string literal values.
PROPERTY VALUES DESCRIPTION

sync_object Name of the table or view used to


produce a synchronization output file.
The default is NULL. Not supported for
Oracle Publishers.

tablespace Identifies the tablespace used by the


logging table for an article published
from an Oracle database. For more
information, see Manage Oracle
Tablespaces.

threshold The percentage value that controls


when the Distribution Agent assigns a
new identity range. Not supported for
peer-to-peer replication.

type Not supported for Oracle Publishers.

logbased Log-based article.

logbased manualboth Log-based article with manual filter and


manual view. This option requires that
the sync_object and filter properties
also be set. Not supported for Oracle
Publishers.

logbased manualfilter Log-based article with manual filter.


This option requires that the
sync_object and filter properties also
be set. Not supported for Oracle
Publishers.

logbased manualview Log-based article with manual view.


This option requires that the
sync_object property also be set. Not
supported for Oracle Publishers.

indexed viewlogbased Log-based indexed view article. Not


supported for Oracle Publishers. For
this type of article, the base table does
not need to be published separately.

indexed viewlogbased manualboth Log-based indexed view article with


manual filter and manual view. This
option requires that the sync_object
and filter properties also be set. For
this type of article, the base table does
not need to be published separately.
Not supported for Oracle Publishers.

indexed viewlogbased manualfilter Log-based indexed view article with


manual filter. This option requires the
sync_object and filter properties also
be set. For this type of article, the base
table does not need to be published
separately. Not supported for Oracle
Publishers.
PROPERTY VALUES DESCRIPTION

indexed viewlogbased manualview Log-based indexed view article with


manual view. This option requires that
the sync_object property also be set.
For this type of article, the base table
does not need to be published
separately. Not supported for Oracle
Publishers.

upd_cmd UPDATE statement to execute;


otherwise, it is constructed from the
log.

NULL NULL Returns a list of article properties that


can be changed.

[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure may invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default of 0.
0 specifies that changes to the article do not cause the snapshot to be invalid. If the stored procedure detects that
the change does require a new snapshot, an error occurs and no changes are made.
1 specifies that changes to the article may cause the snapshot to be invalid, and if there are existing subscriptions
that would require a new snapshot, gives permission for the existing snapshot to be marked as obsolete and a
new snapshot generated.
See the Remarks section for the properties that, when changed, require the generation of a new snapshot.
[ @force_reinit_subscription=]force_reinit_subscription
Acknowledges that the action taken by this stored procedure may require existing subscriptions to be reinitialized.
force_reinit_subscription is a bit with a default of 0.
0 specifies that changes to the article do not cause the subscription to be reinitialized. If the stored procedure
detects that the change would require existing subscriptions to be reinitialized, an error occurs and no changes
are made.
1 specifies that changes to the article cause existing subscriptions to be reinitialized, and gives permission for the
subscription reinitialization to occur.
See the Remarks section for the properties that, when changed, require that all existing subscriptions be
reinitialized.
[ @publisher= ] 'publisher'
Specifies a non- SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when changing article properties on a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changearticle is used in snapshot replication and transactional replication.
When an article belongs to a publication that supports peer-to-peer transactional replication, you can only change
the description, ins_cmd, upd_cmd, and del_cmd properties.
Changing any of the following properties requires that a new snapshot be generated, and you must specify a
value of 1 for the force_invalidate_snapshot parameter:
del_cmd
dest_table
destination_owner
ins_cmd
pre_creation_cmd
schema_options
upd_cmd
Changing any of the following properties requires that existing subscriptions be reinitialized, and you must
specify a value of 1 for the force_reinit_subscription parameter.
del_cmd
dest_table
destination_owner
filter
ins_cmd
status
upd_cmd
Within an existing publication, you can use sp_changearticle to change an article without having to drop
and re-create the entire publication.

NOTE
When changing the value of schema_option, the system does not perform a bitwise update. This means that when you set
schema_option using sp_changearticle, existing bit settings may be turned off. To retain the existing settings, you should
perform | (Bitwise OR) between the value that you are setting and the current value of schema_option, which can be
determined by executing sp_helparticle.

Valid Schema Options


The following table describes the allowable values of schema_option based upon the replication type (shown
across the top) and the article type (shown down the first column).

ARTICLE TYPE REPLICATION TYPE

Transactional Snapshot

logbased All options All options but 0x02


ARTICLE TYPE REPLICATION TYPE

logbased manualfilter All options All options but 0x02

logbased manualview All options All options but 0x02

indexed view logbased All options All options but 0x02

indexed view logbased manualfilter All options All options but 0x02

indexed view logbased manualview All options All options but 0x02

indexed view logbase manualboth All options All options but 0x02

proc exec 0x01, 0x20, 0x2000, 0x400000, 0x01, 0x20, 0x2000, 0x400000,
0x800000, 0x2000000, 0x8000000, 0x800000, 0x2000000, 0x8000000,
0x10000000, 0x20000000, 0x10000000, 0x20000000,
0x40000000, and 0x80000000 0x40000000, and 0x80000000

serializable proc exec 0x01, 0x20, 0x2000, 0x400000, 0x01, 0x20, 0x2000, 0x400000,
0x800000, 0x2000000, 0x8000000, 0x800000, 0x2000000, 0x8000000,
0x10000000, 0x20000000, 0x10000000, 0x20000000,
0x40000000, and 0x80000000 0x40000000, and 0x80000000

proc schema only 0x01, 0x20, 0x2000, 0x400000, 0x01, 0x20, 0x2000, 0x400000,
0x800000, 0x2000000, 0x8000000, 0x800000, 0x2000000, 0x8000000,
0x10000000, 0x20000000, 0x10000000, 0x20000000,
0x40000000, and 0x80000000 0x40000000, and 0x80000000

view schema only 0x01, 0x010, 0x020, 0x040, 0x0100, 0x01, 0x010, 0x020, 0x040, 0x0100,
0x2000, 0x40000, 0x100000, 0x2000, 0x40000, 0x100000,
0x200000, 0x400000, 0x800000, 0x200000, 0x400000, 0x800000,
0x2000000, 0x8000000, 0x40000000, 0x2000000, 0x8000000, 0x40000000,
and 0x80000000 and 0x80000000

func schema only 0x01, 0x20, 0x2000, 0x400000, 0x01, 0x20, 0x2000, 0x400000,
0x800000, 0x2000000, 0x8000000, 0x800000, 0x2000000, 0x8000000,
0x10000000, 0x20000000, 0x10000000, 0x20000000,
0x40000000, and 0x80000000 0x40000000, and 0x80000000

indexed view schema only 0x01, 0x010, 0x020, 0x040, 0x0100, 0x01, 0x010, 0x020, 0x040, 0x0100,
0x2000, 0x40000, 0x100000, 0x2000, 0x40000, 0x100000,
0x200000, 0x400000, 0x800000, 0x200000, 0x400000, 0x800000,
0x2000000, 0x8000000, 0x40000000, 0x2000000, 0x8000000, 0x40000000,
and 0x80000000 and 0x80000000

NOTE
For queued updating publications, the schema_option value of 0x80 must be enabled. The supported schema_option
values for non- SQL Server publications are: 0x01, 0x02, 0x10, 0x40, 0x80, 0x1000 and 0x4000.

Example
DECLARE @publication AS sysname;
DECLARE @article AS sysname;
DECLARE @option AS int;
SET @publication = N'AdvWorksProductTran';
SET @article = N'Product';
SET @option = (SELECT CAST(0x0000000002030073 AS int));

-- Change the schema options to replicate schema with XML.


USE [AdventureWorks2012]
EXEC sp_changearticle
@publication = @publication,
@article = @article,
@property = N'schema_option',
@value = @option,
@force_invalidate_snapshot = 1;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_changearticle.

See Also
View and Modify Article Properties
Change Publication and Article Properties
sp_addarticle (Transact-SQL)
sp_articlecolumn (Transact-SQL)
sp_droparticle (Transact-SQL)
sp_helparticle (Transact-SQL)
sp_helparticlecolumns (Transact-SQL)
sp_changearticlecolumndatatype (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the article column data type mapping for an Oracle publication. This stored procedure is executed at the
Distributor on any database.

NOTE
The data type mappings between supported Publisher types are provided by default. Use
sp_changearticlecolumndatatype only when overriding these default settings.

Transact-SQL Syntax Conventions

Syntax
sp_changearticlecolumndatatype [ @publication= ] 'publication'
[ @article = ] 'article'
[ @column = ] 'column'
[ , [ @type = ] 'type' ]
[ , [ @length = ] length ]
[ , [ @precision = ] precision ]
[ , [ @scale = ] scale ]
[ , [ @publisher = ] 'publisher'

Arguments
[ @publication= ] 'publication'
Is the name of the Oracle publication. publication is sysname, with no default.
[ @article = ] 'article'
Is the name of the article. article is sysname, with no default.
[ @column= ] 'column'
Is the name of the column for which to change the data type mapping. column is sysname, with no default.
[ @type = ] 'type'
Is the name of the Microsoft SQL Server data type in the destination column. type is sysname, with a default of
NULL.
[ @length = ] length
Is the length of the SQL Server data type in the destination column. length is bigint, with a default of NULL.
[ @precision= ] precision
Is the precision of the SQL Server data type in the destination column. precision is bigint, with a default of NULL.
[ @publisher= ] 'publisher'
Specifies a non- SQL Server publisher. publisher is sysname, with a default of NULL.
Return Code Values
0 (success) or 1 (failure)

Remarks
Sp_changearticlecolumndatatype is used to override the default data type mappings between supported
Publisher types (Oracle and SQL Server). To view these default data type mappings, execute
sp_getdefaultdatatypemapping.
sp_changearticlecolumndatatype is only supported for Oracle Publishers. Executing this stored procedure
against a SQL Server publication results in an error.
sp_changearticlecolumndatatype must be executed for each article column mapping that must be changed.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_changearticlecolumndatatype.

See Also
Change Publication and Article Properties
Data Type Mapping for Oracle Publishers
Replication Stored Procedures (Transact-SQL)
sp_changedistpublisher (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the properties of the distribution Publisher. This stored procedure is executed at the Distributor on any
database.
Transact-SQL Syntax Conventions

Syntax
sp_changedistpublisher [ @publisher = ] 'publisher'
[ , [ @property = ] 'property' ]
[ , [ @value = ] 'value' ]

Arguments
[ @publisher= ] 'publisher'
Is the Publisher name. publisher is sysname, with no default.
[ @property= ] 'property'
Is a property to change for the given Publisher. property is sysname and can be one of these values.
[ @value= ] 'value'
Is the value for the given property. value is nvarchar(255), with a default of NULL.
This table describes the properties of Publishers and the values for those properties.

PROPERTY VALUES DESCRIPTION

active true Activates the Publisher.

false Deactivates the publisher

distribution_db Name of the distribution database.

login Login name.

password Strong password for the supplied login.

security_mode 1 Use Windows Authentication when


connecting to the Publisher. This
cannot be changed for a non-
Microsoft SQL Server publisher.

0 Use SQL Server Authentication when


connecting to the Publisher. This
cannot be changed for a non- SQL
Server publisher.
PROPERTY VALUES DESCRIPTION

working_directory Working directory used to store data


and schema files for the publication.

NULL (default) All available property options are


printed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changedistpublisher is used in all types of replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_changedistpublisher.

See Also
View and Modify Distributor and Publisher Properties
sp_adddistpublisher (Transact-SQL)
sp_dropdistpublisher (Transact-SQL)
sp_helpdistpublisher (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_changedistributiondb (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the properties of the distribution database. This stored procedure is executed at the Distributor on any
database.
Transact-SQL Syntax Conventions

Syntax
sp_changedistributiondb [ @database= ] 'database'
[ , [ @property= ] 'property' ]
[ , [ @value= ] 'value' ]

Arguments
[ @database=] 'database'
Is the name of the distribution database. database is sysname, with no default.
[ @property=] 'property'
Is the property to change for the given database. property is sysname, and can be one of these values.

VALUE DESCRIPTION

history_retention History table retention period.

max_distretention Maximum distribution retention period.

min_distretention Minimum distribution retention period.

NULL (default) All available property values are printed.

[ @value=] 'value'
Is the new value for the specified property. value is nvarchar(255), with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changedistributiondb is used in all types of replication.

Example
DECLARE @distributionDB AS sysname;
SET @distributionDB = N'distribution';

-- Change the history retention period to 24 hours and the


-- maximum retention period to 48 hours.
USE distribution
EXEC sp_changedistributiondb @distributionDB, N'history_retention', 24
EXEC sp_changedistributiondb @distributionDB, N'max_distretention', 48
GO

Permissions
Only members of the sysadmin fixed server role can execute sp_changedistributiondb.

See Also
View and Modify Distributor and Publisher Properties
sp_adddistributiondb (Transact-SQL)
sp_dropdistributiondb (Transact-SQL)
sp_helpdistributiondb (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_changedistributor_password (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the password for a Distributor. This stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_changedistributor_password [ @password= ] 'password'

Arguments
[ @password=] 'password'
Is the new password. password is sysname, with no default. If the Distributor is local, the password of the
distributor_admin system login is changed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changedistributor_password is used in all types of replication.

Example
-- Change the password on the Distributor.
-- To avoid storing the password in the script file, the value is passed
-- into SQLCMD as a scripting variable. For information about how to use
-- scripting variables on the command line and in SQL Server Management
-- Studio, see the "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".
USE master
EXEC sp_changedistributor_password $(Password)
GO

Permissions
Only members of the sysadmin fixed server role can execute sp_changedistributor_password.

See Also
View and Modify Replication Security Settings
Secure the Distributor
sp_adddistributor (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_changedistributor_property (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the properties of the Distributor. This stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_changedistributor_property [ [ @property= ] 'property' ]
[ , [ @value= ] 'value' ]

Arguments
[ @property=] 'property'
Is the property for a given Distributor. property is sysname, and can be one of these values.

VALUE DESCRIPTION

heartbeat_interval Maximum number of minutes that an agent can run without


logging a progress message.

NULL (default) All available property values are printed.

[ @value=] 'value'
Is the value for the given Distributor property. value is varchar(255), with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changedistributor_property is used in all types of replication.

Example
-- Change the heartbeat interval at the Distributor to 5 minutes.
USE master
exec sp_changedistributor_property
@property = N'heartbeat_interval',
@value = 5;
GO

Permissions
Only members of the sysadmin fixed server role can execute sp_changedistributor_property.

See Also
View and Modify Distributor and Publisher Properties
sp_adddistributor (Transact-SQL)
sp_dropdistributor (Transact-SQL)
sp_helpdistributor (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_changedynamicsnapshot_job (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Modifies the agent job that generates the snapshot for a subscription to a publication with a parameterized row
filter. This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_changedynamicsnapshot_job [ @publication = ] 'publication'
[ , [ @dynamic_snapshot_jobname = ] 'dynamic_snapshot_jobname' ]
[ , [ @dynamic_snapshot_jobid = ] 'dynamic_snapshot_jobid' ]
[ , [ @frequency_type = ] frequency_type ]
[ , [ @frequency_interval = ] frequency_interval ]
[ , [ @frequency_subday = ] frequency_subday ]
[ , [ @frequency_subday_interval = ] frequency_subday_interval ]
[ , [ @frequency_relative_interval = ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor = ] frequency_recurrence_factor ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @active_start_time_of_day = ] active_start_time_of_day ]
[ , [ @active_end_time_of_day = ] active_end_time_of_day ]
[ , [ @job_login = ] 'job_login' ]
[ , [ @job_password = ] 'job_password' ]

Arguments
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @dynamic_snapshot_jobname = ] 'dynamic_snapshot_jobname'
Is the name of the snapshot job being changed. dynamic_snapshot_jobnameis sysname, with default value of
N'%'. If dynamic_snapshot_jobid is specified, you must use the default value for dynamic_snapshot_jobname.
[ @dynamic_snapshot_jobid = ] 'dynamic_snapshot_jobid'
Is the ID of the snapshot job being changed. dynamic_snapshot_jobid is uniqueidentifier, with default value of
NULL. If dynamic_snapshot_jobnameis specified, you must use the default value for dynamic_snapshot_jobid.
[ @frequency_type = ] frequency_type
Is the frequency with which to schedule the agent. frequency_type is int, and can be one of the following values.

VALUE DESCRIPTION

1 One time

2 On demand

4 Daily
VALUE DESCRIPTION

8 Weekly

16 Monthly

32 Monthly relative

64 Autostart

128 Recurring

NULL (default)

[ @frequency_interval = ] frequency_interval
The days that the agent runs. frequency_interval is int, and can be one of the following values.

VALUE DESCRIPTION

1 Sunday

2 Monday

3 Tuesday

4 Wednesday

5 Thursday

6 Friday

7 Saturday

8 Day

9 Weekdays

10 Weekend days

NULL (default)

[ @frequency_subday = ] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of the following
values.

VALUE DESCRIPTION

1 Once

2 Second

4 Minute
VALUE DESCRIPTION

8 Hour

NULL (default)

[ @frequency_subday_interval = ] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of NULL.
[ @frequency_relative_interval = ] frequency_relative_interval
Is the date that the Merge Agent runs. This parameter is used when frequency_type is set to 32 (monthly relative).
frequency_relative_interval is int, and can be one of the following values.

VALUE DESCRIPTION

1 First

2 Second

4 Third

8 Fourth

16 Last

NULL (default)

[ @frequency_recurrence_factor = ] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of NULL.
[ @active_start_date = ] active_start_date
Is the date when the Merge Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of NULL.
[ @active_end_date = ] active_end_date
Is the date when the Merge Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a
default of NULL.
[ @active_start_time_of_day = ] active_start_time_of_day
Is the time of day when the Merge Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is int,
with a default of NULL.
[ @active_end_time_of_day = ] active_end_time_of_day
Is the time of day when the Merge Agent stops being scheduled, formatted as HHMMSS. active_end_time_of_day is
int, with a default of NULL.
[ @job_login= ] 'job_login'
Is the Microsoft Windows Account under which the Snapshot Agent runs when generating the snapshot for a
subscription using a parameterized row filter. job_login is nvarchar(257), with a default value of NULL.
[ @job_password= ] 'job_password'
Is the password for the Windows Account under which the Snapshot Agent runs when generating the snapshot for
a subscription using a parameterized row filter. job_password is nvarchar(257), with a default value of NULL.
IMPORTANT
When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must
secure the file to prevent unauthorized access.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changedynamicsnapshot_job is used in merge replication for publications with parameterized row filters.
After changing an agent login or password, you must stop and restart the agent before the change takes effect.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_changedynamicsnapshot_job.

See Also
View and Modify Replication Security Settings
Snapshots for Merge Publications with Parameterized Filters
sp_changelogreader_agent (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes security properties of a Log Reader agent. This stored procedure is executed at the Publisher on the
publication database.

IMPORTANT
When configuring a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and
job_password, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its
remote Distributor before executing this stored procedure. For more information, see Enable Encrypted Connections to the
Database Engine (SQL Server Configuration Manager).

Syntax
sp_changelogreader_agent [ [ @job_login = ] 'job_login' ]
[ , [ @job_password = ] 'job_password' ]
[ , [ @publisher_security_mode = ] publisher_security_mode ]
[ , [ @publisher_login = ] 'publisher_login' ]
[ , [ @publisher_password = ] 'publisher_password' ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @job_login= ] 'job_login'
Is the login for the Windows account under which the agent runs. job_login is nvarchar(257), with a default of
NULL. This cannot be changed for a non- Microsoft SQL Server publisher.
[ @job_password= ] 'job_password'
Is the password for the Microsoft Windows account under which the agent runs. job_password is sysname, with a
default of NULL.

IMPORTANT
When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must
secure the file to prevent unauthorized access.

[ @publisher_security_mode= ] publisher_security_mode
Is the security mode used by the agent when connecting to the Publisher. publisher_security_mode is smallint,
with a default of NULL. 0 specifies SQL Server Authentication, and 1 specifies Windows Authentication.

IMPORTANT
When possible, use Windows Authentication.

[ @publisher_login= ] 'publisher_login'
Is the login used when connecting to the Publisher. publisher_login is sysname, with a default of NULL.
publisher_login must be specified when publisher_security_mode is 0. If publisher_login is NULL and
publisher_security_mode is 1, then the Windows account specified in job_login is used when connecting to the
Publisher.
[ @publisher_password= ] 'publisher_password'
Is the password used when connecting to the Publisher. publisher_password is sysname, with a default of NULL.

IMPORTANT
Do not use a blank password. Use a strong password. When possible, prompt users to enter security credentials at runtime.
If you must store credentials in a script file, you must secure the file to prevent unauthorized access.

[ @publisher= ] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of NULL. This parameter is only supported for
non-SQL Server Publishers.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changelogreader_agent is used in transactional replication.
sp_changelogreader_agent is used to change the Windows account under which a Log Reader agent runs. You
can change the password of an existing Windows login or supply a new Windows login and password.
After changing an agent login or password, you must stop and restart the agent before the change takes effect.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_changelogreader_agent.

See Also
View and Modify Replication Security Settings
sp_helplogreader_agent (Transact-SQL)
sp_addlogreader_agent (Transact-SQL)
sp_changemergearticle (Transact-SQL)
11/21/2017 • 13 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the properties of a merge article. This stored procedure is executed at the Publisher on the publication
database.
Transact-SQL Syntax Conventions

Syntax
sp_changemergearticle [ @publication = ] 'publication'
, [ @article = ] 'article'
[ , [ @property = ] 'property' ]
[ , [ @value = ] 'value' ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]

Arguments
[ @publication=] 'publication'
Is the name of the publication in which the article exists. publication is sysname, with no default.
[ @article=] 'article'
Is the name of the article to change. article is sysname, with no default.
[ @property=] 'property'
Is the property to change for the given article and publication. property is nvarchar(30), and can be one of the
values listed in the table.
[ @value=] 'value'
Is the new value for the specified property. value is nvarchar(1000), and can be one of the values listed in the
table.
This table describes the properties of articles and the values for those properties.

PROPERTY VALUES DESCRIPTION

allow_interactive_resolver true Enables the use of an interactive


resolver for the article.

false Disables the use of an interactive


resolver for the article.

article_resolver Custom resolver for the article. Applies


only to a table article.

check_permissions (bitmap) 0x00 Table-level permissions are not


checked.
PROPERTY VALUES DESCRIPTION

0x10 Table-level permissions are checked at


the Publisher before INSERT statements
made at the Subscriber are applied at
the Publisher.

0x20 Table-level permissions are checked at


the Publisher before UPDATE
statements made at the Subscriber are
applied at the Publisher.

0x40 Table-level permissions are checked at


the Publisher before DELETE statements
at the Subscriber are applied at the
Publisher.

column_tracking true Turns on column level tracking. Applies


only to a table article.

Note: Column level tracking cannot be


used when publishing tables with more
than 246 columns.

false Turns off column level tracking and


leaves conflict detection at the row
level. Applies only to a table article.

compensate_for_errors true Compensating actions are performed


when errors occur during
synchronization. For more information,
see sp_addmergearticle.

false Compensating actions are not


performed, which is the default
behavior. For more information, see
sp_addmergearticle.

** Important *\* Although data in the


affected rows might appear to be out of
convergence, as soon as you address
any errors, changes can be applied and
data will converge. If the source table
for an article is already published in
another publication, then the value of
compensate_for_errors must be the
same for both articles.

creation_script Path and name of an optional article


schema script used to create the article
in the subscription database.

delete_tracking true DELETE statements are replicated,


which is the default behavior.
PROPERTY VALUES DESCRIPTION

false DELETE statements are not replicated.

** Important *\* Setting


delete_tracking to false results in
non-convergence, and deleted rows
need to be manually removed.

description Descriptive entry for the article.

destination_owner Name of the owner of the object in the


subscription database, if not dbo.

identity_range bigint that specifies the range size to


use when assigning new identity values
if the article has
identityrangemanagementoption set
to auto or auto_identity_range set to
true. Applies to a table article only. For
more information, see the "Merge
Replication" section of Replicate Identity
Columns.

identityrangemanagementoption manual Disables automatic identity range


management. Marks identity columns
using NOT FOR REPLICATION to enable
manual identity range handling. For
more information, see Replicate Identity
Columns.

none Disables all identity range management.

logical_record_level_conflict_detecti true A conflict is detected if changes are


on made anywhere in the logical record.
Requires that
logical_record_level_conflict_resolut
ion be set to true.

false Default conflict detection is used as


specified by column_tracking.

logical_record_level_conflict_resolut true Entire winning logical record overwrites


ion the losing logical record.

false Winning rows are not constrained to


the logical record.

partition_options 0 The filtering for the article either is


static or does not yield a unique subset
of data for each partition, i.e. an
"overlapping" partition.

1 The partitions are overlapping, and


DML updates made at the Subscriber
cannot change the partition to which a
row belongs.
PROPERTY VALUES DESCRIPTION

2 The filtering for the article yields non-


overlapping partitions, but multiple
Subscribers can receive the same
partition.

3 The filtering for the article yields non-


overlapping partitions that are unique
for each subscription.

Note: If you specify a value of 3 for


partition_options, there can be only a
single subscription for each partition of
data in that article. If a second
subscription is created in which the
filtering criterion of the new
subscription resolves to the same
partition as the existing subscription,
the existing subscription is dropped.

pre_creation_command none If the table already exists at the


Subscriber, no action is taken.

delete Issues a delete based on the WHERE


clause in the subset filter.

drop Drops the table before re-creating it.

truncate Truncates the destination table.

processing_order int that indicates the processing order


of articles in a merge publication.

pub_identity_range bigint that specifies the range size


allocated to a Subscriber with a server
subscription if the article has
identityrangemanagementoption set
to auto or auto_identity_range set to
true. This identity range is reserved for
a republishing Subscriber to allocate to
its own Subscribers. Applies to a table
article only. For more information, see
the "Merge Replication" section of
Replicate Identity Columns.

published_in_tran_pub true Article is also published in a


transactional publication.

false Article is not also published in a


transactional publication.
PROPERTY VALUES DESCRIPTION

resolver_info Is used to specify additional information


required by a custom resolver. Some of
the Microsoft Resolvers require a
column provided as input to the
resolver. resolver_info is
nvarchar(255), with a default of NULL.
For more information, see Microsoft
COM-Based Resolvers.

schema_option (bitmap) For more information, see the Remarks


section later in this topic.

0x00 Disables scripting by the Snapshot


Agent and uses the script provided in
creation_script.

0x01 Generates the object creation script


(CREATE TABLE, CREATE PROCEDURE,
and so on).

0x10 Generates a corresponding clustered


index.

0x20 Converts user-defined data types to


base data types at the Subscriber. This
option cannot be used when there is a
CHECK or DEFAULT constraint on a
user-defined type (UDT) column, if a
UDT column is part of the primary key,
or if a computed column references a
UDT column.

0x40 Generates corresponding nonclustered


indexes.

0x80 Includes declared referential integrity


on the primary keys.

0x100 Replicates user triggers on a table


article, if defined.

0x200 Replicates FOREIGN KEY constraints. If


the referenced table is not part of a
publication, all FOREIGN KEY
constraints on a published table are not
replicated.

0x400 Replicates CHECK constraints.

0x800 Replicates defaults.

0x1000 Replicates column-level collation.


PROPERTY VALUES DESCRIPTION

0x2000 Replicates extended properties


associated with the published article
source object.

0x4000 Replicates unique keys if defined on a


table article.

0x8000 Generates ALTER TABLE statements


when scripting constraints.

0x10000 Replicates CHECK constraints as NOT


FOR REPLICATION so that the
constraints are not enforced during
synchronization.

0x20000 Replicates FOREIGN KEY constraints as


NOT FOR REPLICATION so that the
constraints are not enforced during
synchronization.

0x40000 Replicates filegroups associated with a


partitioned table or index.

0x80000 Replicates the partition scheme for a


partitioned table.

0x100000 Replicates the partition scheme for a


partitioned index.

0x200000 Replicates table statistics.

0x400000 Replicates default Bindings

0x800000 Replicates rule Bindings

0x1000000 Replicates the full-text index

0x2000000 XML schema collections bound to xml


columns are not replicated.

0x4000000 Replicates indexes on xml columns.

0x8000000 Create any schemas not already


present on the subscriber.

0x10000000 Converts xml columns to ntext on the


Subscriber.

0x20000000 Converts large object data types


(nvarchar(max), varchar(max), and
varbinary(max)) that were introduced
in SQL Server 2005 to data types that
are supported on SQL Server 2000.
PROPERTY VALUES DESCRIPTION

0x40000000 Replicate permissions.

0x80000000 Attempt to drop dependencies to any


objects that are not part of the
publication.

0x100000000 Use this option to replicate the


FILESTREAM attribute if it is specified
on varbinary(max) columns. Do not
specify this option if you are replicating
tables to SQL Server 2005 Subscribers.
Replicating tables that have
FILESTREAM columns to SQL Server
2000 Subscribers is not supported,
regardless of how this schema option is
set. See related option 0x800000000.

0x200000000 Converts date and time data types


(date, time, datetimeoffset, and
datetime2) that are introduced in SQL
Server 2008 to data types that are
supported on earlier versions of SQL
Server.

0x400000000 Replicates the compression option for


data and indexes. For more information,
see Data Compression.

0x800000000 Set this option to store FILESTREAM


data on its own filegroup at the
Subscriber. If this option is not set,
FILESTREAM data is stored on the
default filegroup. Replication does not
create filegroups; therefore, if you set
this option, you must create the
filegroup before you apply the
snapshot at the Subscriber. For more
information about how to create
objects before you apply the snapshot,
see Execute Scripts Before and After the
Snapshot Is Applied.

See related option 0x100000000.

0x1000000000 Converts common language runtime


(CLR) user-defined types (UDTs) to
varbinary(max) so that columns of
type UDT can be replicated to
Subscribers that are running SQL Server
2005.
PROPERTY VALUES DESCRIPTION

0x2000000000 Converts the hierarchyid data type to


varbinary(max) so that columns of
type hierarchyid can be replicated to
Subscribers that are running SQL Server
2005. For more information about how
to use hierarchyid columns in
replicated tables, see hierarchyid
(Transact-SQL).

0x4000000000 Replicates any filtered indexes on the


table. For more information about
filtered indexes, see Create Filtered
Indexes.

0x8000000000 Converts the geography and


geometry data types to
varbinary(max) so that columns of
these types can be replicated to
Subscribers that are running SQL Server
2005.

0x10000000000 Replicates indexes on columns of type


geography and geometry.

NULL System auto-generates a valid schema


option for the article.

status active Initial processing script to publish the


table is run.

unsynced The initial processing script to publish


the table is run the next time the
Snapshot Agent runs.

stream_blob_columns true A data stream optimization is used


when replicating binary large object
columns. However, certain merge
replication functionalities, such as
logical records, can still prevent the
stream optimization from being used.
stream_blob_columns is set to true
when FILESTREAM is enabled. This
allows replication of FILESTREAM data
to perform optimally and reduce
memory utilization. To force
FILESTREAM table articles to not use
blob streaming, set
stream_blob_columns to false.

** Important *\* Enabling this memory


optimization might hurt the
performance of the Merge Agent
during synchronization. This option
should only be used when replicating
columns that contain megabytes of
data.
PROPERTY VALUES DESCRIPTION

false The optimization is not used when


replicating binary large object columns.

subscriber_upload_options 0 No restrictions on updates made at a


Subscriber with a client subscription;
changes are uploaded to the Publisher.
Changing this property may require
that existing Subscribers be reinitialized.

1 Changes are allowed at a Subscriber


with a client subscription, but they are
not uploaded to the Publisher.

2 Changes are not allowed at a


Subscriber with a client subscription.

subset_filterclause WHERE clause specifying the horizontal


filtering. Applies only to a table article.

** Important *\* For performance


reasons, we recommended that you not
apply functions to column names in
parameterized row filter clauses, such as
LEFT([MyColumn]) = SUSER_SNAME() .
If you use HOST_NAME in a filter clause
and override the HOST_NAME value,
you might have to convert data types
by using CONVERT. For more
information about best practices for
this case, see the section "Overriding
the HOST_NAME() Value" in
Parameterized Row Filters.

threshold Percentage value used for Subscribers


running SQL Server Compact or earlier
versions of SQL Server. threshold
controls when the Merge Agent assigns
a new identity range. When the
percentage of values specified in
threshold is used, the Merge Agent
creates a new identity range. Used
when
identityrangemanagementoption is
set to auto or auto_identity_range is
set to true. Applies to a table article
only. For more information, see the
"Merge Replication" section of Replicate
Identity Columns.

verify_resolver_signature 1 Digital signature on a custom resolver


is verified to determine if it is from a
trusted source.

0 Digital signature on a custom resolver


is not verified to determine if it is from
a trusted source.
PROPERTY VALUES DESCRIPTION

NULL (default) Returns the list of supported values for


property.

[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure may invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default of 0.
0 specifies that changes to the merge article do not cause the snapshot to be invalid. If the stored procedure
detects that the change does require a new snapshot, an error occurs and no changes are made.
1 means that changes to the merge article may cause the snapshot to be invalid, and if there are existing
subscriptions that would require a new snapshot, gives permission for the existing snapshot to be marked as
obsolete and a new snapshot generated.
See the Remarks section for the properties that, when changed, require the generation of a new snapshot.
[ @force_reinit_subscription = ] force_reinit_subscription
Acknowledges that the action taken by this stored procedure may require existing subscriptions to be reinitialized.
force_reinit_subscription is a bit, with a default of 0.
0 specifies that changes to the merge article do not cause the subscription to be reinitialized. If the stored
procedure detects that the change would require existing subscriptions to be reinitialized, an error occurs and no
changes are made.
1 means that changes to the merge article cause existing subscriptions to be reinitialized, and gives permission for
the subscription reinitialization to occur.
See the Remarks section for the properties that, when changed, require that all existing subscriptions be
reinitialized.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changemergearticle is used in merge replication.
Because sp_changemergearticle is used to change article properties that were initially specified by using
sp_addmergearticle, refer to sp_addmergearticle for additional information about these properties.
Changing the following properties requires that a new snapshot be generated, and you must specify a value of 1
for the force_invalidate_snapshot parameter:
check_permissions
column_tracking
destination_owner
pre_creation_command
schema_options
subset_filterclause
Changing the following properties requires that existing subscriptions be reinitialized, and you must specify
a value of 1 for the force_reinit_subscription parameter:
check_permissions
column_tracking
destination_owner
pre_creation_command
identityrangemanagementoption
subscriber_upload_options
subset_filterclause
creation_script
schema_option
logical_record_level_conflict_detection
logical_record_level_conflict_resolution
When specifying a value of 3 for partition_options, metadata is cleaned up whenever the Merge Agent
runs and the partitioned snapshot expires more quickly. When using this option, you should consider
enabling subscriber requested partitioned snapshot. For more information, see Snapshots for Merge
Publications with Parameterized Filters.
When setting the column_tracking property, if the table is already published in other merge publications,
the column tracking must be the same as the value being used by existing articles based on this table. This
parameter is specific to table articles only.
If multiple publications publish articles based on the same underlying table, changing the delete_tracking
property or the compensate_for_errors property for one article causes the same change to be made to
the other articles that are based on the same table.
If the Publisher login/user account used by the merge process does not have the correct table permissions,
the invalid changes are logged as conflicts.
When changing the value of schema_option, the system does not perform a bitwise update. This means
that when you set schema_option using sp_changemergearticle, existing bit settings may be turned off.
To retain the existing settings, you should perform & (Bitwise AND) between the value that you are setting
and the current value of schema_option, which can be determined by executing sp_helpmergearticle.
Cau t i on

When you many (perhaps hundreds) of articles in a publication and you execute sp_changemergearticle for one
of the articles, it might take a long time to finish execution.

Valid Schema Option Table


The following table describes the allowed schema_optionvalues, depending on article type.

ARTICLE TYPE SCHEMA OPTION VALUES

func schema only 0x01 and 0x2000

indexed view schema only 0x01, 0x040, 0x0100, 0x2000, 0x40000, 0x1000000, and
0x200000
ARTICLE TYPE SCHEMA OPTION VALUES

proc schema only 0x01 and 0x2000

table All options.

view schema only 0x01, 0x040, 0x0100, 0x2000, 0x40000, 0x1000000, and
0x200000

Example
DECLARE @publication AS sysname;
DECLARE @article AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @article = N'SalesOrderHeader';

-- Enable column-level conflict tracking.


-- Changing this property requires that existing subscriptions
-- be reinitialized and that a new snapshot be generated.
USE [AdventureWorks2012]
EXEC sp_changemergearticle
@publication = @publication,
@article = @article,
@property = N'column_tracking',
@value = N'true',
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_changemergearticle.

See Also
View and Modify Article Properties
Change Publication and Article Properties
sp_addmergearticle (Transact-SQL)
sp_dropmergearticle (Transact-SQL)
sp_helpmergearticle (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_changemergefilter (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes some merge filter properties. This stored procedure is executed at the Publisher on the publication
database.
Transact-SQL Syntax Conventions

Syntax
sp_changemergefilter [ @publication= ] 'publication'
, [ @article= ] 'article'
, [ @filtername= ] 'filtername'
, [ @property= ] 'property'
, [ @value= ] 'value'
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @article= ] 'article'
Is the name of the article. article is sysname, with no default.
[ @filtername= ] 'filtername'
Is the current name of the filter. filtername is sysname, with no default.
[ @property= ] 'property'
Is the name of the property to change. property is sysname, with no default.
[ @value=] 'value'
Is the new value for the specified property. valueis nvarchar(1000), with no default.
This table describes the properties of articles and the values for those properties.

PROPERTY VALUE DESCRIPTION

filter_type 1 Join filter.

This option is required to support SQL


Server Compact Subscribers.

2 Logical record relationship.

3 Join filter is also a logical record


relationship.
PROPERTY VALUE DESCRIPTION

filtername Name of the filter.

join_articlename Name of the join article.

join_filterclause Filter clause.

join_unique_key true Join is on a unique key

false Join is not on a unique key.

[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure may invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default 0.
0 specifies that changes to the merge article do not cause the snapshot to be invalid. If the stored procedure
detects that the change does require a new snapshot, an error occurs and no changes are made.
1 means that changes to the merge article may cause the snapshot to be invalid, and if there are existing
subscriptions that would require a new snapshot, gives permission for the existing snapshot to be marked as
obsolete and a new snapshot generated.
[ @force_reinit_subscription = ] force_reinit_subscription
Acknowledges that the action taken by this stored procedure may require existing subscriptions to be reinitialized.
force_reinit_subscription is a bit with a default of 0.
0 specifies that changes to the merge article do not cause the subscription to be reinitialized. If the stored
procedure detects that the change would require existing subscriptions to be reinitialized, an error occurs and no
changes are made.
1 means that changes to the merge article will cause existing subscriptions to be reinitialized, and gives permission
for the subscription reinitialization to occur.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changemergefilter is used in merge replication.
Changing the filter on a merge article requires the snapshot, if one exists, to be recreated. This is performed by
setting the @force_invalidate_snapshot to 1. Also, if there are subscriptions to this article, the subscriptions
need to be reinitialized. This is done by setting the @force_reinit_subscription to 1.
To use logical records, the publication and articles must meet a number of requirements. For more information,
see Group Changes to Related Rows with Logical Records.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_changemergefilter.

See Also
Change Publication and Article Properties
sp_addmergefilter (Transact-SQL)
sp_dropmergefilter (Transact-SQL)
sp_helpmergefilter (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_changemergepublication (Transact-SQL)
11/21/2017 • 9 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the properties of a merge publication. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_changemergepublication [ @publication= ] 'publication'
[ , [ @property= ] 'property' ]
[ , [ @value= ] 'value' ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]

Arguments
[ @publication=] 'publication'
The name of the publication. publication is sysname, with no default.
[ @property=] 'property'
The property to change for the given publication. property is sysname, and can be one of the values listed in the
table that follows.
[ @value=] 'value'
The new value for the specified property. value is nvarchar(255), and can be one of the values listed in the table
that follows.
This table describes the properties of the publication that can be changed, and describes restrictions on the values
for those properties.

PROPERTY VALUE DESCRIPTION

allow_anonymous true Anonymous subscriptions are allowed.

false Anonymous subscriptions are not


allowed.

allow_partition_realignment true Deletes are sent to the Subscriber to


reflect the results of a partition change
by removing data that is no longer part
of the Subscriber's partition. This is the
default behavior.
PROPERTY VALUE DESCRIPTION

false Data from an old partition is left on the


Subscriber, where changes made to this
data on the Publisher do not replicate
to this Subscriber. Instead, changes that
are made on the Subscriber replicate to
the Publisher. This is used to retain data
in a subscription from an old partition
when the data has to be accessible for
historical purposes.

allow_pull true Pull subscriptions are allowed for the


given publication.

false Pull subscriptions are not allowed for


the given publication.

allow_push true Push subscriptions are allowed for the


given publication.

false Push subscriptions are not allowed for


the given publication.

allow_subscriber_initiated_snapshot true Subscriber can initiate the snapshot


process.

false Subscriber cannot initiate the snapshot


process.

allow_subscription_copy true You can copy the subscription


databases that subscribe to this
publication.

false You cannot copy the subscription


databases that subscribe to this
publication.

allow_synctoalternate true Allows an alternative synchronization


partner to synchronize with this
Publisher.

false Does not allow an alternative


synchronization partner to synchronize
with this Publisher.

allow_web_synchronization true Subscriptions can be synchronized over


HTTPS.

false Subscriptions cannot be synchronized


over HTTPS.

alt_snapshot_folder Specifies the location of the alternative


folder for the snapshot.
PROPERTY VALUE DESCRIPTION

automatic_reinitialization_policy 1 Changes are uploaded from the


Subscriber before the subscription is
reinitialized.

0 The subscription is reinitialized without


first uploading changes.

centralized_conflicts true All conflict records are stored at the


Publisher. If you change this property,
existing Subscribers must be
reinitialized.

false Conflict records are stored at the server


that lost in the conflict resolution. If you
change this property, existing
Subscribers must be reinitialized.

compress_snapshot true Snapshot in an alternative snapshot


folder is compressed into the CAB
format. The snapshot in the default
snapshot folder cannot be compressed.
Changing this property requires a new
snapshot.

false By default, the snapshot is not


compressed. Changing this property
requires a new snapshot.

conflict_logging publisher Conflict records are stored at the


Publisher.

subscriber Conflict records are stored at the


Subscriber that caused the conflict. Not
supported for SQL Server Compact
Subscribers.

both Conflict records are stored at both the


Publisher and Subscriber.

conflict_retention An int that specifies the retention


period, in days, for which conflicts are
retained. Setting conflict_retention to 0
means no conflict cleanup is needed.

description Description of the publication.

dynamic_filters true Publication is filtered based on a


dynamic clause.

false Publication is not filtered dynamically.


PROPERTY VALUE DESCRIPTION

enabled_for_internet true Publication is enabled for the Internet.


File Transfer Protocol (FTP) can be used
to transfer the snapshot files to a
Subscriber. The synchronization files for
the publication are put into the
C:\Program Files\Microsoft SQL
Server\MSSQL\Repldata\ftp directory.

false Publication is not enabled for the


Internet.

ftp_address The network address of the FTP service


for the Distributor. Specifies where
publication snapshot files are stored.

ftp_login The user name that is used to connect


to the FTP service.

ftp_password The user password that is used to


connect to the FTP service.

ftp_port The port number of the FTP service for


the Distributor. Specifies the TCP port
number of the FTP site where the
publication snapshot files are stored.

ftp_subdirectory Specifies where the snapshot files are


created if the publication supports
propagating snapshots by using FTP.

generation_leveling_threshold int Specifies the number of changes that


are contained in a generation. A
generation is a collection of changes
that are delivered to a Publisher or
Subscriber.

keep_partition_changes true Synchronization is optimized, and only


Subscribers that have rows in the
changed partitions are affected.
Changing this property requires a new
snapshot.

false Synchronization is not optimized, and


the partitions that are sent to
Subscribers are verified when data
changes in a partition. Changing this
property requires a new snapshot.

max_concurrent_merge This is an int that represents the


maximum number of concurrent merge
processes that can be run against a
publication. If 0, there is no limit.If more
than this number of merge processes
are scheduled to run at the same time,
the excess jobs are put into a queue
until a currentlmerge process finishes.
PROPERTY VALUE DESCRIPTION

max_concurrent_dynamic_snapshots This is an int that represents the


maximum number of snapshot sessions
to generate a filtered data snapshot
that can concurrently run against a
merge publication that uses
parameterized row filters. If 0, there is
no limit. If more than this number of
snapshot processes are scheduled to
run at the same time, the excess jobs
are put into a queue until a current
merge process finishes.

post_snapshot_script Specifies a pointer to an .sql file


location. The Distribution Agent or
Merge Agent runs the post-snapshot
script after all the other replicated
object scripts and data have been
applied during an initial
synchronization. Changing this
property requires a new snapshot.

pre_snapshot_script Specifies a pointer to an .sql file


location. The Merge Agent runs the
pre-snapshot script before any of the
replicated object scripts when applying
a snapshot at a Subscriber. Changing
this property requires a new snapshot.

publication_compatibility_level 100RTM SQL Server 2008

90RTM SQL Server 2005

publish_to_activedirectory true This parameter has been deprecated


and is only supported for the backward
compatibility of scripts. You can no
longer add publication information to
Active Directory.

false Removes the publication information


from Active Directory.

replicate_ddl 1 Data Definition Language (DDL)


statements that are executed at the
Publisher are replicated.

0 DDL statements are not replicated.


PROPERTY VALUE DESCRIPTION

retention This is an int that represents the


number of retention_period_unit units
for which to save changes for the given
publication. If the subscription is not
synchronized within the retention
period, and the pending changes it
would have received have been
removed by a clean-up operation at the
Distributor, the subscription expires and
must be reinitialized. The maximum
allowable retention period is the
number of days between December 31,
9999, and the current date.

Note: The retention period for merge


publications has a 24 hour grace period
to accommodate Subscribers in
different time zones.

retention_period_unit day Retention period is specified in days.

week Retention period is specified in weeks.

month Retention period is specified in months.

year Retention period is specified in years.

snapshot_in_defaultfolder true Snapshot files are stored in the default


snapshot folder.

false Snapshot files are stored in the


alternative location that is specified by
alt_snapshot_folder. This combination
specifies that the snapshot files are
stored in both the default and
alternative locations.

snapshot_ready true Snapshot for the publication is


available.

false Snapshot for the publication is not


available.

status active Publication is in an active state.

inactive Publication is in an inactive state.

sync_mode native or Native-mode bulk-copy program


output of all tables is used for the initial
bcp native snapshot.

character Character-mode bulk-copy program


output of all tables is used for the initial
or bcp character snapshot, which is required for all non-
SQL Server Subscribers.
PROPERTY VALUE DESCRIPTION

use_partition_groups true Publication uses precomputed


partitions.
Note: After using partition_groups, if
you to revert to using setupbelongs,
and set use_partition_groups=false
in changemergearticle, this might not
be correctly reflected after a snapshot is
taken. The triggers that are generated
by snapshot are compliant with
partition groups.

The workaround to this scenario is to


set the status to Inactive, modify the
use_partition_groups, and then set
status to Active.

false Publication does not use precomputed


partitions.

validate_subscriber_info Lists the functions that are being used


to retrieve Subscriber information.
Then, validates the dynamic filtering
criteria that is being used for the
Subscriber to verify that the
information is partitioned consistently.

web_synchronization_url Default value of the Internet URL used


for Web synchronization.

NULL (default) Returns the list of supported values for


property.

[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure might invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default of 0.
0 specifies that changing the publication does not invalidate the snapshot. If the stored procedure detects that the
change does require a new snapshot, an error occurs and no changes are made.
1 specifies that changing the publication might invvalidate the snapshot. If there are existing subscriptions that
would require a new snapshot, gives permission for the existing snapshot to be marked as obsolete and for a new
snapshot to be generated.
See the Remarks section for the properties that, when changed, require a new snapshot to be generated.
[ @force_reinit_subscription = ] force_reinit_subscription
Acknowledges that the action taken by this stored procedure might require existing subscriptions to be
reinitialized. force_reinit_subscription is a bit with a default of 0.
0 specifies that changing the publication does not require that subscriptions be reinitialized. If the stored
procedure detects that the change would require existing subscriptions to be reinitialized, an error occurs and no
changes are made.
1 specifies that changing the publication causes existing subscriptions to be reinitialized, and gives permission for
the subscription reinitialization to occur.
See the Remarks section for the properties that, when changed, require that all existing subscriptions be
reinitialized.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changemergepublication is used in merge replication.
Changing the following properties requires that a new snapshot be generated. You you must specify a value of 1
for the force_invalidate_snapshot parameter.
alt_snapshot_folder
compress_snapshot
dynamic_filters
ftp_address
ftp_login
ftp_password
ftp_port
ftp_subdirectory
post_snapshot_script
publication_compatibility_level (to 80SP3 only)
pre_snapshot_script
snapshot_in_defaultfolder
sync_mode
use_partition_groups
Changing the following properties requires that existing subscriptions be reinitialized. You must specify a
value of 1 for the force_reinit_subscription parameter.
dynamic_filters
validate_subscriber_info
To list publication objects to Active Directory by using the publish_to_active_directory, the SQL Server
object must already be created in Active Directory.

Example
DECLARE @publication AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';

-- Disable DDL replication for the publication.


USE [AdventureWorks2012]
EXEC sp_changemergepublication
@publication = @publication,
@property = N'replicate_ddl',
@value = 0,
@force_invalidate_snapshot = 0,
@force_reinit_subscription = 0;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_changemergepublication.

See Also
View and Modify Publication Properties
Change Publication and Article Properties
sp_addmergepublication (Transact-SQL)
sp_dropmergepublication (Transact-SQL)
sp_helpmergepublication (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_changemergepullsubscription (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the properties of the merge pull subscription. This stored procedure is executed at the Subscriber on the
subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_changemergepullsubscription [ [ @publication= ] 'publication' ]
[ , [ @publisher= ] 'publisher' ]
[ , [ @publisher_db= ] 'publisher_db' ]
[ , [ @property= ] 'property' ]
[ , [ @value= ] 'value' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of %.
[ @publisher=] 'publisher'
Is the name of the Publisher. publisheris sysname, with a default of %.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_dbis sysname, with a default of %.
[ @property=] 'property'
Is the name of the property to change. property is sysname, and can be one of the values in the table.
[ @value=] 'value'
Is the new value for the specified property. valueis nvarchar(255), and can be one of the values in the table.

PROPERTY VALUE DESCRIPTION

alt_snapshot_folder Location where the snapshot folder is


stored if the location is other than or in
addition to the default location.

description Description of this merge pull


subscription.

distributor Name of the Distributor.

distributor_login Login ID used at the Distributor for


SQL Server Authentication
PROPERTY VALUE DESCRIPTION

distributor_password Password (encrypted) used at the


Distributor for SQL Server
Authentication.

distributor_security_mode 1 Use Windows Authentication when


connecting to the Distributor.

0 Use SQL Server Authentication when


connecting to the Distributor.

dynamic_snapshot_location Path to the folder where the snapshot


files are saved.

ftp_address Available for backward compatibility


only. Is the network address of the File
Transfer Protocol (FTP) service for the
Distributor.

ftp_login Available for backward compatibility


only. Is the username used to connect
to the FTP service.

ftp_password Available for backward compatibility


only. Is the user password used to
connect to the FTP service.

ftp_port Available for backward compatibility


only. Is the port number of the FTP
service for the Distributor.

hostname Specifies a the value for HOST_NAME()


when this function is used in the
WHERE clause of a join filter or logical
record relationship.

internet_login Login that the Merge Agent uses when


connecting to the Web server that is
hosting Web synchronization using
Basic Authentication.

internet_password Password for the login that the Merge


Agent uses when connecting to the
Web server that is hosting Web
synchronization using Basic
Authentication.

internet_security_mode 1 Use Windows Authentication when


connecting to the Web server that is
hosting Web synchronization.

0 Use Basic Authentication when


connecting to the Web server that is
hosting Web synchronization.
PROPERTY VALUE DESCRIPTION

internet_timeout Length of time, in seconds, before a


Web synchronization request expires.

internet_url URL that represents the location of the


replication listener for Web
synchronization.

merge_job_login Login for the Windows account under


which the agent runs.

merge_job_password Password for the Windows account


under which the agent runs.

priority Available for backward compatibility


only; run sp_changemergesubscription
at the Publisher instead to modify the
priority of a subscription.

publisher_login Login ID used at the Publisher for SQL


Server Authentication.

publisher_password Password (encrypted) used at the


Publisher for SQL Server
Authentication.

publisher_security_mode 0 Use SQL Server Authentication when


connecting to the Publisher.

1 Use Windows Authentication when


connecting to the Publisher.

2 Synchronization triggers use a static


sysservers entry to do remote
procedure call (RPC), and the Publisher
must be defined in the sysservers table
as a remote server or linked server.

sync_type automatic Schema and initial data for published


tables are transferred to the Subscriber
first.

none Subscriber already has the schema and


initial data for published tables; system
tables and data are always transferred.

use_ftp true Use FTP instead of the typical protocol


to retrieve snapshots.

false Use the typical protocol to retrieve


snapshots.

use_web_sync true Subscription can be synchronized over


HTTP.
PROPERTY VALUE DESCRIPTION

false Subscription cannot be synchronized


over HTTP.

use_interactive_resolver true Interactive resolver is used during


reconciliation.

false Interactive resolver is not used.

working_directory Fully-qualified path to the directory


where snapshot files are transferred
using FTP when that option is specified.

NULL (default) Returns the list of supported values for


property.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changemergepullsubscription is used in merge replication.
The current server and current database are assumed to be the Subscriber and Subscriber database.
After changing an agent login or password, you must stop and restart the agent before the change takes effect.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_changemergepullsubscription.

See Also
View and Modify Pull Subscription Properties
sp_addmergepullsubscription (Transact-SQL)
sp_dropmergepullsubscription (Transact-SQL)
sp_helpmergepullsubscription (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_changemergesubscription (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes selected properties of a merge push subscription. This stored procedure is executed at the Publisher on
the publication database.

IMPORTANT
When configuring a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and
job_password, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its
remote Distributor before executing this stored procedure. For more information, see Enable Encrypted Connections to the
Database Engine (SQL Server Configuration Manager).

Syntax
sp_changemergesubscription [ [ @publication= ] 'publication' ]
[ , [ @subscriber= ] 'subscriber'
[ , [ @subscriber_db= ] 'subscriber_db' ]
[ , [ @property= ] 'property' ]
[ , [ @value= ] 'value' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication to change. publication is sysname, with a default of NULL. The publication must
already exist and must conform to the rules for identifiers.
[ @subscriber=] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[ @subscriber_db=] 'subscriber_db'
Is the name of the subscription database. subscriber_dbis sysname, with a default of NULL.
[ @property=] 'property'
Is the property to change for the given publication. property is sysname, and can be one of the values in the table.
[ @value=] 'value'
Is the new value for the specified property. value is nvarchar(255), and can be one of the values in the table.

PROPERTY VALUE DESCRIPTION

description Description of this merge subscription.

priority Is the subscription priority. The priority


is used by the default resolver to pick a
winner when conflicts are detected.
PROPERTY VALUE DESCRIPTION

merge_job_login Login for the Microsoft Windows


account under which the agent runs.

merge_job_password Password for the Windows account


under which the agent runs.

publisher_security_mode 1 Use Windows Authentication when


connecting to the Publisher.

0 Use SQL Server Authentication when


connecting to the Publisher.

publisher_login Login name at the Publisher.

publisher_password Strong password for the supplied


Publisher login.

subscriber_security_mode 1 Use Windows Authentication when


connecting to the Subscriber.

0 Use SQL Server Authentication when


connecting to the Subscriber.

subscriber_login Login name at the Subscriber.

subscriber_password Strong password for the supplied


Subscriber login.

sync_type automatic Schema and initial data for published


tables are transferred to the Subscriber
first.

none Subscriber already has the schema and


initial data for published tables; system
tables and data are always transferred.

use_interactive_resolver true Allows conflicts to be resolved


interactively for all articles that allow
interactive resolution.

false Conflicts are resolved automatically


using a default resolver or custom
resolver.

NULL (default) NULL (default)

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changemergesubscription is used in merge replication.
After changing an agent login or password, you must stop and restart the agent before the change takes effect.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_changemergesubscription.

See Also
sp_addmergesubscription (Transact-SQL)
sp_dropmergesubscription (Transact-SQL)
sp_helpmergesubscription (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_changepublication (Transact-SQL)
11/21/2017 • 11 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the properties of a publication. This stored procedure is executed at the Publisher on the publication
database.
Transact-SQL Syntax Conventions

Syntax
sp_changepublication [ [ @publication = ] 'publication' ]
[ , [ @property = ] 'property' ]
[ , [ @value = ] 'value' ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with a default of NULL.
[ @property = ] 'property'
Is the publication property to change. property is nvarchar(255).
[ @value = ] 'value'
Is the new property value. value is nvarchar(255), with a default of NULL.
This table describes the properties of the publication that can be changed and restrictions on the values for those
properties.

PROPERTY VALUE DESCRIPTION

allow_anonymous true Anonymous subscriptions can be


created for the given publication, and
immediate_sync must also be true.
Cannot be changed for peer-to-peer
publications.

false Anonymous subscriptions cannot be


created for the given publication.
Cannot be changed for peer-to-peer
publications.

allow_initialize_from_backup true Subscribers can initialize a subscription


to this publication from a backup rather
than an initial snapshot. This property
cannot be changed for non- Microsoft
SQL Server publications.
PROPERTY VALUE DESCRIPTION

false Subscribers must use the initial


snapshot. This property cannot be
changed for non- SQL Server
publications.

allow_partition_switch true ALTER TABLE…SWITCH statements can


be executed against the published
database. For more information, see
Replicate Partitioned Tables and
Indexes.

false ALTER TABLE…SWITCH statements


cannot be executed against the
published database.

allow_pull true Pull subscriptions are allowed for the


given publication. This property cannot
be changed for non- SQL Server
publications.

false Pull subscriptions are not allowed for


the given publication. This property
cannot be changed for non- SQL Server
publications.

allow_push true Push subscriptions are allowed for the


given publication.

false Push subscriptions are not allowed for


the given publication.

allow_subscription_copy true Enables the ability to copy databases


that subscribe to this publication. This
property cannot be changed for non-
SQL Server publications.

false Disables the ability to copy databases


that subscribe to this publication. This
property cannot be changed for non-
SQL Server publications.

alt_snapshot_folder Location of the alternate folder for the


snapshot.

centralized_conflicts true Conflict records are stored at the


Publisher. Can be changed only if there
are no active subscriptions. This
property cannot be changed for non-
SQL Server publications.

false Conflict records are stored at both the


Publisher and at the Subscriber that
caused the conflict. Can be changed
only if there are no active subscriptions.
This property cannot be changed for
non- SQL Server publications.
PROPERTY VALUE DESCRIPTION

compress_snapshot true Snapshot in an alternate snapshot


folder is compressed into the .cab file
format. The snapshot in the default
snapshot folder cannot be compressed.

false Snapshot is not compressed, which is


the default behavior for replication.

conflict_policy pub wins Conflict resolution policy for updating


Subscribers where the Publisher wins
the conflict. This property can be
changed only if there are no active
subscriptions. Not supported for Oracle
Publishers.

sub reinit For updating Subscribers, if a conflict


occurs the subscription must be
reinitialized. This property can be
changed only if there are no active
subscriptions. Not supported for Oracle
Publishers.

sub wins Conflict resolution policy for updating


Subscribers where the Subscriber wins
the conflict. This property can be
changed only if there are no active
subscriptions. Not supported for Oracle
Publishers.

conflict_retention int that specifies the conflict retention


period, in days. The default retention is
14 days. 0 means that no conflict
cleanup is needed. Not supported for
Oracle Publishers.

description Optional entry describing the


publication.

enabled_for_het_sub true Enables the publication to support


non- SQL Server Subscribers.
enabled_for_het_sub cannot be
changed when there are subscriptions
to the publication. You may need to
execute Replication Stored Procedures
(Transact-SQL) to comply with the
following requirements before setting
enabled_for_het_sub to true:
- allow_queued_tran must be false.
- allow_sync_tran must be false.
Changing enabled_for_het_sub to
true may change existing publication
settings. For more information, see
Non-SQL Server Subscribers. This
property cannot be changed for non-
SQL Server publications.
PROPERTY VALUE DESCRIPTION

false Publication does not support non- SQL


Server Subscribers. This property
cannot be changed for non- SQL Server
publications.

enabled_for_internet true Publication is enabled for the Internet,


and File Transfer Protocol (FTP) can be
used to transfer the snapshot files to a
subscriber. The synchronization files for
the publication are put into the
following directory: C:\Program
Files\Microsoft SQL
Server\MSSQL\Repldata\ftp.
ftp_address cannot be NULL. This
property cannot be changed for non-
SQL Server publications.

false Publication is not enabled for the


Internet. This property cannot be
changed for non- SQL Server
publications.

enabled_for_p2p true The publication supports peer-to-peer


replication. This property cannot be
changed for non- SQL Server
publications.
To set enabled_for_p2p to true, the
following restrictions apply:
- allow_anonymous must be false
- allow_dts must be false.
- allow_initialize_from_backup must
be true
- allow_queued_tran must be false.
- allow_sync_tran must be false.
- enabled_for_het_sub must be false.
- independent_agent must be true.
- repl_freq must be continuous.
- replicate_ddl must be 1.

false The publication does not support peer-


to-peer replication. This property
cannot be changed for non- SQL Server
publications.

ftp_address FTP accessible location of the


publication snapshot files. This property
cannot be changed for non- SQL Server
publications.

ftp_login User name used to connect to the FTP


service, and the value ANONYMOUS is
allowed. This property cannot be
changed for non- SQL Server
publications.
PROPERTY VALUE DESCRIPTION

ftp_password Password for the user name used to


connect to the FTP service. This
property cannot be changed for non-
SQL Server publications.

ftp_port Port number of the FTP service for the


Distributor. This property cannot be
changed for non- SQL Server
publications.

ftp_subdirectory Specifies where the snapshot files are


created if the publication supports
propagating snapshots using FTP. This
property cannot be changed for non-
SQL Server publications.

immediate_sync true Synchronization files for the publication


are created or re-created each time the
Snapshot Agent runs. Subscribers are
able to receive the synchronization files
immediately after the subscription if the
Snapshot Agent has been completed
once before the subscription. New
subscriptions get the newest
synchronization files generated by the
most recent execution of the Snapshot
Agent. independent_agent must also
be true. See remarks below for
additional information about
immediate_sync.

false Synchronization files are created only if


there are new subscriptions.
Subscribers cannot receive the
synchronization files after the
subscription until the Snapshot Agent
is started and completes.

independent_agent true Publication has its own dedicated


Distribution Agent.

false Publication uses a shared Distribution


Agent, and each
publication/subscription database pair
has a shared agent.
PROPERTY VALUE DESCRIPTION

p2p_continue_onconflict true The Distribution Agent continues to


process changes when a conflict is
detected.
Caution: We recommend that you use
the default value of FALSE . When this
option is set to TRUE , the Distribution
Agent tries to converge data in the
topology by applying the conflicting
row from the node that has the highest
originator ID. This method does not
guarantee convergence. You should
make sure that the topology is
consistent after a conflict is detected.
For more information, see "Handling
Conflicts" in Conflict Detection in Peer-
to-Peer Replication.

false The Distribution Agent stops


processing changes when a conflict is
detected.

post_snapshot_script Specifies the location of a Transact-SQL


script file that the Distribution Agent
runs after all the other replicated object
scripts and data have been applied
during an initial synchronization.

pre_snapshot_script Specifies the location of a Transact-SQL


script file that the Distribution Agent
runs before all the other replicated
object scripts and data have been
applied during an initial
synchronization.

publish_to_ActiveDirectory true This parameter has been deprecated


and is only supported for the backward
compatibility of scripts. You can no
longer add publication information to
the Microsoft Active Directory.

false Removes the publication information


from Active Directory.

queue_type sql Use SQL Server to store transactions.


This property can be changed only if
there are no active subscriptions.

Note: Support for using Microsoft


Message Queuing has been
discontinued. Specifying a value of
msmq for value results in an error.

repl_freq continuous Publishes output of all log-based


transactions.

snapshot Publishes only scheduled


synchronization events.
PROPERTY VALUE DESCRIPTION

replicate_ddl 1 Data definition language (DDL)


statements executed at the publisher
are replicated. This property cannot be
changed for non- SQL Server
publications.

0 DDL statements are not replicated. This


property cannot be changed for non-
SQL Server publications. Replication of
schema changes cannot be disabled
when using peer-to-peer replication.

replicate_partition_switch true ALTER TABLE…SWITCH statements that


are executed against the published
database should be replicated to
Subscribers. This option is valid only if
allow_partition_switch is set to TRUE.
For more information, see Replicate
Partitioned Tables and Indexes.

false ALTER TABLE…SWITCH statements


should not be replicated to Subscribers.

retention int representing the retention period, in


hours, for subscription activity. If a
subscription is not active within the
retention period, it is removed.

snapshot_in_defaultfolder true Snapshot files are stored in the default


snapshot folder. If
alt_snapshot_folderis also specified,
snapshot files are stored in both the
default and alternate locations.

false Snapshot files are stored in the


alternate location specified by
alt_snapshot_folder.

status active Publication data is available for


Subscribers immediately when the
publication is created. Not supported
for Oracle Publishers.

inactive Publication data are not available for


Subscribers when the publication is
created. Not supported for Oracle
Publishers.

sync_method native Uses native-mode bulk copy output of


all tables when synchronizing
subscriptions.

character Uses character-mode bulk copy output


of all tables when synchronizing
subscriptions.
PROPERTY VALUE DESCRIPTION

concurrent Uses native-mode bulk-copy program


output of all tables, but does not lock
tables during the snapshot generation
process. Not valid for snapshot
replication.

concurrent_c Uses character-mode bulk copy


program output of all tables, but does
not lock tables during the snapshot
generation process. Not valid for
snapshot replication.

taskid This property has been deprecated and


is no longer supported.

allow_drop true Enables DROP TABLE DLL support for


articles which are part of transactional
replication. Minimum supported
version: SQL Server 2014 Service Pack
2 or above and SQL Server 2016
Service Pack 1 or above. Additional
reference: KB 3170123

false Disables DROP TABLE DLL support for


articles that are part of transactional
replication. This is the default value for
this property.

NULL (default) Returns the list of supported values for


property.

[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure may invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default of 0.
0 specifies that changes to the article do not cause the snapshot to be invalid. If the stored procedure detects
that the change does require a new snapshot, an error occurs and no changes are made.
1 specifies that changes to the article may cause the snapshot to be invalid. If there are existing subscriptions
that would require a new snapshot, this value gives permission for the existing snapshot to be marked as
obsolete and a new snapshot generated.
See the Remarks section for the properties that, when changed, require the generation of a new snapshot.
[@force_reinit_subscription = ] force_reinit_subscription
Acknowledges that the action taken by this stored procedure may require existing subscriptions to be reinitialized.
force_reinit_subscription is a bit with a default of 0.
0 specifies that changes to the article do not cause the subscription to be reinitialized. If the stored procedure
detects that the change would require existing subscriptions to be reinitialized, an error occurs and no changes
are made.
1 specifies that changes to the article cause the existing subscription to be reinitialized, and gives permission
for the subscription reinitialization to occur.
[ @publisher = ] 'publisher'
Specifies a non- SQL Server Publisher. publisher is sysname, with a default of NULL.
NOTE
publisher should not be used when changing article properties on a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changepublication is used in snapshot replication and transactional replication.
After changing any of the following properties, you must generate a new snapshot, and you must specify a value
of 1 for the force_invalidate_snapshot parameter.
alt_snapshot_folder
compress_snapshot
enabled_for_het_sub
ftp_address
ftp_login
ftp_password
ftp_port
ftp_subdirectory
post_snapshot_script
pre_snapshot_script
snapshot_in_defaultfolder
sync_mode
To list publication objects in the Active Directory using the publish_to_active_directory parameter, the SQL
Server object must already be created in the Active Directory.

Impact of immediate sync


When immediate sync is on, all changes in the log are tracked immediately after the initial snapshot is generated
even if there are no subscriptions. Logged changes are used when a customer is using backup to add a new peer
node. After the backup is restored, the peer is synched with any other changes occurring after the backup was
taken. Since the commands are tracked in the distribution database, the synchronization logic can look at the last
backed up LSN and use this as a starting point, knowing that the command is available if the backup was taken
within the max retention period. (The default value for the min retention period is 0 hrs and max retention period
is 24 hrs.)
When immediate sync is off, changes are kept at least the min retention period and cleaned up immediately for all
the transactions that are already replicated. If immediate sync is off and configured with the default retention
period, it is likely that the required changes after the backup was taken were cleaned up and the new peer node
will not be initialized properly. The only option left is to quiesce the topology. Setting immediate sync to on
provides greater flexibility and is the recommended setting for P2P replication.

Example
DECLARE @publication AS sysname
SET @publication = N'AdvWorksProductTran'

-- Turn off DDL replication for the transactional publication.


USE [AdventureWorks2012]
EXEC sp_changepublication
@publication = @publication,
@property = N'replicate_ddl',
@value = 0
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_changepublication.

See Also
View and Modify Publication Properties
Change Publication and Article Properties
sp_addpublication (Transact-SQL)
sp_droppublication (Transact-SQL)
sp_helppublication (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_changepublication_snapshot (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes properties of the Snapshot Agent for the specified publication. This stored procedure is executed at the
Publisher on the publication database.

IMPORTANT
When configuring a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and
job_password, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its
remote Distributor before executing this stored procedure. For more information, see Enable Encrypted Connections to the
Database Engine (SQL Server Configuration Manager).

Transact-SQL Syntax Conventions

Syntax
sp_changepublication_snapshot [ @publication= ] 'publication'
[ , [ @frequency_type= ] frequency_type ]
[ , [ @frequency_interval= ] frequency_interval ]
[ , [ @frequency_subday= ] frequency_subday ]
[ , [ @frequency_subday_interval= ] frequency_subday_interval ]
[ , [ @frequency_relative_interval= ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor= ] frequency_recurrence_factor ]
[ , [ @active_start_date= ] active_start_date ]
[ , [ @active_end_date= ] active_end_date ]
[ , [ @active_start_time_of_day= ] active_start_time_of_day ]
[ , [ @active_end_time_of_day= ] active_end_time_of_day ]
[ , [ @snapshot_job_name = ] 'snapshot_agent_name' ]
[ , [ @publisher_security_mode = ] publisher_security_mode ]
[ , [ @publisher_login = ] 'publisher_login' ]
[ , [ @publisher_password = ] 'publisher_password' ]
[ , [ @job_login = ] 'job_login' ]
[ , [ @job_password = ] 'job_password' ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @frequency_type =] frequency_type
Is the frequency with which to schedule the agent. frequency_type is int, and can be one of the following values.

VALUE DESCRIPTION

1 One time

2 On demand
VALUE DESCRIPTION

4 Daily

8 Weekly

16 Monthly

32 Monthly relative

64 Autostart

128 Recurring

NULL (default)

[ @frequency_interval =] frequency_interval
Specifies the days that the agent runs. frequency_interval is int, and can be one of the following values.

VALUE DESCRIPTION

1 Sunday

2 Monday

3 Tuesday

4 Wednesday

5 Thursday

6 Friday

7 Saturday

8 Day

9 Weekdays

10 Weekend days

NULL (default)

[ @frequency_subday =] frequency_subday
Is the units for freq_subday_interval. frequency_subday is int, and can be one of these values.

VALUE DESCRIPTION

1 Once

2 Second
VALUE DESCRIPTION

4 Minute

8 Hour

NULL (default)

[ @frequency_subday_interval =] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of NULL.
[ @frequency_relative_interval =] frequency_relative_interval
Is the date the Snapshot Agent runs. frequency_relative_interval is int, with a default of NULL.
[ @frequency_recurrence_factor =] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of NULL.
[ @active_start_date =] active_start_date
Is the date when the Snapshot Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of NULL.
[ @active_end_date =] active_end_date
Is the date when the Snapshot Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int,
with a default of NULL.
[ @active_start_time_of_day =] active_start_time_of_day
Is the time of day when the Snapshot Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is
int, with a default of NULL.
[ @active_end_time_of_day =] active_end_time_of_day
Is the time of day when the Snapshot Agent stops being scheduled, formatted as HHMMSS.
active_end_time_of_day is int, with a default of NULL.
[ @snapshot_job_name = ] 'snapshot_agent_name'
Is the name of an existing Snapshot Agent job name if an existing job is being used. snapshot_agent_name is
nvarchar(100) with a default value of NULL.
[ @publisher_security_mode = ] publisher_security_mode
Is the security mode used by the agent when connecting to the Publisher. publisher_security_mode is smallint,
with a default of NULL. 0 specifies SQL Server Authentication, and 1 specifies Windows Authentication. A value of
0 must be specified for non- SQL Server Publishers.

IMPORTANT
When possible, use Windows Authentication.

[ @publisher_login = ] 'publisher_login'
Is the login used when connecting to the Publisher. publisher_login is sysname, with a default of NULL.
publisher_login must be specified when publisher_security_mode is 0. If publisher_login is NULL and
publisher_security_mode is 1, then the Windows account specified in job_login is used when connecting to the
Publisher.
[ @publisher_password = ] 'publisher_password'
Is the password used when connecting to the Publisher. publisher_password is sysname, with a default of NULL.
IMPORTANT
Do not use a blank password. Use a strong password. When possible, prompt users to enter security credentials at runtime.
If you must store credentials in a script file, you must secure the file to prevent unauthorized access.

[ @job_login = ] 'job_login'
Is the login for the Windows account under which the agent runs. job_login is nvarchar(257), with a default of
NULL. This Windows account is always used for agent connections to the Distributor. You must supply this
parameter when creating a new Snapshot Agent job. This cannot be changed for a non- SQL Server publisher.
[ @job_password = ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with a default of
NULL. You must supply this parameter when creating a new Snapshot Agent job.

IMPORTANT
When possible, prompt users to enter security credentials at runtime. If you must store credentials in a script file, you must
secure the file to prevent unauthorized access.

[ @publisher = ] 'publisher'
Specifies a non- SQL Server publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when creating a Snapshot Agent at a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changepublication_snapshot is used in snapshot replication, transactional replication, and merge
replication.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_changepublication_snapshot.

See Also
View and Modify Publication Properties
Change Publication and Article Properties
sp_addpublication_snapshot (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_changeqreader_agent (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes security properties of a Queue Reader agent. This stored procedure is executed at the Distributor on the
distribution database or at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_changeqreader_agent [ [ @job_login = ] 'job_login' ]
[ , [ @job_password = ] 'job_password' ]
[ , [ @frompublisher = ] frompublisher

Arguments
[ @job_login= ] 'job_login'
Is the login for the Microsoft Windows account under which the agent runs. job_login is nvarchar(257), with a
default of NULL.
[ @job_password= ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with a default of
NULL.
[ @frompublisher= ] frompublisher
Is if the procedure is being executed at the Publisher. frompublisher is bit, with a default value of 0. A value of 1
means that the procedure is being executed from the Publisher on the publication database.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changeqreader_agent is used in transactional replication.
sp_changeqreader_agent is used to change the Windows account under which a Queue Reader agent runs. You
can change the password of an existing Windows login or supply a new Windows login and password.
After changing an agent login or password, you must stop and restart the agent before the change takes effect.

Permissions
Only members of the sysadmin fixed server role can execute sp_changeqreader_agent.

See Also
View and Modify Replication Security Settings
sp_addqreader_agent (Transact-SQL)
sp_changereplicationserverpasswords (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes stored passwords for the Microsoft Windows account or Microsoft SQL Server login used by replication
agents when connecting to servers in a replication topology. You would normally have to change a password for
each individual agent running at a server, even if they all use the same login or account. This stored procedure
enables you to change the password for all instances of a given SQL Server Login or Windows account used by all
replication agents that run at a server. This stored procedure is executed at any server in the replication topology
on the master database.
Transact-SQL Syntax Conventions

Syntax
sp_changereplicationserverpasswords [ @login_type = ] login_type
, [ @login = ] 'login'
, [ @password = ] 'password'
[ , [ @server = ] 'server' ]

Arguments
[ @login_type = ] login_type
Is the type of authentication for the supplied credentials. login_type is tinyint, with no default.
1 = Windows Integrated Authentication
0 = SQL Server Authentication
[ @login = ] 'login'
Is the name of the Windows account or SQL Server login being changed. login is nvarchar(257), with no default
[ @password = ] 'password'
Is the new password to be stored for the specified login. password is sysname, with no default.

NOTE
After changing a replication password, you must stop and restart each agent that uses the password before the change takes
effect for that agent.

[ @server = ] 'server'
Is the server connection for which the stored password is being changed. server is sysname, and can be one of
these values:

VALUE DESCRIPTION

distributor All agent connections to the Distributor.


VALUE DESCRIPTION

publisher All agent connections to the Publisher.

subscriber All agent connections to the Subscriber.

% (default) All agent connections to all servers in a replication topology.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changereplicationserverpasswords is used with all types of replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_changereplicationserverpasswords.

See Also
View and Modify Replication Security Settings
sp_changesubscriber (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the options for a Subscriber. Any distribution task for the Subscribers to this Publisher is updated. This
stored procedure writes to the MSsubscriber_info table in the distribution database. This stored procedure is
executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_changesubscriber [ @subscriber= ] 'subscriber'
[ , [ @type= ] type ]
[ , [ @login= ] 'login' ]
[ , [ @password= ] 'password' ]
[ , [ @commit_batch_size= ] commit_batch_size ]
[ , [ @status_batch_size= ] status_batch_size ]
[ , [ @flush_frequency= ] flush_frequency ]
[ , [ @frequency_type= ] frequency_type ]
[ , [ @frequency_interval= ] frequency_interval ]
[ , [ @frequency_relative_interval= ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor= ] frequency_recurrence_factor ]
[ , [ @frequency_subday= ] frequency_subday ]
[ , [ @frequency_subday_interval= ] frequency_subday_interval ]
[ , [ @active_start_time_of_day= ] active_start_time_of_day ]
[ , [ @active_end_time_of_day= ] active_end_time_of_day ]
[ , [ @active_start_date= ] active_start_date ]
[ , [ @active_end_date= ] active_end_date ]
[ , [ @description= ] 'description' ]
[ , [ @security_mode= ] security_mode ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @subscriber=] 'subscriber'
Is the name of the Subscriber on which to change the options. subscriber is sysname, with no default.
[ @type=] type
Is the Subscriber type. type is tinyint, with a default of NULL. 0 indicates a Microsoft SQL Server Subscriber. 1
specifies a non- SQL Server or other ODBC data source server Subscriber.
[ @login=] 'login'
Is the SQL Server Authentication login ID. login is sysname, with a default of NULL.
[ @password=] 'password'
Is the SQL Server Authentication password. password is sysname, with a default of %. % indicates there is no
change to the password property.
[ @commit_batch_size=] commit_batch_size
Supported for backward compatibility only.
[ @status_batch_size=] status_batch_size
Supported for backward compatibility only.
[ @flush_frequency=] flush_frequency
Supported for backward compatibility only.
[ @frequency_type=] frequency_type
Is the frequency with which to schedule the distribution task. frequency_type is int, and can be one of these values.

VALUE DESCRIPTION

1 One time

2 On demand

4 Daily

8 Weekly

16 Monthly

32 Monthly relative

64 Autostart

128 Recurring

[ @frequency_interval=] frequency_interval
Is the interval for frequency_type. frequency_interval is int, with a default of NULL.
[ @frequency_relative_interval=] frequency_relative_interval
Is the date of the distribution task. This parameter is used when frequency_type is set to 32 (monthly relative).
frequency_relative_interval is int, and can be one of these values.

VALUE DESCRIPTION

1 First

2 Second

4 Third

8 Fourth

16 Last

[ @frequency_recurrence_factor=] frequency_recurrence_factor
Is how often the distribution task should recur during the defined frequency_type. frequency_recurrence_factor is
int, with a default of NULL.
[ @frequency_subday=] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of these values.
VALUE DESCRIPTION

1 Once

2 Second

4 Minute

8 Hour

[ @frequency_subday_interval=] frequency_subday_interval
Is the interval for frequence_subday. frequency_subday_interval is int, with a default of NULL.
[ @active_start_time_of_day=] active_start_time_of_day
Is the time of day when the distribution task is first scheduled, formatted as HHMMSS. active_start_time_of_day is
int, with a default of NULL.
[ @active_end_time_of_day=] active_end_time_of_day
Is the time of day when the distribution task stops being scheduled, formatted as HHMMSS.
active_end_time_of_dayis int, with a default of NULL.
[ @active_start_date=] active_start_date
Is the date when the distribution task is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of NULL.
[ @active_end_date=] active_end_date
Is the date when the distribution task stops being scheduled, formatted as YYYYMMDD. active_end_dateis int, with
a default of NULL.
[ @description=] 'description'
Is an optional text description. description is nvarchar(255), with a default of NULL.
[ @security_mode=] security_mode
Is the implemented security mode. security_mode is int, and can be one of these values.

VALUE DESCRIPTION

0 SQL Server Authentication

1 Windows Authentication

[ @publisher= ] 'publisher'
Specifies a non- SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when changing article properties on a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changesubscriber is used in all types of replication.
Permissions
Only members of the sysadmin fixed server role can execute sp_changesubscriber.

See Also
sp_addsubscriber (Transact-SQL)
sp_dropsubscriber (Transact-SQL)
sp_helpdistributiondb (Transact-SQL)
sp_helpserver (Transact-SQL)
sp_helpsubscriberinfo (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_changesubscriber_schedule (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the Distribution Agent or Merge Agent schedule for a subscriber. This stored procedure is executed at the
Publisher on any database.
Transact-SQL Syntax Conventions

Syntax
sp_changesubscriber_schedule [ @subscriber = ] 'subscriber', [ @agent_type = ] type
[ , [ @frequency_type = ] frequency_type ]
[ , [ @frequency_interval = ] frequency_interval ]
[ , [ @frequency_relative_interval = ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor = ] frequency_recurrence_factor ]
[ , [ @frequency_subday = ] frequency_subday ]
[ , [ @frequency_subday_interval = ] frequency_subday_interval ]
[ , [ @active_start_time_of_day = ] active_start_time_of_day ]
[ , [ @active_end_time_of_day = ] active_end_time_of_day ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @subscriber=] 'subscriber'
Is the name of the Subscriber. subscriber is sysname. The name of the Subscriber must be unique in the database,
must not already exist, and cannot be NULL.
[ @agent_type=] type
Is the type of agent. type is smallint, with a default of 0. 0 indicates a Distribution Agent. 1 indicates a Merge
Agent.
[ @frequency_type=] frequency_type
Is the frequency with which to schedule the distribution task. frequency_type is int, with a default of 64. There are
10 schedule columns.
[ @frequency_interval=] frequency_interval
Is the value applied to the frequency set by frequency_type. frequency_interval is int, with a default of 1.
[ @frequency_relative_interval=] frequency_relative_interval
Is the date of the distribution task. frequency_relative_interval is int, with a default of 1.
[ @frequency_recurrence_factor=] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 0.
[ @frequency_subday=] frequency_subday
Is how often, in minutes, to reschedule during the defined period. frequency_subday is int, with a default of 4.
[ @frequency_subday_interval=] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of 5.
[ @active_start_time_of_day=] active_start_time_of_day
Is the time of day when the distribution task is first scheduled. active_start_time_of_day is int, with a default of 0.
[ @active_end_time_of_day=] active_end_time_of_day
Is the time of day when the distribution task stops being scheduled. active_end_time_of_day is int, with a default of
235959, which means 11:59:59 P.M. on a 24-hour clock.
[ @active_start_date=] active_start_date
Is the date when the distribution task is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of 0.
[ @active_end_date=] active_end_date
Is the date when the distribution task stops being scheduled, formatted as YYYYMMDD. active_end_date is int,
with a default of 99991231, which means December 31, 9999.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when changing article properties on a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changesubscriber_schedule is used in all types of replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_changesubscriber_schedule.

See Also
sp_addsubscriber_schedule (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_changesubscriptiondtsinfo (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the Data Transformation Services (DTS) package properties of a subscription. This stored procedure is
executed at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_changesubscriptiondtsinfo [ [ @job_id = ] job_id ]
[ , [ @dts_package_name= ] 'dts_package_name' ]
[ , [ @dts_package_password= ] 'dts_package_password' ]
[ , [ @dts_package_location= ] 'dts_package_location' ]

Arguments
[ @job_id=] job_id
Is the job ID of the Distribution Agent for the push subscription. job_id is varbinary(16), with no default. To find
the Distribution Job ID, run sp_helpsubscription or sp_helppullsubscription.
[ @dts_package_name= ] 'dts_package_name'
Specifies the name of the DTS package. dts_package_name is a sysname, with a default of NULL. For example, to
specify a package named DTSPub_Package, you would specify @dts_package_name = N'DTSPub_Package' .
[ @dts_package_password= ] 'dts_package_password'
Specifies the password on the package. dts_package_password is sysname with a default of NULL, which specifies
that the password property is to be left unchanged.

NOTE
A DTS package must have a password.

[ @dts_package_location= ] 'dts_package_location'
Specifies the package location. dts_package_location is a nvarchar(12), with a default of NULL, which specifies that
the package location is to be left unchanged. The location of the package can be changed to distributor or
subscriber.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changesubscriptiondtsinfo is used for snapshot replication and transactional replication that are push
subscriptions only.
Permissions
Only members of the sysadmin fixed server role, db_owner fixed database role, or the creator of the subscription
can execute sp_changesubscriptiondtsinfo.

See Also
System Stored Procedures (Transact-SQL)
sp_changesubscription (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the properties of a snapshot or transactional push subscription or a pull subscription involved in queued
updating transactional replication. To change properties of all other types of pull subscriptions, use
sp_change_subscription_properties (Transact-SQL). sp_changesubscription is executed at the Publisher on the
publication database.

IMPORTANT
When configuring a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and
job_password, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its
remote Distributor before executing this stored procedure. For more information, see Enable Encrypted Connections to the
Database Engine (SQL Server Configuration Manager).

Transact-SQL Syntax Conventions

Syntax
sp_changesubscription [ @publication = ] 'publication'
, [ @article = ] 'article'
, [ @subscriber = ] 'subscriber'
, [ @destination_db = ] 'destination_db'
, [ @property = ] 'property'
, [ @value = ] 'value'
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication to change. publicationis sysname, with no default
[ @article = ] 'article'
Is the name of the article to change. article is sysname, with no default.
[ @subscriber = ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with no default.
[ @destination_db = ] 'destination_db'
Is the name of the subscription database. destination_db is sysname, with no default.
[ @property=] 'property'
Is the property to change for the given subscription. property is nvarchar(30), and can be one of the values in the
table.
[ @value=] 'value'
Is the new value for the specified property. value is nvarchar(4000), and can be one of the values in the table.
PROPERTY VALUE DESCRIPTION

distrib_job_login Login for the Microsoft Windows


account under which the agent runs.

distrib_job_password Password for the Windows account


under which the agent runs.

subscriber_catalog Catalog to be used when making a


connection to the OLE DB provider.
This property is only valid for non-
Microsoft SQL Server Subscribers.

subscriber_datasource Name of the data source as understood


by the OLE DB provider. This property
is only valid for non- SQL Server
Subscribers.

subscriber_location Location of the database as understood


by the OLE DB provider. This property
is only valid for non- SQL Server
Subscribers.

subscriber_login Login name at the Subscriber.

subscriber_password Strong password for the supplied login.

subscriber_security_mode 1 Use Windows Authentication when


connecting to the Subscriber.

0 Use SQL Server Authentication when


connecting to the Subscriber.

subscriber_provider Unique programmatic identifier


(PROGID) with which the OLE DB
provider for the non- SQL Server data
source is registered. This property is
only valid for non- SQL Server
Subscribers.

subscriber_providerstring OLE DB provider-specific connection


string that identifies the data source.
This property is only valid for non-
SQL Server Subscribers.

subscriptionstreams Is the number of connections allowed


per Distribution Agent to apply batches
of changes in parallel to a Subscriber. A
range of values from 1 to 64 is
supported for SQL Server Publishers.
This property must be 0 for non- SQL
Server Subscribers, Oracle Publishers or
peer-to-peer subscriptions.

subscriber_type 1 ODBC data source server

3 OLE DB provider
PROPERTY VALUE DESCRIPTION

memory_optimized bit Indicates that the subscription supports


memory optimized tables.
memory_optimized is bit, where 1
equals true (the subscription supports
memory optimized tables).

[ @publisher = ] 'publisher'
Specifies a non- SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be specified for a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changesubscription is used in snapshot and transactional replication.
sp_changesubscription can only be used to modify the properties of push subscriptions or pull subscriptions
involved in queued updating transactional replication. To change properties of all other types of pull subscriptions,
use sp_change_subscription_properties (Transact-SQL).
After changing an agent login or password, you must stop and restart the agent before the change takes effect.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_changesubscription.

See Also
sp_addsubscription (Transact-SQL)
sp_dropsubscription (Transact-SQL)
sp_changesubstatus (Transact-SQL)
11/21/2017 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Changes the status of an existing Subscriber. This stored procedure is executed at the Publisher on the publication
database.
Transact-SQL Syntax Conventions

Syntax
sp_changesubstatus [ [ @publication = ] 'publication' ]
[ , [ @article = ] 'article' ]
[ , [ @subscriber = ] 'subscriber' ]
, [ @status = ] 'status'
[ , [ @previous_status = ] 'previous_status' ]
[ , [ @destination_db = ] 'destination_db' ]
[ , [ @frequency_type = ] frequency_type ]
[ , [ @frequency_interval = ] frequency_interval ]
[ , [ @frequency_relative_interval = ] frequency_relative_interval ]
[ , [ @frequency_recurrence_factor = ] frequency_recurrence_factor ]
[ , [ @frequency_subday = ] frequency_subday ]
[ , [ @frequency_subday_interval = ] frequency_subday_interval ]
[ , [ @active_start_time_of_day = ] active_start_time_of_day ]
[ , [ @active_end_time_of_day = ] active_end_time_of_day ]
[ , [ @active_start_date = ] active_start_date ]
[ , [ @active_end_date = ] active_end_date ]
[ , [ @optional_command_line = ] 'optional_command_line' ]
[ , [ @distribution_jobid = ] distribution_jobid ]
[ , [ @from_auto_sync = ] from_auto_sync ]
[ , [ @ignore_distributor = ] ignore_distributor ]
[ , [ @offloadagent= ] remote_agent_activation ]
[ , [ @offloadserver= ] 'remote_agent_server_name' ]
[ , [ @dts_package_name= ] 'dts_package_name' ]
[ , [ @dts_package_password= ] 'dts_package_password' ]
[ , [ @dts_package_location= ] dts_package_location ]
[ , [ @skipobjectactivation = ] skipobjectactivation
[ , [ @distribution_job_name= ] 'distribution_job_name' ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of %. If publication is not specified, all
publications are affected.
[ @article=] 'article'
Is the name of the article. It must be unique to the publication. article is sysname, with a default of %. If article is
not specified, all articles are affected.
[ @subscriber=] 'subscriber'
Is the name of the Subscriber to change the status of. subscriber is sysname, with a default of %. If subscriber is
not specified, status is changed for all Subscribers to the specified article.
[ @status =] 'status'
Is the subscription status in the syssubscriptions table. status is sysname, with no default, and can be one of
these values.

VALUE DESCRIPTION

active Subscriber is synchronized and is receiving data.

inactive Subscriber entry exists without a subscription.

subscribed Subscriber is requesting data, but is not yet synchronized.

[ @previous_status=] 'previous_status'
Is the previous status for the subscription. previous_status is sysname, with a default of NULL. This parameter
allows you to change any subscriptions that currently have that status, thus allowing group functions on a specific
set of subscriptions (for example, setting all active subscriptions back to subscribed).
[ @destination_db=] 'destination_db'
Is the name of the destination database. destination_db is sysname, with a default of %.
[ @frequency_type=] frequency_type
Is the frequency with which to schedule the distribution task. frequency_type is int, with a default of NULL.
[ @frequency_interval=] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of NULL.
[ @frequency_relative_interval=] frequency_relative_interval
Is the date of the distribution task. This parameter is used when frequency_type is set to 32 (monthly relative).
frequency_relative_interval is int, and can be one of these values.

VALUE DESCRIPTION

1 First

2 Second

4 Third

8 Fourth

16 Last

NULL (default)

[ @frequency_recurrence_factor=] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of NULL.
[ @frequency_subday=] frequency_subday
Is how often, in minutes, to reschedule during the defined period. frequency_subday is int, and can be one of these
values.

VALUE DESCRIPTION

1 Once
VALUE DESCRIPTION

2 Second

4 Minute

8 Hour

NULL (default)

[ @frequency_subday_interval=] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of NULL.
[ @active_start_time_of_day=] active_start_time_of_day
Is the time of day when the distribution task is first scheduled, formatted as HHMMSS. active_start_time_of_day is
int, with a default of NULL.
[ @active_end_time_of_day=] active_end_time_of_day
Is the time of day when the distribution task stops being scheduled, formatted as HHMMSS.
active_end_time_of_day is int, with a default of NULL.
[ @active_start_date=] active_start_date
Is the date when the distribution task is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a
default of NULL.
[ @active_end_date=] active_end_date
Is the date when the distribution task stops being scheduled, formatted as YYYYMMDD. active_end_date is int,
with a default of NULL.
[ @optional_command_line=] 'optional_command_line'
Is an optional command prompt. optional_command_line is nvarchar(4000), with a default of NULL.
[ @distribution_jobid=] distribution_jobid
Is the job ID of the Distribution Agent at the Distributor for the subscription when changing the subscription status
from inactive to active. In other cases, it is not defined. If more than one Distribution Agent is involved in a single
call to this stored procedure, the result is not defined. distribution_jobid is binary(16), with a default of NULL.
[ @from_auto_sync=] from_auto_sync
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @ignore_distributor=] ignore_distributor
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @offloadagent= ] remote_agent_activation

NOTE
Remote agent activation has been deprecated and is no longer supported. This parameter is supported only to maintain
backward compatibility of scripts. Setting remote_agent_activation to a value other than 0 generates an error.

[ @offloadserver= ] 'remote_agent_server_name'
NOTE
Remote agent activation has been deprecated and is no longer supported. This parameter is supported only to maintain
backward compatibility of scripts. Setting remote_agent_server_name to any non-NULL value generates an error.

[ @dts_package_name= ] 'dts_package_name'
Specifies the name of the Data Transformation Services (DTS) package. dts_package_name is a sysname, with a
default of NULL. For example, for a package named DTSPub_Package you would specify
@dts_package_name = N'DTSPub_Package' .

[ @dts_package_password= ] 'dts_package_password'
Specifies the password on the package. dts_package_password is sysname with a default of NULL, which specifies
that the password property is to be left unchanged.

NOTE
A DTS package must have a password.

[ @dts_package_location= ] dts_package_location
Specifies the package location. dts_package_location is an int, with a default of 0. If 0, the package location is at
the Distributor. If 1, the package location is at the Subscriber. The location of the package can be distributor or
subscriber.
[ @skipobjectactivation= ] skipobjectactivation
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @distribution_job_name= ] 'distribution_job_name'
Is the name of the distribution job. distribution_job_name is sysname, with a default of NULL.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when changing article properties on a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_changesubstatus is used in snapshot replication and transactional replication.
sp_changesubstatus changes the status of the Subscriber in the syssubscriptions table with the changed status.
If required, it updates the article status in the sysarticles table to indicate active or inactive. If required, it sets the
replication flag on or off in the sysobjects table for the replicated table.

Permissions
Only members of the sysadmin fixed server role, db_owner fixed database role, or the creator of the subscription
can execute sp_changesubstatus.
See Also
sp_addsubscription (Transact-SQL)
sp_dropsubscription (Transact-SQL)
sp_helpdistributor (Transact-SQL)
sp_helpsubscription (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_change_subscription_properties (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates information for pull subscriptions. This stored procedure is executed at the Subscriber on the
subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_change_subscription_properties [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
, [ @property = ] 'property'
, [ @value = ] 'value'
[ , [ @publication_type = ] publication_type ]

Arguments
[ @publisher=] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @property=] 'property'
Is the property to be changed. property is sysname.
[ @value=] 'value'
Is the new value of the property. value is nvarchar(1000), with no default.
[ @publication_type = ] publication_type
Specifies the replication type of the publication. publication_type is int, and can be one of these values.

VALUE PUBLICATION TYPE

0 Transactional

1 Snapshot

2 Merge

NULL (default) Replication determines the publication type. Because the


stored procedure must look through multiple tables, this
option is slower than when the exact publication type is
provided.
This table describes the properties of articles and the values for those properties.

PROPERTY VALUE DESCRIPTION

alt_snapshot_folder Specifies the location of the alternate


folder for the snapshot. If set to NULL,
the snapshot files are picked up from
the default location specified by the
Publisher.

distrib_job_login Login for the Microsoft Windows


account under which the agent runs.

distrib_job_password Password for the Windows account


under which the agent runs.

distributor_login Distributor login.

distributor_password Distributor password.

distributor_security_mode 1 Use Windows Authentication when


connecting to the Distributor.

0 Use SQL Server Authentication when


connecting to the Distributor.

dts_package_name Specifies the name of the SQL Server


2000 Data Transformation Services
(DTS) package. This value can be
specified only if the publication is
transactional or snapshot.

dts_package_password Specifies the password on the package.


dts_package_password is sysname
with a default of NULL, which specifies
that the password property is to be left
unchanged.

Note: A DTS package must have a


password.

This value can be specified only if the


publication is transactional or snapshot.

dts_package_location Location where the DTS package is


stored. This value can be specified only
if the publication is transactional or
snapshot.

dynamic_snapshot_location Specifies the path to the folder where


the snapshot files are saved. This value
can be specified only if the publication
is a merge publication.

ftp_address For backward compatibility only.

ftp_login For backward compatibility only.


PROPERTY VALUE DESCRIPTION

ftp_password For backward compatibility only.

ftp_port For backward compatibility only.

hostname Host name used when connecting to


the Publisher.

internet_login Login that the Merge Agent uses when


connecting to the Web server that is
hosting Web synchronization using
Basic Authentication.

internet_password Password that the Merge Agent uses


when connecting to the Web server
that is hosting Web synchronization
using Basic Authentication.

internet_security_mode 1 Use Windows Integrated


Authentication for Web
synchronization. We recommend using
Basic Authentication with Web
synchronization. For more information,
see Configure Web Synchronization.

0 Use Basic Authentication for Web


synchronization.

Note: Web synchronization requires an


SSL connection to the Web server.

internet_timeout Length of time, in seconds, before a


Web synchronization request expires.

internet_url URL that represents the location of the


replication listener for Web
synchronization.

merge_job_login Login for the Windows account under


which the agent runs.

merge_job_password Password for the Windows account


under which the agent runs.

publisher_login Publisher login. Changing


publisher_login is only supported for
subscriptions to merge publications.

publisher_password Publisher password. Changing


publisher_password is only supported
for subscriptions to merge publications.
PROPERTY VALUE DESCRIPTION

publisher_security_mode 1 Use Windows Authentication when


connecting to the Publisher. Changing
publisher_security_mode is only
supported for subscriptions to merge
publications.

0 Use SQL Server Authentication when


connecting to the Publisher.

use_ftp true Use FTP instead of the regular protocol


to retrieve snapshots.

false Use the regular protocol to retrieve


snapshots.

use_web_sync true Enable Web synchronization.

false Disable Web synchronization.

working_directory Name of the working directory used to


temporarily store data and schema files
for the publication when File Transfer
Protocol (FTP) is used to transfer
snapshot files.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_change_subscription_properties is used in all types of replication.
sp_change_subscription_properties is used for pull subscriptions.
For Oracle Publishers, the value of publisher_db is ignored since Oracle only allows one database per instance of
the server.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_change_subscription_properties.

See Also
View and Modify Pull Subscription Properties
sp_addmergepullsubscription (Transact-SQL)
sp_addmergepullsubscription_agent (Transact-SQL)
sp_addpullsubscription (Transact-SQL)
sp_addpullsubscription_agent (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_check_dynamic_filters (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Displays information on parameterized row filter properties for a publication, in particular the functions used to
generate a filtered data partition for a publication and whether the publication qualifies for using precomputed
partitions. This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_check_dynamic_filters [ @publication = ] 'publication'

Arguments
[ @publication= ] 'publication'
Is the name of the publication. publication is sysname, with no default.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

can_use_partition_groups bit Is if the publication qualifies for using


precomputed partitions; where 1 means
that precomputed partitions can be
used, and 0 means that they cannot be
used.

has_dynamic_filters bit Is if at least one parameterized row filter


has been defined in the publication;
where 1 means that one or more
parameterized row filters exist, and 0
means that no dynamic filters exist.

dynamic_filters_function_list nvarchar(500) List of functions used to filter articles in


a publication, where each function is
separated by a semi-colon.

validate_subscriber_info nvarchar(500) List of functions used to filter articles in


a publication, where each function is
separated by a plus sign (+).

uses_host_name bit If the HOST_NAME() function is used in


parameterized row filters, where 1
means that this function is used for
dynamic filtering.
COLUMN NAME DATA TYPE DESCRIPTION

uses_suser_sname bit If the SUSER_SNAME() function is used


in parameterized row filters, where 1
means that this function is used for
dynamic filtering.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_check_dynamic_filters is used in merge replication.
If a publication has been defined to use precomputed partitions, sp_check_dynamic_filters checks for any
violations of the restrictions of precomputed partitions. If any are found, an error is returned. For more information,
see Optimize Parameterized Filter Performance with Precomputed Partitions.
If a publication has been defined as having parameterized row filters, but no parameterized row filters are found,
an error is returned.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_check_dynamic_filters.

See Also
Manage Partitions for a Merge Publication with Parameterized Filters
sp_check_join_filter (Transact-SQL)
sp_check_subset_filter (Transact-SQL)
sp_check_for_sync_trigger (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Determines whether a user-defined trigger or stored procedure is being called in the context of a replication trigger
that is used for immediate updating subscriptions. This stored procedure is executed at the Publisher on the
publication database or at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_check_for_sync_trigger [ @tabid = ] 'tabid'
[ , [ @trigger_op = ] 'trigger_output_parameters' OUTPUT ]
[ , [ @fonpublisher = ] fonpublisher ]

Arguments
[@tabid = ] 'tabid'
Is the object ID of the table being checked for immediate updating triggers. tabid is int with no default.
[@trigger_op = ] 'trigger_output_parameters' OUTPUT
Specifies if the output parameter is to return the type of trigger it is being called from. trigger_output_parameters
is char(10) and can be one of these values.

VALUE DESCRIPTION

Ins INSERT trigger

Upd UPDATE trigger

Del DELETE trigger

NULL (default)

[ @fonpublisher = ] fonpublisher
Specifies the location where the stored procedure is executed. fonpublisher is bit, with a default value of 0. If 0, the
execution is at the Subscriber, and if 1, the execution is at the Publisher.

Return Code Values


0 indicates that the stored procedure is not being called within the context of an immediate-updating trigger. 1
indicates that it is being called within the context of an immediate-updating trigger and is the type of trigger being
returned in @trigger_op.

Remarks
sp_check_for_sync_trigger is used in snapshot replication and transactional replication.
sp_check_for_sync_trigger is used to coordinate between replication and user-defined triggers. This stored
procedure determines if it is being called within the context of a replication trigger. For example, you can call the
procedure sp_check_for_sync_trigger in the body of a user-defined trigger. If sp_check_for_sync_trigger
returns 0, the user-defined trigger continues processing. If sp_check_for_sync_trigger returns 1, the user-defined
trigger exits. This ensures that the user-defined trigger does not fire when the replication trigger updates the table.

Example
The following example shows code that could be used in a trigger on a Subscriber table.

DECLARE @retcode int, @trigger_op char(10), @table_id int


SELECT @table_id = object_id('tablename')
EXEC @retcode = sp_check_for_sync_trigger @table_id, @trigger_op OUTPUT
IF @retcode = 1
RETURN

Example
The code can also be added to a trigger on a table at the Publisher; the code is similar, but the call to
sp_check_for_sync_trigger includes an additional parameter.

DECLARE @retcode int, @trigger_op char(10), @table_id int, @fonpublisher int


SELECT @table_id = object_id('tablename')
SELECT @fonpublisher = 1
EXEC @retcode = sp_check_for_sync_trigger @table_id, @trigger_op OUTPUT, @fonpublisher
IF @retcode = 1
RETURN

Permissions
sp_check_for_sync_trigger stored procedure can be executed by any user with SELECT permissions in the
sys.objects system view.

See Also
Updatable Subscriptions for Transactional Replication
sp_check_join_filter (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Is used to verify a join filter between two tables to determine if the join filter clause is valid. This stored procedure
also returns information about the supplied join filter, including if it can be used with precomputed partitions for
the given table. This stored procedure is executed at the Publisher on the publication. For more information, see
Optimize Parameterized Filter Performance with Precomputed Partitions.
Transact-SQL Syntax Conventions

Syntax
sp_check_join_filter [ @filtered_table = ] 'filtered_table'
, [@join_table = ] 'join_table'
, [ @join_filterclause = ] 'join_filterclause'

Arguments
[ @filtered_table= ] 'filtered_table'
Is the name of a filtered table. filtered_table is nvarchar(400), with no default.
[ @join_table= ] 'join_table'
Is the name of a table being joined to filtered_table. join_table is nvarchar(400), with no default.
[ @join_filterclause = ] 'join_filterclause'
Is the join filter clause being tested. join_filterclause is nvarchar(1000), with no default.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

can_use_partition_groups bit Is if the publication qualifies for


precomputed partitions; where 1 means
that precomupted partitions can be
used, and 0 means that they cannot be
used.

has_dynamic_filters bit Is if the supplied filter clause includes at


least one parameterized filtering
function; where 1 means that a
parameterized filtering function is used,
and 0 means that such a function is not
used.

dynamic_filters_function_list nvarchar(500) List of the functions in the filter clause


that define a parameterized filter for an
article, where each function is separated
by a semi-colon.
COLUMN NAME DATA TYPE DESCRIPTION

uses_host_name bit If the HOST_NAME() function is used in


the filter clause, where 1 means that
this function is present.

uses_suser_sname bit If the SUSER_SNAME() function is used


in the filter clause, where 1 means that
this function is present.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_check_join_filter is used in merge replication.
sp_check_join_filter can be executed against any related tables even if they are not published. This stored
procedure can be used to verify a join filter clause before defining a join filter between two articles.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_check_join_filter.

See Also
Replication Stored Procedures (Transact-SQL)
sp_check_subset_filter (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Is used to check a filter clause against any table to determine if the filter clause is valid for the table. This stored
procedure returns information about the supplied filter, including if the filter qualifies for use with precomputed
partitions. This stored procedure is executed at the Publisher on the database containing the publication.
Transact-SQL Syntax Conventions

Syntax
sp_check_subset_filter [ @filtered_table = ] 'filtered_table'
, [ @subset_filterclause = ] 'subset_filterclause'
[ , [ @has_dynamic_filters = ] has_dynamic_filters OUTPUT ]

Arguments
[ @filtered_table= ] 'filtered_table'
Is the name of a filtered table. filtered_table is nvarchar(400), with no default.
[ @subset_filterclause = ] 'subset_filterclause'
Is the filter clause being tested. subset_filterclause is nvarchar(1000), with no default.
[ @has_dynamic_filters= ] has_dynamic_filters
Is if the filter clause is a parameterized row filter. has_dynamic_filters is bit, with a default of NULL and is an output
parameter. Returns a value of 1 when the filter clause is a parameterized row filter.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

can_use_partition_groups bit Is if the publication qualifies for using


precomputed partitions; where 1 means
that precomputed partitions can be
used, and 0 means that they cannot be
used.

has_dynamic_filters bit Is if the supplied filter clause includes at


least one parameterized row filter;
where 1 means that a parameterized
row filter is used, and 0 means that
such a function is not used.

dynamic_filters_function_list nvarchar(500) List of the functions in the filter clause


that dynamically filter an article, where
each function is separated by a semi-
colon.
COLUMN NAME DATA TYPE DESCRIPTION

uses_host_name bit If the HOST_NAME() function is used in


the filter clause, where 1 means that
this function is present.

uses_suser_sname bit If the SUSER_SNAME() function is used


in the filter clause, where 1 means that
this function is present.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_check_subset_filter is used in merge replication.
sp_check_subset_filter can be executed against any table even if the table is not published. This stored procedure
can be used to verify a filter clause before defining a filtered article.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_check_subset_filter.

See Also
Optimize Parameterized Filter Performance with Precomputed Partitions
sp_configure_peerconflictdetection (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Configures conflict detection for a publication that is involved in a peer-to-peer transactional replication topology.
For more information, see Conflict Detection in Peer-to-Peer Replication. This stored procedure is executed at the
Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_configure_peerconflictdetection [ @publication = ] 'publication'
[ , [ @action = ] 'action']
[ , [ @originator_id = ] originator_id ]
[ , [ @conflict_retention = ] conflict_retention ]
[ , [ @continue_onconflict = ] 'continue_onconflict']
[ , [ @local = ] 'local']
[ , [ @timeout = ] timeout ]

Arguments
[ @publication=] 'publication'
Is the name of the publication for which to configure conflict detection. publication is sysname, with no default.
[ @action= ] 'action'
Specifies whether to enable or disable conflict detection for a publication. action is nvarchar(5), and can be one of
the following values.

VALUE DESCRIPTION

enable Enables conflict detection for a publication.

disable Disables conflict detection for a publication.

NULL (default)

[ @originator_id= ] originator_id
Specifies an ID for a node in a peer-to-peer topology. originator_id is int, with a default of NULL. This ID is used for
conflict detection if action is set to enable. Specify a positive, nonzero ID that has never been used in the topology.
For a list of IDs that have already been used, query the Mspeer_originatorid_history system table.
[ @conflict_retention= ] conflict_retention
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @continue_onconflict= ] 'continue_onconflict' ]
Determines whether the Distribution Agent continues to process changes after a conflict is detected.
continue_onconflict is nvarchar(5) with a default value of FALSE.
Cau t i on
We recommend that you use the default value of FALSE. When this option is set to TRUE, the Distribution Agent
tries to converge data in the topology by applying the conflicting row from the node that has the highest originator
ID. This method does not guarantee convergence. You should make sure that the topology is consistent after a
conflict is detected. For more information, see "Handling Conflicts" in Conflict Detection in Peer-to-Peer Replication.
[ @local= ] 'local'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @timeout= ] timeout
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_configure_peerconflictdetection is used in peer-to-peer transactional replication. To use conflict detection, all
nodes must be running SQL Server 2008 or later versions; and detection must be enabled for all nodes.

Permissions
Requires membership in the sysadmin fixed server role or db_owner fixed database role.

See Also
Conflict Detection in Peer-to-Peer Replication
Peer-to-Peer Transactional Replication
Replication Stored Procedures (Transact-SQL)
sp_copymergesnapshot (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Copies the snapshot folder of the specified publication to the folder listed in the @destination_folder. This stored
procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_copymergesnapshot [ @publication = ] 'publication', [ @destination_folder = ] 'destination_folder'

Arguments
[ @publication=] 'publication'
Is the name of the publication whose snapshot contents are to be copied. publication is sysname, with no default.
[ @destination_folder=] 'destination_folder'
Is the name of the folder where the contents of the publication snapshot is to be copied. destination_folderis
nvarchar(255), with no default. The destination_folder can be an alternate location such as on another server, on a
network drive, or on removable media (such as CD-ROMs or removable disks).

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_copymergesnapshot is used in merge replication. Subscribers running Microsoft SQL Server version 7.0 and
earlier cannot use the alternate snapshot location.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_copymergesnapshot.

See Also
Alternate Snapshot Folder Locations
System Stored Procedures (Transact-SQL)
sp_copysnapshot (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Copies the snapshot folder of the specified publication to the folder listed in the @destination_folder. This stored
procedure is executed at the Publisher on the publication database. This stored procedure is useful for copying a
snapshot to removable media, such as CD-ROM.
Transact-SQL Syntax Conventions

Syntax
sp_copysnapshot [ @publication = ] 'publication', [ @destination_folder = ] 'destination_folder' ]
[ , [ @subscriber = ] 'subscriber' ]
[ , [ @subscriber_db = ] 'subscriber_db' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication whose snapshot contents are to be copied. publication is sysname, with no default.
[ @destination_folder=] 'destination_folder'
Is the name of the folder where the contents of the publication snapshot are to be copied. destination_folderis
nvarchar(255), with no default. The destination_folder can be an alternate location such as on another server, on a
network drive, or on removable media (such as CD-ROMs or removable disks).
[ @subscriber=] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[ @subscriber_db=] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_copysnapshot is used in all types of replication. Subscribers running Microsoft SQL Server version 7.0 and
earlier cannot use the alternate snapshot location.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_copysnapshot.

See Also
Alternate Snapshot Folder Locations
System Stored Procedures (Transact-SQL)
sp_copysubscription (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse

IMPORTANT
The attachable subscriptions feature is deprecated and will be removed in a future release. This feature should not be used in
new development work. For merge publications that are partitioned using parameterized filters, we recommend using the
new features of partitioned snapshots, which simplify the initialization of a large number of subscriptions. For more
information, see Snapshots for Merge Publications with Parameterized Filters. For publications that are not partitioned, you
can initialize a subscription with a backup. For more information, see Initialize a Transactional Subscription Without a
Snapshot.

Copies a subscription database that has pull subscriptions, but no push subscriptions. Only single file databases
can be copied. This stored procedure is executed at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_copysubscription [ @filename = ] 'file_name'
[ , [ @temp_dir = ] 'temp_dir' ]
[ , [ @overwrite_existing_file = ] overwrite_existing_file]

Arguments
[ @filename =] 'file_name'
Is the string that specifies the complete path, including file name, to which a copy of the data file (.mdf) is saved. file
name is nvarchar(260), with no default.
[ @temp_dir=] 'temp_dir'
Is the name of the directory that contains the temp files. temp_dir is nvarchar(260), with a default of NULL. If
NULL, the Microsoft SQL Server default data directory will be used. The directory should have enough space to
hold a file the size of all the subscriber database files combined.
[ @overwrite_existing_file=] 'overwrite_existing_file'
Is an optional Boolean flag that specifies whether or not to overwrite an existing file of the same name specified in
@filename. overwrite_existing_fileis bit, with a default of 0. If 1, it overwrites the file specified by @filename, if it
exists. If 0, the stored procedure fails if the file exists, and the file is not overwritten.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_copysubscription is used in all types of replication to copy a subscription database to a file as an alternative to
applying a snapshot at the Subscriber. The database must be configured to support only pull subscriptions. Users
having appropriate permissions can make copies of the subscription database and then e-mail, copy, or transport
the subscription file (.msf) to another Subscriber, where it can then be attached as a subscription.
The size of the subscription database being copied must be less than 2 gigabytes (GB).
sp_copysubscription is only supported for databases with client subscriptions and cannot be executed when the
database has server subscriptions.

Permissions
Only members of the sysadmin fixed server role can execute sp_copysubscription.

See Also
Alternate Snapshot Folder Locations
System Stored Procedures (Transact-SQL)
sp_deletemergeconflictrow (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Deletes rows from a conflict table or the MSmerge_conflicts_info (Transact-SQL) table. This stored procedure is
executed at the computer where the conflict table is stored, in any database.
Transact-SQL Syntax Conventions

Syntax
sp_deletemergeconflictrow [ [ @conflict_table = ] 'conflict_table' ]
[ , [ @source_object = ] 'source_object' ]
{ , [ @rowguid = ] 'rowguid'
, [ @origin_datasource = ] 'origin_datasource' ] }
[ , [ @drop_table_if_empty = ] 'drop_table_if_empty' ]

Arguments
[ @conflict_table=] 'conflict_table'
Is the name of the conflict table. conflict_table is sysname, with a default of %. If the conflict_table is specified as
NULL or %, the conflict is assumed to be a delete conflict and the row matching rowguid and origin_datasource
and source_object is deleted from the MSmerge_conflicts_info (Transact-SQL) table.
[ @source_object=] 'source_object'
Is the name of the source table. source_object is nvarchar(386), with a default of NULL.
[ @rowguid =] 'rowguid'
Is the row identifier for the delete conflict. rowguid is uniqueidentifier, with no default.
[ @origin_datasource=] 'origin_datasource'
Is the origin of the conflict. origin_datasource is varchar(255), with no default.
[ @drop_table_if_empty=] 'drop_table_if_empty'
Is a flag indicating that the conflict_table is to be dropped if is empty. drop_table_if_empty is varchar(10), with a
default of FALSE.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_deletemergeconflictrow is used in merge replication.
MSmerge_conflicts_info (Transact-SQL) table is a system table and is not deleted from the database, even if it is
empty.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_deletemergeconflictrow.

See Also
System Stored Procedures (Transact-SQL)
sp_deletepeerrequesthistory (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Deletes history related to a publication status request, which includes the request history (MSpeer_request
(Transact-SQL)) as well as the response history (MSpeer_response (Transact-SQL)).This stored procedure is
executed on the publication database at a Publisher participating in a Peer-to-Peer replication topology. For more
information, see Peer-to-Peer Transactional Replication.
Transact-SQL Syntax Conventions

Syntax
sp_deletepeerrequesthistory [ @publication = ] 'publication'
[ , [ @request_id = ] request_id ]
[ , [ @cutoff_date = ] cutoff_date ]

Arguments
[ @publication= ] 'publication'
Name of the publication for which the status request was made. publication is sysname, with no default.
[ @request_id= ] request_id
Specifies an individual status request so that all responses to this request will be deleted. request_id is int, with a
default value of NULL.
[ @cutoff_date= ] cutoff_date
Specifies a cutoff date, before which all earlier response records are deleted. cutoff_date is datetime, with a
default value of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_deletepeerrequesthistory is used in a Peer-to-Peer transactional replication topology. For more information,
see Peer-to-Peer Transactional Replication.
When executing sp_deletepeerrequesthistory, either request_id or cutoff_date must be specified.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_deletepeerrequesthistory.

See Also
sp_helppeerrequests (Transact-SQL)
sp_helppeerresponses (Transact-SQL)
sp_requestpeerresponse (Transact-SQL)
sp_deletetracertokenhistory (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes tracer token records from the MStracer_tokens (Transact-SQL) and MStracer_history (Transact-SQL)
system tables. This stored procedure is executed at the Publisher on the publication database or at the Distributor
on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_deletetracertokenhistory [ @publication = ] 'publication'
[ , [ @tracer_id = ] tracer_id ]
[ , [ @cutoff_date = ] cutoff_date ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @publisher_db = ] 'publisher_db' ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication in which the tracer token was inserted. publication is sysname, with no default.
[ @tracer_id= ] tracer_id
Is the ID of the tracer token to delete. tracer_id is int, with a default value of NULL. If null, then all tracer tokens
belonging to the publication are deleted.
[ @cutoff_date= ] cutoff_date
Specifies a cutoff date such that all tracer tokens inserted into the publication before that date are removed.
cutoff_date is datetime, with a default value of NULL.
[ @publisher= ] 'publisher'
The name of the Publisher. publisher is sysname, with a default of NULL.

NOTE
This parameter should only be specified for non- Microsoft SQL Server Publishers.

[ @publisher_db= ] 'publisher_db'
The name of the publication database. publisher_db is sysname, with a default value of NULL. This parameter is
ignored if the stored procedure is executed at the Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_deletetracertokenhistory is used in transactional replication.
When executing sp_deletetracertokenhistory, you can only specify one of tracer_id or cutoff_date. An error
occurs when you specify both parameters.
If you do not execute sp_deletetracertokenhistory to remove tracer token metadata, the information will be
removed when the regularly scheduled history cleanup occurs.
Tracer token IDs can be determined by executing sp_helptracertokens (Transact-SQL) or by querying the
MStracer_tokens (Transact-SQL) system table.

Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role in the publication database, or
db_owner fixed database or replmonitor roles in the distribution database can execute
sp_deletetracertokenhistory.

See Also
Measure Latency and Validate Connections for Transactional Replication
sp_helptracertokenhistory (Transact-SQL)
sp_drop_agent_parameter (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops one or all parameters from a profile in the MSagent_parameters table. This stored procedure is executed
at the Distributor where the agent is running, on any database.
Transact-SQL Syntax Conventions

Syntax
sp_drop_agent_parameter [ @profile_id = ] profile_id
[ , [ @parameter_name = ] 'parameter_name' ]

Arguments
[ @profile_id=] profile_id
Is the ID of the profile for which a parameter is to be dropped. profile_id is int, with no default.
[ @parameter_name=] 'parameter_name'
Is the name of the parameter to be dropped. parameter_name is sysname, with a default of %. If %, all
parameters for the specified profile are dropped.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_drop_agent_parameter is used in all types of replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_drop_agent_parameter.

See Also
sp_add_agent_parameter (Transact-SQL)
sp_help_agent_parameter (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_drop_agent_profile (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops a profile from the MSagent_profiles table. This stored procedure is executed at the Distributor on any
database.
Transact-SQL Syntax Conventions

Syntax
sp_drop_agent_profile [ @profile_id = ] profile_id

Arguments
[ @profile_id=] profile_id
Is the ID of the profile to be dropped. profile_id is int, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_drop_agent_profile is used in all types of replication.
The parameters of the given profile are also dropped from the MSagent_parameters table.

Permissions
Only members of the sysadmin fixed server role can execute sp_drop_agent_profile.

See Also
sp_add_agent_profile (Transact-SQL)
sp_change_agent_profile (Transact-SQL)
sp_help_agent_profile (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_dropanonymousagent (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Drops an anonymous agent for replication monitoring at the distributor from the Publisher. This stored procedure
is executed at the Publisher on any database.
Transact-SQL Syntax Conventions

Syntax
sp_dropanonymousagent [ @subid= ] sub_id , [ @type= ] type

Arguments
[ @subid=] sub_id
Is the global identifier for an anonymous subscription. sub_id is uniqueidentifier, with no default. This identifier
can be retrieved at the Subscriber using sp_helppullsubscription. The value in the subid field of the returned
result set is this global identifier.
[ @type=] type
Is the type of subscription. type is int, with no default. Valid values are 1 or 2. Specify 1, if snapshot replication or
transactional replication using the Distribution Agent. Specify 2, if merge replication using the Merge Agent.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropanonymousagent is used in all types of replication.
This stored procedure is used to drop anonymous subscription agents only and cannot be used to drop well-
known subscriptions.

Permissions
Only members of the db_owner fixed database role in the distribution database can execute
sp_dropanonymousagent.

See Also
Replication Stored Procedures (Transact-SQL)
sp_droparticle (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops an article from a snapshot or transactional publication. An article cannot be removed if one or more
subscriptions to it exist. This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_droparticle [ @publication= ] 'publication'
, [ @article= ] 'article'
[ , [ @ignore_distributor = ] ignore_distributor ]
[ , [ @force_invalidate_snapshot= ] force_invalidate_snapshot ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @from_drop_publication = ] from_drop_publication ]

Arguments
[ @publication=] 'publication'
Is the name of the publication that contains the article to be dropped. publication is sysname, with no default.
[ @article=] 'article'
Is the name of the article to be dropped. article is sysname, with no default.
[ @ignore_distributor =] ignore_distributor
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Acknowledges that the action taken by this stored procedure may invalidate an existing snapshot.
force_invalidate_snapshot is a bit, with a default of 0.
0 specifies that changes to the article do not cause the snapshot to be invalid. If the stored procedure detects that
the change does require a new snapshot, an error occurs and no changes are made.
1 specifies that changes to the article may cause the snapshot to be invalid, and if there are existing subscriptions
that would require a new snapshot, gives permission for the existing snapshot to be marked as obsolete and a
new snapshot generated.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when changing article properties on a SQL Server Publisher.

[ @from_drop_publication= ] from_drop_publication
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
Return Code Values
0 (success) or 1 (failure)

Remarks
sp_droparticle is used in snapshot and transactional replication.
For horizontally filtered articles, sp_droparticle checks the type column of the article in the sysarticles (Transact-
SQL) table to determine whether a view or filter should also be dropped. If a view or filter was autogenerated, it is
dropped with the article. If it was manually created, it is not dropped.
Executing sp_droparticle to drop an article from a publication does not remove the object from the publication
database or the corresponding object from the subscription database. Use DROP <object> to manually remove
these objects if necessary.

Example
DECLARE @publication AS sysname;
DECLARE @article AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @article = N'Product';

-- Drop the transactional article.


USE [AdventureWorks2012]
EXEC sp_droparticle
@publication = @publication,
@article = @article,
@force_invalidate_snapshot = 1;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_droparticle.

See Also
Delete an Article
Add Articles to and Drop Articles from Existing Publications
sp_addarticle (Transact-SQL)
sp_changearticle (Transact-SQL)
sp_helparticle (Transact-SQL)
sp_helparticlecolumns (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_dropdistpublisher (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops a distribution Publisher. This stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_dropdistpublisher [ @publisher = ] 'publisher'
[ , [ @no_checks = ] no_checks ]
[ , [ @ignore_distributor = ] ignore_distributor ]

Arguments
[ @publisher= ] 'publisher'
Is the Publisher to drop. publisher is sysname, with no default.
[ @no_checks= ] no_checks
Specifies whether sp_dropdistpublisher checks that the Publisher has uninstalled the server as the Distributor.
no_checks is bit, with a default of 0.
If 0, replication verifies that the remote Publisher has uninstalled the local server as the Distributor. If the Publisher
is local, replication verifies that there are no publication or distribution objects remaining on the local server.
If 1, all the replication objects associated with the distribution Publisher are dropped even if a remote Publisher
cannot be reached. After doing this, the remote Publisher must uninstall replication using sp_dropdistributor with
@ignore_distributor = 1.
[ @ignore_distributor= ] ignore_distributor
Specifies whether distribution objects are left at the Distributor when the Publisher is removed. ignore_distributor
is bit and can be one of these values:
1 = distribution objects belonging to the publisher remain at the Distributor.
0 = distribution objects for the publisher are cleaned-up at the Distributor.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropdistpublisher is used in all types of replication.
When dropping an Oracle Publisher, if unable to drop the Publisher sp_dropdistpublisher returns an error and
the Distributor objects for the Publisher are removed.
Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Disable publishing and distribution.


DECLARE @distributionDB AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB as sysname;
SET @distributionDB = N'distribution';
SET @publisher = $(DistPubServer);
SET @publicationDB = N'AdventureWorks2012';

-- Disable the publication database.


USE [AdventureWorks2012]
EXEC sp_removedbreplication @publicationDB;

-- Remove the registration of the local Publisher at the Distributor.


USE master
EXEC sp_dropdistpublisher @publisher;

-- Delete the distribution database.


EXEC sp_dropdistributiondb @distributionDB;

-- Remove the local server as a Distributor.


EXEC sp_dropdistributor;
GO

Permissions
Only members of the sysadmin fixed server role can execute sp_dropdistpublisher.

See Also
Disable Publishing and Distribution
sp_adddistpublisher (Transact-SQL)
sp_changedistpublisher (Transact-SQL)
sp_helpdistpublisher (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_dropdistributiondb (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops a distribution database. Drops the physical files used by the database if they are not used by another
database. This stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_dropdistributiondb [ @database= ] 'database'

Arguments
[ @database=] 'database'
Is the database to drop. database is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropdistributiondb is used in all types of replication.
This stored procedure must be executed before dropping the Distributor by executing sp_dropdistributor.
sp_dropdistributiondb also removes a Queue Reader Agent job for the distribution database, if one exists.
To disable distribution, the distribution database must be online. If a database snapshot exists for the distribution
database, it must be dropped before disabling distribution. A database snapshot is a read-only offline copy of a
database, and is not related to a replication snapshot. For more information, see Database Snapshots (SQL Server).

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Disable publishing and distribution.


DECLARE @distributionDB AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB as sysname;
SET @distributionDB = N'distribution';
SET @publisher = $(DistPubServer);
SET @publicationDB = N'AdventureWorks2012';

-- Disable the publication database.


USE [AdventureWorks2012]
EXEC sp_removedbreplication @publicationDB;

-- Remove the registration of the local Publisher at the Distributor.


USE master
EXEC sp_dropdistpublisher @publisher;

-- Delete the distribution database.


EXEC sp_dropdistributiondb @distributionDB;

-- Remove the local server as a Distributor.


EXEC sp_dropdistributor;
GO

Permissions
Only members of the sysadmin fixed server role can execute sp_dropdistributiondb.

See Also
Disable Publishing and Distribution
sp_adddistributiondb (Transact-SQL)
sp_changedistributiondb (Transact-SQL)
sp_helpdistributiondb (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_dropdistributor (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Uninstalls the Distributor. This stored procedure is executed at the Distributor on any database except the
distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_dropdistributor [ [ @no_checks= ] no_checks ]
[ , [ @ignore_distributor= ] ignore_distributor ]

Arguments
[ @no_checks=] no_checks
Indicates whether to check for dependent objects before dropping the Distributor. no_checks is bit, with a default
of 0.
If 0, sp_dropdistributor checks to make sure that all publishing and distribution objects in addition to the
Distributor have been dropped.
If 1, sp_dropdistributor drops all the publishing and distribution objects prior to uninstalling the distributor.
[ @ignore_distributor=] ignore_distributor
Indicates whether this stored procedure is executed without connecting to the Distributor. ignore_distributor is bit,
with a default of 0.
If 0, sp_dropdistributor connects to the Distributor and removes all replication objects. If sp_dropdistributor is
unable to connect to the Distributor, the stored procedure fails.
If 1, no connection is made to the Distributor and the replication objects are not removed. This is used if the
Distributor is being uninstalled or is permanently offline. The objects for this Publisher at the Distributor are not
removed until the Distributor is reinstalled at some future time.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropdistributor is used in all types of replication.
If other Publisher or distribution objects exist on the server, sp_dropdistributor fails unless @no_checks is set to
1.
This stored procedure must be executed after dropping the distribution database by executing
sp_dropdistributiondb.
Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Disable publishing and distribution.


DECLARE @distributionDB AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB as sysname;
SET @distributionDB = N'distribution';
SET @publisher = $(DistPubServer);
SET @publicationDB = N'AdventureWorks2012';

-- Disable the publication database.


USE [AdventureWorks2012]
EXEC sp_removedbreplication @publicationDB;

-- Remove the registration of the local Publisher at the Distributor.


USE master
EXEC sp_dropdistpublisher @publisher;

-- Delete the distribution database.


EXEC sp_dropdistributiondb @distributionDB;

-- Remove the local server as a Distributor.


EXEC sp_dropdistributor;
GO

Permissions
Only members of the sysadmin fixed server role can execute sp_dropdistributor.

See Also
Disable Publishing and Distribution
sp_adddistributor (Transact-SQL)
sp_changedistributor_property (Transact-SQL)
sp_helpdistributor (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_dropdynamicsnapshot_job (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a filtered data snapshot job for a publication with parameterized row filters. This stored procedure is
executed at the Publisher on the publication database. When the job is deleted, all of the related data is deleted
from the MSdynamicsnapshotjobs system table.
Transact-SQL Syntax Conventions

Syntax
sp_dropdynamicsnapshot_job [ @publication = ] 'publication'
[ , [ @dynamic_snapshot_jobname = ] 'dynamic_snapshot_jobname' ]
[ , [ @dynamic_snapshot_jobid = ] 'dynamic_snapshot_jobid' ]
[ , [ @ignore_distributor =] ignore_distributor ]

Arguments
[ @publication=] 'publication'
Is the name of the publication from which the filtered data snapshot job is being removed. publication is sysname,
with no default.
[ @dynamic_snapshot_jobname= ] 'dynamic_snapshot_jobname'
Is the name of the filtered data snapshot job being removed. dynamic_snapshot_jobnameis sysname, and if it is
not supplied defaults to whatever job name is associated with dynamic_snapshot_jobid.
[ @dynamic_snapshot_jobid= ] 'dynamic_snapshot_jobid'
Is an identifier for the filtered data snapshot job being removed. dynamic_snapshot_jobidis uniqueidentifier, with
default of NULL.

IMPORTANT
Only dynamic_snapshot_jobidor dynamic_snapshot_jobname can be specified. If values are not supplied for either
dynamic_snapshot_jobidor dynamic_snapshot_jobname, all dynamic snapshot jobs for the publication are removed.

[ @ignore_distributor =] ignore_distributor
ignore_distributor is bit, with a default of 0. This parameter can be used to drop a dynamic snapshot job without
doing cleanup tasks at the Distributor.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropdynamicsnapshot is used in merge replication.
Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_dropdynamicsnapshot.

See Also
sp_adddynamicsnapshot_job (Transact-SQL)
sp_dropmergealternatepublisher (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes an alternate Publisher from a merge publication. This stored procedure is executed at the Subscriber on
the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_dropmergealaternatepublisher [ @publisher = ] 'publisher' , [ @publisher_db = ] 'publisher_db' , [
@publication = ] 'publication' , [ @alternate_publisher = ] 'alternate_publisher' , [
@alternate_publisher_db = ] 'alternate_publisher_db' , [ @alternate_publication = ] 'alternate_publication'

Arguments
[ @publisher=] 'publisher'
Is the name of the current Publisher. publisheris sysname, with no default.
[ @publisher_db=] 'publisher_db'
Is the name of the current publication database. publisher_dbis sysname, with no default.
[ @publication =] 'publication'
Is the name of the current publication. publication is sysname, with no default.
[ @alternate_publisher=] 'alternate_publisher'
Is the name of the alternate Publisher to drop as the alternate synchronization partner. alternate_publisheris
sysname, with no default.
[ @alternate_publisher_db=] 'alternate_publisher_db'
Is the name of the publication database to drop as the alternate synchronization partner publication database.
alternate_publisher_dbis sysname, with no default.
[ @alternate_publication=] 'alternate_publication'
Is the name of the publication to drop as the alternate synchronization partner publication. alternate_publicationis
sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropmergealternatepublisher is used in merge replication.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_dropmergelternatepublisher.

See Also
sp_addmergealternatepublisher (Transact-SQL)
sp_dropmergearticle (Transact-SQL)
1/2/2018 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes an article from a merge publication. This stored procedure is executed at the Publisher on the publication
database.
Transact-SQL Syntax Conventions

Syntax
sp_dropmergearticle [ @publication= ] 'publication'
, [ @article= ] 'article'
[ , [ @ignore_distributor= ] ignore_distributor
[ , [ @reserved= ] reserved
[ , [ @force_invalidate_snapshot= ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]
[ , [ @ignore_merge_metadata = ] ignore_merge_metadata ]

Arguments
[ @publication=] 'publication'
Is the name of the publication from which to drop an article. publicationis sysname, with no default.
[ @article=] 'article'
Is the name of the article to drop from the given publication. articleis sysname, with no default. If all, all existing
articles in the specified merge publication are removed. Even if article is all, the publication still must be dropped
separately from the article.
[ @ignore_distributor=] ignore_distributor
Indicates whether this stored procedure is executed without connecting to the Distributor. ignore_distributor is bit,
with a default of 0.
[ @reserved=] reserved
Is reserved for future use. reserved is nvarchar(20), with a default of NULL.
[ @force_invalidate_snapshot=] force_invalidate_snapshot
Enables or disables the ability to have a snapshot invalidated. force_invalidate_snapshot is a bit, with a default 0.
0 specifies that changes to the merge article do not cause the snapshot to be invalid.
1 means that changes to the merge article may cause the snapshot to be invalid, and if that is the case, a value of 1
gives permission for the new snapshot to occur.
[ @force_reinit_subscription = ] force_reinit_subscription
Acknowledges that dropping the article requires existing subscriptions to be reinitialized. force_reinit_subscription
is a bit, with a default of 0.
0 specifies that dropping the article does not cause the subscription to be reinitialized.
1 means that dropping the article causes existing subscriptions to be reinitialized, and gives permission for the
subscription reinitialization to occur.
[ @ignore_merge_metadata= ] ignore_merge_metadata
Internal use only.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropmergearticle is used in merge replication. For more information about dropping articles, see Add Articles
to and Drop Articles from Existing Publications.
Executing sp_dropmergearticle to drop an article from a publication does not remove the object from the
publication database or the corresponding object from the subscription database. Use DROP <object> to remove
these objects manually if necessary.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_dropmergearticle.

Example
DECLARE @publication AS sysname;
DECLARE @article1 AS sysname;
DECLARE @article2 AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @article1 = N'SalesOrderDetail';
SET @article2 = N'SalesOrderHeader';

-- Remove articles from a merge publication.


USE [AdventureWorks]
EXEC sp_dropmergearticle
@publication = @publication,
@article = @article1,
@force_invalidate_snapshot = 1;
EXEC sp_dropmergearticle
@publication = @publication,
@article = @article2,
@force_invalidate_snapshot = 1;
GO
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @table3 AS sysname;
DECLARE @salesschema AS sysname;
DECLARE @hrschema AS sysname;
DECLARE @filterclause AS nvarchar(1000);
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesOrderHeader';
SET @table3 = N'SalesOrderDetail';
SET @salesschema = N'Sales';
SET @hrschema = N'HumanResources';
SET @filterclause = N'Employee.LoginID = HOST_NAME()';

-- Drop the merge join filter between SalesOrderHeader and SalesOrderDetail.


EXEC sp_dropmergefilter
@publication = @publication,
@article = @table3,
@filtername = N'SalesOrderDetail_SalesOrderHeader',
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Drops the merge join filter between Employee and SalesOrderHeader.


EXEC sp_dropmergefilter
@publication = @publication,
@article = @table2,
@filtername = N'SalesOrderHeader_Employee',
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Drops the article for the SalesOrderDetail table.


EXEC sp_dropmergearticle
@publication = @publication,
@article = @table3,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Drops the article for the SalesOrderHeader table.


EXEC sp_dropmergearticle
@publication = @publication,
@article = @table2,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Drops the article for the Employee table.


EXEC sp_dropmergearticle
@publication = @publication,
@article = @table1,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;
GO

See Also
Delete an Article
Add Articles to and Drop Articles from Existing Publications
sp_addmergearticle (Transact-SQL)
sp_changemergearticle (Transact-SQL)
sp_helpmergearticle (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_dropmergefilter (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops a merge filter. sp_dropmergefilter drops all the merge filter columns defined on the merge filter that is to
be dropped. This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_dropmergefilter [ @publication= ] 'publication', [ @article= ] 'article' , [ @filtername= ]
'filtername'
[ , [ @force_invalidate_snapshot= ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @article=] 'article'
Is the name of the article. article is sysname, with no default.
[ @filtername=] 'filtername'
Is the name of the filter to be dropped. filtername is sysname, with no default.
[ @force_invalidate_snapshot= ] force_invalidate_snapshot
Enables or disables the ability to have a snapshot invalidated. force_invalidate_snapshot is a bit, with a default 0.
0 specifies that changes to the merge article do not cause the snapshot to be invalid.
1 means that changes to the merge article may cause the snapshot to be invalid. If that is the case, a value of 1
gives permission for the new snapshot to occur.
[ @force_reinit_subscription= ] force_reinit_subscription
Enables or disables the ability to mark a subscription as not valid. force_reinit_subscription is a bit, with a default 0.
0 specifies that changes to the merge article filter do not cause the subscriptions to be invalid.
1 means that changes to the merge article filter causes the subscriptions to be invalid.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropmergefilter is used in merge replication.
Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_dropmergefilter.

See Also
Change Publication and Article Properties
sp_addmergefilter (Transact-SQL)
sp_changemergefilter (Transact-SQL)
sp_helpmergefilter (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_dropmergepartition (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes a partition for a parameterized row filter from a publication. This stored procedure is executed at the
Publisher on the publication database. This stored procedure also removes the corresponding snapshot job and
snapshot files for the partition.
Transact-SQL Syntax Conventions

Syntax
sp_dropmergepartition [ @publication = ] 'publication'
, [ @suser_sname = ] 'suser_sname'
, [ @host_name = ] 'host_name'

Arguments
[ @publication] = 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @suser_sname= ] 'suser_sname'
Is the value of the SUSER_SNAME function at the Subscriber used to define the partition. suser_sname is sysname,
with no default.
[ @host_name = ] 'host_name'
Is the value of the HOST_NAME function at the Subscriber used to define the partition. host_name is sysname,
with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropmergepartition is used in merge replication.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_dropmergepartition.

See Also
Manage Partitions for a Merge Publication with Parameterized Filters
sp_dropmergepublication (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops a merge publication and its associated Snapshot Agent. All subscriptions must be dropped before dropping
a merge publication. The articles in the publication are dropped automatically. This stored procedure is executed at
the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_dropmergepublication [ @publication= ] 'publication'
[ , [ @ignore_distributor = ] ignore_distributor ]
[ , [ @reserved = ] reserved ]
[ , [ @ignore_merge_metadata = ] ignore_merge_metadata ]

Arguments
[ @publication=] 'publication'
Is the name of the publication to drop. publication is sysname, with no default. If all, all existing merge
publications are removed as well as the Snapshot Agent job associated with them. If you specify a particular value
for publication, only that publication and its associated Snapshot Agent job are dropped.
[ @ignore_distributor =] ignore_distributor
Used to drop a publication without doing cleanup tasks at the Distributor. ignore_distributor is bit, with a default
of 0. This parameter is also used when reinstalling the Distributor.
[ @reserved=] reserved
Is reserved for future use. reserved is bit, with a default of 0.
[ @ignore_merge_metadata= ] ignore_merge_metadata
Internal use only.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropmergepublication is used in merge replication.
sp_dropmergepublication recursively drops all articles that are associated with a publication and then drops the
publication itself. A publication cannot be removed if it has one or more subscriptions to it. For information about
how to remove subscriptions, see Delete a Push Subscription and Delete a Pull Subscription.
Executing sp_dropmergepublication to drop a publication does not remove published objects from the
publication database or the corresponding objects from the subscription database. Use DROP <object> to remove
these objects manually if necessary.
Example
DECLARE @publication AS sysname
DECLARE @publicationDB AS sysname
SET @publication = N'AdvWorksSalesOrdersMerge'
SET @publicationDB = N'AdventureWorks'

-- Remove the merge publication.


USE [AdventureWorks]
EXEC sp_dropmergepublication @publication = @publication;

-- Remove replication objects from the database.


USE master
EXEC sp_replicationdboption
@dbname = @publicationDB,
@optname = N'merge publish',
@value = N'false'
GO

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_dropmergepublication.

See Also
Delete a Publication
sp_addmergepublication (Transact-SQL)
sp_changemergepublication (Transact-SQL)
sp_helpmergepublication (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_dropmergepullsubscription (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops a merge pull subscription. This stored procedure is executed at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_dropmergepullsubscription [ @publication= ] 'publication'
, [ @publisher= ] 'publisher'
, [ @publisher_db= ] 'publisher_db'
[ , [ @reserved= ] 'reserved' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of NULL. This parameter is required. Specify
a value of all to remove subscriptions to all publications
[ @publisher=] 'publisher'
Is the name of the Publisher. publisheris sysname, with a default of NULL. This parameter is required.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_dbis sysname, with a default of NULL. This parameter is
required.
[ @reserved=] 'reserved'
Is reserved for future use. reserved is bit, with a default of 0.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropmergepullsubscription is used in merge replication.
sp_dropmergepullsubscription drops the Merge Agent for this merge pull subscription, although the Merge
Agent is not created in sp_addmergepullsubscription.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- This batch is executed at the Subscriber to remove


-- a merge pull subscription.
DECLARE @publication AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publication_db AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @publisher = $(PubServer);
SET @publication_db = N'AdventureWorks2012';

USE [AdventureWorks2012Replica]
EXEC sp_dropmergepullsubscription
@publisher = @publisher,
@publisher_db = @publication_db,
@publication = @publication;
GO

Permissions
Only members of the sysadmin fixed server role or the user that created the merge pull subscription can execute
sp_dropmergepullsubscription. The db_owner fixed database role is only able to execute
sp_dropmergepullsubscription if the user that created the merge pull subscription belongs to this role.

See Also
Delete a Pull Subscription
sp_addmergepullsubscription (Transact-SQL)
sp_changemergepullsubscription (Transact-SQL)
sp_dropmergesubscription (Transact-SQL)
sp_helpmergepullsubscription (Transact-SQL)
sp_dropmergesubscription (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops a subscription to a merge publication and its associated Merge Agent. This stored procedure is executed at
the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_dropmergesubscription [ [ @publication= ] 'publication' ]
[ , [ @subscriber= ] 'subscriber'
[ , [ @subscriber_db= ] 'subscriber_db' ]
[ , [ @subscription_type= ] 'subscription_type' ]
[ , [ @ignore_distributor = ] ignore_distributor ]
[ , [ @reserved = ] reserved ]

Arguments
[ @publication= ] 'publication'
Is the publication name. publication is sysname, with a default of NULL. The publication must already exist and
conform to the rules for identifiers.
[ @subscriber=] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[ @subscriber_db= ] 'subscriber_db'
Is the name of the subscription database. subscription_databaseis sysname, with a default of NULL.
[ @subscription_type= ] 'subscription_type'
Is the type of subscription. subscription_typeis nvarchar(15), and can be one of these values.

VALUE DESCRIPTION

all Push, pull, and anonymous subscriptions

anonymous Anonymous subscription.

push Push subscription.

pull Pull subscription.

both (default) Both push and pull subscriptions.

[ @ignore_distributor = ] ignore_distributor
Indicates whether this stored procedure is executed without connecting to the Distributor. ignore_distributor is
bit, with a default of 0. This parameter can be used to drop a subscription without doing cleanup tasks at the
Distributor. It is also useful if you had to reinstall the Distributor.
[ @reserved= ] reserved
Is reserved for future use. reserved is bit, with a default of 0.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropmergesubscription is used in merge replication.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- This batch is executed at the Publisher to remove


-- a pull or push subscription to a merge publication.
DECLARE @publication AS sysname;
DECLARE @subscriber AS sysname;
DECLARE @subscriptionDB AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @subscriber = $(SubServer);
SET @subscriptionDB = N'AdventureWorks2012Replica';

USE [AdventureWorks2012]
EXEC sp_dropmergesubscription
@publication = @publication,
@subscriber = @subscriber,
@subscriber_db = @subscriptionDB;
GO

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_dropmergesubscription.

See Also
Delete a Push Subscription
Delete a Pull Subscription
sp_addmergesubscription (Transact-SQL)
sp_changemergesubscription (Transact-SQL)
sp_helpmergesubscription (Transact-SQL)
sp_droppublication (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops a publication and its associated Snapshot Agent. All subscriptions must be dropped before dropping a
publication. The articles in the publication are dropped automatically. This stored procedure is executed at the
Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_droppublication [ @publication= ] 'publication'
[ , [ @ignore_distributor = ] ignore_distributor ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication to be dropped. publication is sysname, with no default. If all is specified, all
publications are dropped from the publication database, except for those with subscriptions.
[ @ignore_distributor = ] ignore_distributor
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_droppublication is used in snapshot replication and transactional replication.
sp_droppublication recursively drops all articles associated with a publication and then drops the publication
itself. A publication cannot be removed if it has one or more subscriptions to it. For information about how to
remove subscriptions, see Delete a Push Subscription and Delete a Pull Subscription.
Executing sp_droppublication to drop a publication does not remove published objects from the publication
database or the corresponding objects from the subscription database. Use DROP <object> to remove these
objects manually if necessary.

Permissions
Only members of the sysadmin fixed server role can execute sp_droppublication.

Examples
DECLARE @publicationDB AS sysname;
DECLARE @publication AS sysname;
SET @publicationDB = N'AdventureWorks';
SET @publication = N'AdvWorksProductTran';

-- Remove a transactional publication.


USE [AdventureWorks2012]
EXEC sp_droppublication @publication = @publication;

-- Remove replication objects from the database.


USE [master]
EXEC sp_replicationdboption
@dbname = @publicationDB,
@optname = N'publish',
@value = N'false';
GO

See Also
Delete a Publication
sp_addpublication (Transact-SQL)
sp_changepublication (Transact-SQL)
sp_helppublication (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_droppullsubscription (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops a subscription at the current database of the Subscriber. This stored procedure is executed at the Subscriber
on the pull subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_droppullsubscription [ @publisher= ] 'publisher'
, [ @publisher_db= ] 'publisher_db'
, [ @publication= ] 'publication'
[ , [ @reserved= ] reserved ]

Arguments
[ @publisher= ] 'publisher'
Is the remote server name. publisher is sysname, with no default. If all, the subscription is dropped at all the
Publishers.
[ @publisher_db= ] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default. all means all the Publisher
databases.
[ @publication= ] 'publication'
Is the publication name. publication is sysname, with no default. If all, the subscription is dropped to all the
publications.
[ @reserved= ] reserved
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_droppullsubscription is used in snapshot replication and transactional replication.
sp_droppullsubscription deletes the corresponding row in the MSreplication_subscriptions (Transact-SQL) table
and the corresponding Distributor Agent at the Subscriber. If no rows are left in MSreplication_subscriptions
(Transact-SQL), it drops the table.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- This is the batch executed at the Subscriber to drop


-- a pull subscription to a transactional publication.
DECLARE @publication AS sysname;
DECLARE @publisher AS sysname;
DECLARE @publicationDB AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @publisher = $(PubServer);
SET @publicationDB = N'AdventureWorks2012';

USE [AdventureWorks2012Replica]
EXEC sp_droppullsubscription
@publisher = @publisher,
@publisher_db = @publicationDB,
@publication = @publication;
GO

Permissions
Only members of the sysadmin fixed server role or the user who created the pull subscription can execute
sp_droppullsubscription. The db_owner fixed database role is only able to execute sp_droppullsubscription if
the user who created the pull subscription belongs to this role.

See Also
Delete a Pull Subscription
sp_addpullsubscription (Transact-SQL)
sp_change_subscription_properties (Transact-SQL)
sp_helppullsubscription (Transact-SQL)
sp_dropsubscription (Transact-SQL)
sp_dropsubscriber (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the Subscriber designation from a registered server. This stored procedure is executed at the Publisher
on the publication database.

IMPORTANT
This stored procedure has been deprecated. You are no longer required to explicitly register a Subscriber at the Publisher.

Transact-SQL Syntax Conventions

Syntax
sp_dropsubscriber [ @subscriber= ] 'subscriber'
[ , [ @reserved= ] 'reserved' ]
[ , [ @ignore_distributor = ] ignore_distributor ]

Arguments
[ @subscriber= ] 'subscriber'
Is the name of the Subscriber to be dropped. subscriber is sysname, with no default.
[ @reserved= ] 'reserved'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @ignore_distributor = ] ignore_distributor
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropsubscriber is used in all types of replication.
This stored procedure removes the server sub option and removes the remote login mapping of system
administrator to repl_subscriber.

Permissions
Only members of the sysadmin fixed server role can execute sp_dropsubscriber.

See Also
Delete a Push Subscription
Delete a Pull Subscription
sp_addsubscriber (Transact-SQL)
sp_changesubscriber (Transact-SQL)
sp_helpdistributor (Transact-SQL)
sp_helpserver (Transact-SQL)
sp_helpsubscriberinfo (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_dropsubscription (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Drops subscriptions to a particular article, publication, or set of subscriptions on the Publisher. This stored
procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_dropsubscription [ [ @publication= ] 'publication' ]
[ , [ @article= ] 'article' ]
, [ @subscriber= ] 'subscriber'
[ , [ @destination_db= ] 'destination_db' ]
[ , [ @ignore_distributor = ] ignore_distributor ]
[ , [ @reserved= ] 'reserved' ]

Arguments
[ @publication= ] 'publication'
Is the name of the associated publication. publication is sysname, with a default of NULL. If all, all subscriptions
for all publications for the specified Subscriber are canceled. publication is a required parameter.
[ @article= ] 'article'
Is the name of the article. article is sysname, with a default value of NULL. If all, subscriptions to all articles for
each specified publication and Subscriber are dropped. Use all for publications that allow immediate updating.
[ @subscriber= ] 'subscriber'
Is the name of the Subscriber that will have its subscriptions dropped. subscriber is sysname, with no default. If
all, all subscriptions for all Subscribers are dropped.
[ @destination_db= ] 'destination_db'
Is the name of the destination database. destination_db is sysname, with a default of NULL. If NULL, all the
subscriptions from that Subscriber are dropped.
[ @ignore_distributor = ] ignore_distributor
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @reserved= ] 'reserved'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_dropsubscription is used in snapshot and transactional replication.
If you drop the subscription on an article in an immediate-sync publication, you cannot add it back unless you
drop the subscriptions on all the articles in the publication and add them all back at once.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- This batch is executed at the Publisher to remove


-- a pull or push subscription to a transactional publication.
DECLARE @publication AS sysname;
DECLARE @subscriber AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @subscriber = $(SubServer);

USE [AdventureWorks2012]
EXEC sp_dropsubscription
@publication = @publication,
@article = N'all',
@subscriber = @subscriber;
GO

Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role, or the user that created the
subscription can execute sp_dropsubscription.

See Also
Delete a Push Subscription
sp_addsubscription (Transact-SQL)
sp_changesubstatus (Transact-SQL)
sp_helpsubscription (Transact-SQL)
sp_dsninfo (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns ODBC or OLE DB data source information from the Distributor associated with the current server. This
stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_dsninfo [ @dsn =] 'dsn'
[ , [ @infotype =] 'info_type']
[ , [ @login =] 'login']
[ , [ @password =] 'password']
[ , [ @dso_type=] dso_type]

Arguments
[ @dsn =] 'dsn'
Is the name of the ODBC DSN or OLE DB linked server. dsn is varchar(128), with no default.
[ @infotype =] 'info_type'
Is the type of information to return. If info_type is not specified or if NULL is specified, all information types are
returned. info_type is varchar(128), with a default of NULL, and can be one of these values.

VALUE DESCRIPTION

DBMS_NAME Specifies the data source vendor name.

DBMS_VERSION Specifies the data source version.

DATABASE_NAME Specifies the database name.

SQL_SUBSCRIBER Specifies the data source can be a Subscriber.

[ @login =] 'login'
Is the login for the data source. If the data source includes a login, specify NULL or omit the parameter. loginis
varchar(128), with a default of NULL.
[ @password =] 'password'
Is the password for the login. If the data source includes a login, specify NULL or omit the parameter. passwordis
varchar(128), with a default of NULL.
[ @dso_type=] dso_type
Is the data source type. dso_type is int, and can be one of these values.
VALUE DESCRIPTION

1 (default) ODBC data source

3 OLE DB data source

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

Information Type nvarchar(64) Information types such as


DBMS_NAME, DBMS_VERSION,
DATABASE_NAME, SQL_SUBSCRIBER.

Value nvarchar(512) Value of the associated information


type.

Remarks
sp_dsninfo is used in all types of replication.
sp_dsninfo retrieves ODBC or OLE DB data source information that shows whether the database can be used for
replication or querying.

Permissions
Only members of the sysadmin fixed server role can execute sp_dsninfo.

See Also
sp_enumdsn (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_enumcustomresolvers (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a list of all available business logic handlers and custom resolvers registered at the Distributor. This stored
procedure is executed at the Publisher on any database.
Transact-SQL Syntax Conventions

Syntax
sp_enumcustomresolvers [ [ @distributor =] 'distributor']

Arguments
[ @distributor =] 'distributor'
Is the name of the Distributor where the custom resolver is located. distributor is sysname, with a default of NULL.
This parameter is deprecated and will be removed in a future release.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

article_resolver nvarchar(255) Friendly name for the business logic


handler or conflict resolver.

resolver_clsid nvarchar(50) Class ID (CLSID) of the COM-based


resolver. For a business logic handler,
this column returns a zero CLSID value.

is_dotnet_assembly bit Indicates whether the registration is for


a business logic handler.

0 = COM-based conflict resolver

1 = business logic handler

dotnet_assembly_name nvarchar(255) The name of the Microsoft .NET


Framework assembly that implements
the business logic handler.

dotnet_class_name nvarchar(255) Is the name of the class that overrides


BusinessLogicModule to implement the
business logic handler.

Return Code Values


0 (success) or 1 (failure)
Remarks
sp_enumcustomresolvers is used in merge replication.

Permissions
Only members of the sysadmin fixed server role and the db_owner fixed database role can execute
sp_enumcustomresolvers.

See Also
Implement a Business Logic Handler for a Merge Article
Implement a Custom Conflict Resolver for a Merge Article
sp_lookupcustomresolver (Transact-SQL)
sp_unregistercustomresolver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_enumeratependingschemachanges (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a list of all pending schema changes. This stored procedure can be used with
sp_markpendingschemachange, which enables an administrator to skip selected pending schema changes so that
they are not replicated. This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_enumeratependingschemachanges [ @publication = ] 'publication'
[ , [ @starting_schemaversion = ] starting_schemaversion ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @starting_schemaversion= ] starting_schemaversion
Is the lowest number schema change to include in the result set.

Result Set
COLUMN NAME DATA TYPE DESCRIPTION

article_name sysname Name of the article to which the


schema change applies, or Publication-
wide for schema changes that apply to
the entire publication.

schemaversion int Number of the pending schema change.

schematype sysname A text value that represents the type of


schema change.

schematext nvarchar(max) Transact-SQL that describes the schema


change.

schemastatus nvarchar(10) Indicates if a schema change is pending


for the article, which can be one of the
following values:

active = schema change is pending

inactive = schema change is inactive

skip = schema change is not replicated


COLUMN NAME DATA TYPE DESCRIPTION

schemaguid uniqueidentifier Identifies the schema change.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_enumeratependingschemachanges is used in merge replication.
sp_enumeratependingschemachanges, used with sp_markpendingschemachange, is intended for the
supportability of merge replication and should be used only when other corrective actions, such as reinitialization,
have failed to correct the situation.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_enumeratependingschemachanges.

See Also
Replication Stored Procedures (Transact-SQL)
sysmergeschemachange (Transact-SQL)
sp_enumdsn (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns a list of all defined ODBC and OLE DB data source names for a server running under a specific Microsoft
Windows user account. This stored procedure is executed at the Publisher on any database.
Transact-SQL Syntax Conventions

Syntax
sp_enumdsn

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

Data Source Name sysname Name of the data source.

Description varchar(255) Description of the data source.

Type int Type of data source:

1 = ODBC DSN

3 = OLE DB data source

Provider Name varchar(255) Name of the OLE DB provider. Value is


NULL for ODBC DSN.

Remarks
Every Microsoft SQL Server service has a user context. A user context is a set of Registry entries that includes the
definitions of the ODBC data sources for the user. The user context is provided by the username under which the
SQL Server is running.
For example, if the server is running under the system account user context, the data source names (DSNs) that are
returned will all be system DSNs that are associated with the system account. If the server is running under a
private user account, only the DSNs defined for that private account of that user is returned.

Permissions
Only members of the sysadmin fixed server role can execute sp_enumdsn.
See Also
sp_dsninfo (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_expired_subscription_cleanup (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Checks the status of all the subscriptions of every publication and drops those that have expired. This stored
procedure is executed at the Publisher on any database or at the Distributor on the distribution database for a non-
Microsoft SQL Server Publisher.
Transact-SQL Syntax Conventions

Syntax
sp_expired_subscription_cleanup [ [ @publisher = ] 'publisher' ]

Arguments
[ @publisher= ] 'publisher'
Is the name of a non- SQL Server publisher. publication is sysname, with a default value of NULL. You should not
specify this parameter for a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_expired_subscription_cleanup is used in all types of replication.
sp_expired_subscription_cleanup is executed by the Expired Subscription Clean Up job to detect and remove
expired subscriptions from publication databases every 24 hours. If any of the subscriptions are out-of-date, that is,
have not synchronized with the Publisher within the retention period, the publication is declared expired and the
traces of the subscription are cleaned up at the Publisher. For more information, see Subscription Expiration and
Deactivation.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_expired_subscription_cleanup.

See Also
sp_mergesubscription_cleanup (Transact-SQL)
sp_subscription_cleanup (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_generatefilters (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Creates filters on foreign key tables when a specified table is replicated. This stored procedure is executed at the
Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_generatefilters [ @publication =] 'publication'

Arguments
[ @publication=] 'publication'
Is the name of the publication to be filtered. publication is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_generatefilters is used in merge replication.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_generatefilters.

See Also
sp_bindsession (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_get_distributor (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Determines whether a Distributor is installed on a server. This stored procedure is executed at the computer where
the Distributor is being looked for, on any database.
Transact-SQL Syntax Conventions

Syntax
sp_get_distributor

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

installed int 0 = No; 1 = Yes

distribution server sysname Name of the Distributor server

distribution db installed int 0 = No; 1 = Yes

is distribution publisher int 0 = No; 1 = Yes

has remote distribution publisher int 0 = No; 1 = Yes

Remarks
sp_get_distributor is used primarily by the Microsoft SQL Server Management Studio in snapshot, transactional,
and merge replication.

Permissions
Any user can execute sp_get_distributor. A non-NULL result set is returned when this stored procedure is
executed by members of the db_owner or replmonitor fixed database roles on the distribution database, or
members of the db_owner fixed database role on at least one published database. A non-NULL result set is also
returned when this stored procedure is executed by users in the publication access list (PAL) of at least one
published database, or in the PAL of the distribution database for a non-SQL Server Publisher, can also execute
sp_get_distributor.

See Also
Configure Publishing and Distribution
Distributor and Publisher Information Script
Replication Stored Procedures (Transact-SQL)
sp_get_redirected_publisher (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Used by replication agents to query a distributor to determine whether the original publisher has been redirected.
Transact-SQL Syntax Conventions

Syntax
sp_get_redirected_publisher
[ @original_publisher = ] 'original_publisher',
[ @publisher_db = ] 'database_name',
[ @bypass_publisher_validation = ] [0 | 1 ]

Arguments
[ @original_publisher = ] 'original_publisher'
The name of the database being published. publisher_db is sysname, with no default.
[ @publisher_db = ] 'publisher_db'
The name of the database being published. publisher_db is sysname, with no default.
[ @bypass_publisher_validation = ] [0 | 1 ]
Used to bypass validation of the redirected publisher. If 0, validation is performed . If 1, validation is not performed.
bypass_publisher_validation is bit, with a default of 0.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

redirected_publisher sysname The name of the publisher after


redirection.

error_number int The error number of the validation


error.

error_severity int The severity of the validation error.

error_message nvarchar(4000) The text of the validation error


message.

Remarks
redirected_publisher returns the current publisher name. Returns null if the publisher and publishing databases
have not been redirected using sp_redirect_publisher.
If validation is not requested or if no entry exists for the publisher and the publishing database, error_number and
error_severity return 0 and error_message returns null.
If validation is requested, the validation stored procedure sp_validate_redirected_publisher (Transact-SQL) is called
to verify that the target of the redirection is a suitable host for the publishing database. If the validation succeeds,
sp_get_redirected_publisher returns the redirected publisher name, 0 for the error_number and error_severity
columns, and null in the error_message column.
If validation is requested and fails, the redirected publisher name is returned along with error information.

Permissions
Caller must either be a member of the sysadmin fixed server role, the db_owner fixed database role for the
distribution database, or a member of a publication access list for a defined publication associated with the
publisher database.

See Also
Replication Stored Procedures (Transact-SQL)
sp_validate_redirected_publisher (Transact-SQL)
sp_redirect_publisher (Transact-SQL)
sp_validate_replica_hosts_as_publishers (Transact-SQL)
sp_getagentparameterlist (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a list of all replication agent parameters that can be set in an agent profile for the specified agent type. This
stored procedure is executed at the Distributor where the agent is running, on any database.
Transact-SQL Syntax Conventions

Syntax
sp_getagentparameterlist [ @agent_type = ] 'agent_type'

Arguments
[ @agent_type = ] 'agent_type'
Is the replication agent for which the parameter is being added. agent_type is int, and can be one of these values:

VALUE AGENT

1 Snapshot

2 Log Reader

3 Distribution

4 Merge

9 Queue Reader

Return Code Values


0 (success) or 1 (failure)

Remarks
Permissions
Only members of the sysadmin fixed server role can execute sp_getagentparameter.

See Also
sp_add_agent_parameter (Transact-SQL)
sp_add_agent_profile (Transact-SQL)
sp_drop_agent_parameter (Transact-SQL)
sp_help_agent_parameter (Transact-SQL)
Replication Agent Profiles
System Stored Procedures (Transact-SQL)
sp_getdefaultdatatypemapping (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information on the default mapping for the specified data type between Microsoft SQL Server and a non-
SQL Server database management system (DBMS). This stored procedure is executed at the Distributor on any
database.
Transact-SQL Syntax Conventions

Syntax
sp_getdefaultdatatypemapping [ @source_dbms = ] 'source_dbms'
[ , [ @source_version = ] 'source_version' ]
, [ @source_type = ] 'source_type'
[ , [ @source_length = ] source_length ]
[ , [ @source_precision = ] source_precision ]
[ , [ @source_scale = ] source_scale ]
[ , [ @source_nullable = ] source_nullable ]
, [ @destination_dbms = ] 'destination_dbms'
[ , [ @destination_version = ] 'destination_version' ]
[ , [ @destination_type = ] 'destination_type' OUTPUT ]
[ , [ @destination_length = ] destination_length OUTPUT ]
[ , [ @destination_precision = ] destination_precision OUTPUT ]
[ , [ @destination_scale = ] destination_scale OUTPUT ]
[ , [ @destination_nullable = ] source_nullable OUTPUT ]
[ , [ @dataloss = ] dataloss OUTPUT ]

Arguments
[ @source_dbms= ] 'source_dbms'
Is the name of the DBMS from which the data types are mapped. source_dbms is sysname, and can be one of the
following values:

VALUE DESCRIPTION

MSSQLSERVER The source is a SQL Server database.

ORACLE The source is an Oracle database.

You must specify this parameter.


[ @source_version= ] 'source_version'
Is the version number of the source DBMS. source_version is varchar(10), with a default value of NULL.
[ @source_type= ] 'source_type'
Is the data type in the source DBMS. source_type is sysname, with no default.
[ @source_length= ] source_length
Is the length of the data type in the source DBMS. source_length is bigint, with a default value of NULL.
[ @source_precision= ] source_precision
Is the precision of the data type in the source DBMS. source_precision is bigint, with a default value of NULL.
[ @source_scale= ] source_scale
Is the scale of the data type in the source DBMS. source_scale is int, with a default value of NULL.
[ @source_nullable= ] source_nullable
Is if the data type in the source DBMS supports a value of NULL. source_nullable is bit, with a default value of 1,
which means that NULL values are supported.
[ @destination_dbms = ] 'destination_dbms'
Is the name of the destination DBMS. destination_dbms is sysname, and can be one of the following values:

VALUE DESCRIPTION

MSSQLSERVER The destination is a SQL Server database.

ORACLE The destination is an Oracle database.

DB2 The destination is an IBM DB2 database.

SYBASE The destination is a Sybase database.

You must specify this parameter.


[ @destination_version= ] 'destination_version'
Is the product version of the destination DBMS. destination_version is varchar(10), with a default value of NULL.
[ @destination_type= ] 'destination_type' OUTPUT
Is the data type listed in the destination DBMS. destination_type is sysname, with a default value of NULL.
[ @destination_length= ] destination_length OUTPUT
Is the length of the data type in the destination DBMS. destination_length is bigint, with a default value of NULL.
[ @destination_precision= ] destination_precision OUTPUT
Is the precision of the data type in the destination DBMS. destination_precision is bigint, with a default value of
NULL.
[ @destination_scale= ] destination_scaleOUTPUT
Is the scale of the data type in the destination DBMS. destination_scale is int, with a default value of NULL.
[ @destination_nullable= ] destination_nullableOUTPUT
Is if the data type in the destination DBMS supports a value of NULL. destination_nullable is bit, with a default
value of NULL. 1 means that NULL values are supported.
[ @dataloss= ] datalossOUTPUT
Is if the mapping has the potential for data loss. dataloss is bit, with a default value of NULL. 1 means that there is
a potential for data loss.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_getdefaultdatatypemapping is used in all types of replication between SQL Server and a non- SQL Server
DBMS.
sp_getdefaultdatatypemapping returns the default destination data type that is the closest match to the
specified source data type.

Permissions
Only members of the sysadmin fixed server role can execute sp_getdefaultdatatypemapping.

See Also
sp_helpdatatypemap (Transact-SQL)
sp_setdefaultdatatypemapping (Transact-SQL)
Data Type Mapping for Oracle Publishers
IBM DB2 Subscribers
Oracle Subscribers
sp_getmergedeletetype (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the type of merge delete. This stored procedure is executed at the Publisher on the publication database or
at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_getmergedeletetype [ @source_object = ] 'source_object', [ @rowguid =] 'rowguid', [ @delete_type=]
delete_type OUTPUT

Arguments
[ @source_object =] 'source_object'
Is the name of the source object. source_object is nvarchar(386), with no default.
[ @rowguid=] 'rowguid'
Is the row identifier for the delete type. rowguid is uniqueidentifier, with no default.
[ @delete_type=] delete_type OUTPUT
Is the code indicating the type of delete. delete_type is int, with no default. delete_type is also an OUTPUT
parameter, and can be one of these values.

VALUE DESCRIPTION

1 User delete

5 Partial delete

6 System delete

Remarks
sp_getmergedeletetype is used in merge replication.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_getmergedeletetype.

See Also
System Stored Procedures (Transact-SQL)
sp_getqueuedrows (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Retrieves rows at the Subscriber that have updates pending in the queue. This stored procedure is executed at the
Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_getqueuedrows [ @tablename = ] 'tablename'
[ , [ @owner = ] 'owner'
[ , [ @tranid = ] 'transaction_id' ]

Arguments
[ @tablename =] 'tablename'
Is the name of the table. tablename is sysname, with no default. The table must be a part of a queued subscription.
[ @owner =] 'owner'
Is the subscription owner. owner is sysname, with a default of NULL.
[ @tranid = ] 'transaction_id'
Allows the output to be filtered by the transaction ID. transaction_id is nvarchar(70), with a default of NULL. If
specified, the transaction ID associated with the queued command is displayed. If NULL, all the commands in the
queue are displayed.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Shows all rows that currently have at least one queued transaction for the subscribed table.

COLUMN NAME DATA TYPE DESCRIPTION

Action nvarchar(10) Type of action to be taken when


synchronization occurs.

INS= insert

DEL = delete

UPD = update

Tranid nvarchar(70) Transaction ID that the command was


executed under.
COLUMN NAME DATA TYPE DESCRIPTION

table column1...n The value for each column of the table


specified in tablename.

msrepl_tran_version uniqueidentifier This column is used for tracking


changes to replicated data and to
perform conflict detection at the
Publisher. This column is added to the
table automatically.

Remarks
sp_getqueuedrows is used at Subscribers participating in queued updating.
sp_getqueuedrows finds rows of a given table on a subscription database that have participated in a queued
update, yet currently have not been resolved by the queue reader agent.

Permissions
sp_getqueuedrows requires SELECT permissions on the table specified in tablename.

See Also
Updatable Subscriptions for Transactional Replication
Queued Updating Conflict Detection and Resolution
System Stored Procedures (Transact-SQL)
sp_getsubscriptiondtspackagename (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the name of the Data Transformation Services (DTS) package used to transform data before they are sent
to a Subscriber. This stored procedure is executed at the Publisher on any database.
Transact-SQL Syntax Conventions

Syntax
sp_getsubscriptiondtspackagename [ @publication = ] 'publication'
[ , [ @subscriber = ] 'subscriber' ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication. 'publication' is sysname, with no default.
[ @subscriber=] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

new_package_name sysname The name of the DTS package.

Remarks
sp_getsubscriptiondtspackagename is used in snapshot replication and transactional replication.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_getsubscriptiondtspackagename.
sp_gettopologyinfo (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about a peer-to-peer transactional replication topology. Execute sp_requestpeertopologyinfo
to collect information before you execute this procedure.
Transact-SQL Syntax Conventions

Syntax
sp_gettopologyinfo [ @request_id = ] request_id

Arguments
[ @request_id= ] request_id
Is the ID of a topology status request. request_id is int, with a default of NULL. To obtain an ID, use the
@request_id output parameter from sp_requestpeertopologyinfo or query the MSpeer_topologyrequest system
table.

Result Sets
sp_gettopologyinfo returns a result set that has a single XML column. The data in the XML column is the same as
the data in the MSpeer_topologyresponse system table.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_gettopologyinfo is used in peer-to-peer transactional replication. Execute sp_requestpeertopologyinfo before
you execute sp_gettopologyinfo. These procedures are used by the Configure Peer-to-Peer Topology Wizard, but
they can also be used directly if you require topology information in an XML format. If you prefer tabular results,
query the MSpeer_topologyresponse system table.

Permissions
Requires membership in the sysadmin fixed server role or db_owner fixed database role.

See Also
Peer-to-Peer Transactional Replication
Replication Stored Procedures (Transact-SQL)
sp_grant_publication_access (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Adds a login to the access list of the publication. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_grant_publication_access [ @publication = ] 'publication', [ @login = ] 'login'
[ , [ @reserved = ] 'reserved' ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication to access. 'publication' is sysname, with no default.
[ @login= ] 'login'
Is the login ID. 'login' is sysname, with no default.
[ @reserved =] 'reserved'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_grant_publication_access is used in snapshot, transactional, and merge replication.
This stored procedure can be called repeatedly.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_grant_publication_access.

See Also
sp_help_publication_access (Transact-SQL)
sp_revoke_publication_access (Transact-SQL)
Secure the Publisher
System Stored Procedures (Transact-SQL)
sp_help_agent_default (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Retrieves the ID of the default configuration for the agent type passed as parameter. This stored procedure is
executed at Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_help_agent_default [ @profile_id= ] profile_id OUTPUT
, [ @agent_type = ] agent_type

Arguments
[ @profile_id=] profile_idOUTPUT
Is the ID of the default configuration for the type of agent. profile_id is int, with no default.profile_id is also an
OUTPUT parameter and returns the ID of the default configuration for the type of agent.
[ @agent_type=] 'agent_type'
Is the type of agent. agent_type is int, with no default, and can be one of these values.

VALUE DESCRIPTION

1 Snapshot Agent.

2 Log Reader Agent.

3 Distribution Agent.

4 Merge Agent.

9 Queue Reader Agent

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_help_agent_default is used in all types of replication.

Permissions
Only members of the sysadmin fixed server role or the replmonitor fixed database role can execute
sp_help_agent_default.
See Also
System Stored Procedures (Transact-SQL)
sp_help_agent_parameter (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns all the parameters of a profile from the MSagent_parameters (Transact-SQL) system table. This stored
procedure is executed at the Distributor where the agent is running, on any database.
Transact-SQL Syntax Conventions

Syntax
sp_help_agent_parameter [ [ @profile_id = ] profile_id ]

Arguments
[ @profile_id=] profile_id
Is the ID of the profile from the MSagent_parameters (Transact-SQL) table. profile_id is int, with a default of -1,
which returns all parameters.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

profile_id int ID of the agent profile.

parameter_name sysname Name of the parameter.

value nvarchar(255) Value of the parameter.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_help_agent_parameter is used in all types of replication.

Permissions
Only members of the sysadmin fixed server role or the replmonitor fixed database role can execute
sp_help_agent_parameter.

See Also
Work with Replication Agent Profiles
sp_add_agent_parameter (Transact-SQL)
sp_drop_agent_parameter (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_help_agent_profile (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Displays the profile of a specified agent. This stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_help_agent_profile [ [ @agent_type = ] agent_type ]
[ , [ @profile_id = ] profile_id ]

Arguments
[ @agent_type=] agent_type
Is the type of agent. agent_type is int, with a default of 0, and can be one of these values.

VALUE DESCRIPTION

1 Snapshot Agent

2 Log Reader Agent

3 Distribution Agent

4 Merge Agent

9 Queue Reader Agent

[ @profile_id=] profile_id
Is the ID of the profile to be displayed. profile_id is int, with a default of -1, which returns all the profiles in the
MSagent_profiles table.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

profile_id int ID of the profile.

profile_name sysname Unique for agent type.


COLUMN NAME DATA TYPE DESCRIPTION

agent_type int 1 = Snapshot Agent

2 = Log Reader Agent

3 = Distribution Agent

4 = Merge Agent

9 = Queue Reader Agent

Type int 0 = System

1 = Custom

description varchar(3000) Description of the profile.

def_profile bit Specifies whether this profile is the


default for this agent type.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_help_agent_profile is used in all types of replication.

Permissions
Only members of the sysadmin fixed server role or the replmonitor fixed database role can execute
sp_help_agent_profile.

See Also
Work with Replication Agent Profiles
sp_add_agent_profile (Transact-SQL)
sp_drop_agent_profile (Transact-SQL)
sp_help_agent_parameter (Transact-SQL)
sp_help_peerconflictdetection (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about the conflict detection settings for a publication that is involved in a peer-to-peer
transactional replication topology.
Transact-SQL Syntax Conventions

Syntax
sp_help_peerconflictdetection [ @publication = ] 'publication'
[ ,[ @timeout = ] timeout ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication for which to return information. publication is sysname, with no default.
[ @timeout= ] timeout
Specifies the amount of time, in seconds, after which the procedure will time out while waiting for response from
every node in the topology. If there is a read-only Subscriber in the topology, specifying a time-out value is not
valid. Read-only Subscribers will never respond to a call from this procedure. timeout is int, with a default of 60.

Result Sets
sp_help_peerconflictdetection returns three result sets. These results are documented in the following topics:
MSpeer_conflictdetectionconfigrequest
MSpeer_conflictdetectionconfigresponse
Mspeer_originatorid_history

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_help_peerconflictdetection is used in peer-to-peer transactional replication.

Permissions
Requires membership in the sysadmin fixed server role or db_owner fixed database role.

See Also
Conflict Detection in Peer-to-Peer Replication
Peer-to-Peer Transactional Replication
Replication Stored Procedures (Transact-SQL)
sp_help_publication_access (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a list of all granted logins for a publication. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_help_publication_access [ @publication = ] 'publication'
[ , [ @return_granted = ] 'return_granted' ]
[ , [ @login = ] 'login' ]
[ , [ @initial_list = ] initial_list ]

Arguments
[ @publication=] 'publication'
Is the name of the publication to access. publication is sysname, with no default.
[ @return_granted=] 'return_granted'
Is the login ID. return_granted is bit, with a default of 1. If 0 is specified and SQL Server Authentication is used, the
available logins that appear at the Publisher but not at the Distributor are returned. If 0 is specified and Windows
Authentication is used, the logins not specifically denied access at either the Publisher or Distributor are returned.
[ @login=] 'login'
Is the standard security login ID. login is sysname, with a default of %.
[ @initial_list =] initial_list
Specifies whether to return all members with publication access or just those who had access before new members
were added to the list. initial_list is bit, with a default of 0.
1 returns information for all members of the sysadmin fixed server role with valid logins at the Distributor that
existed when the publication was created, as well as the current login.
0 returns information for all members of the sysadmin fixed server role with valid logins at the Distributor that
existed when the publication was created as well as all users in the publication access list who do not belong to the
sysadmin fixed server role.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

Loginname nvarchar(256) Actual login name.

Isntname int 0 = Login is not a Windows user.

1 = Login is a Windows user.


COLUMN NAME DATA TYPE DESCRIPTION

Isntgroup int 0 = Login is not a Windows group.

1 = Login is a Windows group.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_help_publication_access is used in all types of replication.
When both Isntname and Isntgroup in the result set are 0, it is assumed that the login is a SQL Server login.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_help_publication_access.

See Also
sp_grant_publication_access (Transact-SQL)
sp_revoke_publication_access (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helparticle (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Displays information about an article. This stored procedure is executed at the Publisher on the publication
database. For Oracle Publishers, this stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_helparticle [ @publication = ] 'publication'
[ , [ @article = ] 'article' ]
[ , [ @returnfilter = ] returnfilter ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @found = ] found OUTPUT ]

Arguments
[ @publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @article=] 'article'
Is the name of an article in the publication. article is sysname, with a default of %. If article is not supplied,
information on all articles for the specified publication is returned.
[ @returnfilter=] returnfilter
Specifies whether the filter clause should be returned. returnfilter is bit, with a default of 1, which returns the
filter clause.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be specified when requesting information on an article published by a SQL Server Publisher.

[ @found= ] found OUTPUT


Internal use only.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

article id int ID of the article.

article name sysname Name of the article.


COLUMN NAME DATA TYPE DESCRIPTION

base object nvarchar(257) Name of the underlying table


represented by the article or stored
procedure.

destination object sysname Name of the destination (subscription)


table.

synchronization object nvarchar(257) Name of the view that defines the


published article.

type smallint The type of article:

1 = Log-based.

3 = Log-based with manual filter.

5 = Log-based with manual view.

7 = Log-based with manual filter and


manual view.

8 = Stored procedure execution.

24 = Serializable stored procedure


execution.

32 = Stored procedure (schema only).

64 = View (schema only).

96 = Aggregate function (schema


only).

128 = Function (schema only).

257 = Log-based indexed view.

259 = Log-based indexed view with


manual filter.

261 = Log-based indexed view with


manual view.

263 = Log-based indexed view with


manual filter and manual view.

320 = Indexed view (schema only).


COLUMN NAME DATA TYPE DESCRIPTION

status tinyint Can be the & (Bitwise AND) result of


one or more or these article properties:

0x00 = Identified for informational


purposes only. Not supported. Future
compatibility is not guaranteed.

0x01 = Article is active.

0x08 = Include the column name in


insert statements.

0x16 = Use parameterized statements.

0x32 = Use parameterized statements


and include the column name in insert
statements.

filter nvarchar(257) Stored procedure used to horizontally


filter the table. This stored procedure
must have been created using FOR
REPLICATION clause.

description nvarchar(255) Descriptive entry for the article.

insert_command nvarchar(255) The replication command type used


when replicating inserts with table
articles. For more information, see
Specify How Changes Are Propagated
for Transactional Articles.

update_command nvarchar(255) The replication command type used


when replicating updates with table
articles. For more information, see
Specify How Changes Are Propagated
for Transactional Articles.

delete_command nvarchar(255) The replication command type used


when replicating deletes with table
articles. For more information, see
Specify How Changes Are Propagated
for Transactional Articles.

creation script path nvarchar(255) Path and name of an article schema


script used to create target tables.

vertical partition bit Is whether vertical partitioning is


enabled for the article; where a value of
1 means that vertical partitioning is
enabled.

pre_creation_cmd tinyint Precreation command for DROP TABLE,


DELETE TABLE, or TRUNCATE TABLE.

filter_clause ntext WHERE clause specifying the horizontal


filtering.
COLUMN NAME DATA TYPE DESCRIPTION

schema_option binary(8) Bitmap of the schema generation


option for the given article. For a
complete list of schema_option
values, see sp_addarticle (Transact-
SQL).

dest_owner sysname Name of the owner of the destination


object.

source_owner sysname Owner of the source object.

unqua_source_object sysname Name of the source object, without the


owner name.

sync_object_owner sysname Owner of the view that defines the


published article. .

unqualified_sync_object sysname Name of the view that defines the


published article, without the owner
name.

filter_owner sysname Owner of the filter.

unqua_filter sysname Name of the filter, without the owner


name.

auto_identity_range int Flag indicating if automatic identity


range handling was turned on at the
publication at the time it was created. 1
means that automatic identity range is
enabled; 0 means it is disabled.

publisher_identity_range int Range size of the identity range at the


Publisher if the article has
identityrangemanagementoption set
to auto or auto_identity_range set to
true.

identity_range bigint Range size of the identity range at the


Subscriber if the article has
identityrangemanagementoption set
to auto or auto_identity_range set to
true.

threshold bigint Percentage value indicating when the


Distribution Agent assigns a new
identity range.

identityrangemanagementoption int Indicates the identity range


management handled for the article.
COLUMN NAME DATA TYPE DESCRIPTION

fire_triggers_on_snapshot bit Is if replicated user triggers are


executed when the initial snapshot is
applied.

1 = user triggers are executed.

0 = user triggers are not executed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helparticle is used in snapshot replication and transactional replication.

Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role, or the publication access list
for the current publication can execute sp_helparticle.

Example
DECLARE @publication AS sysname;
SET @publication = N'AdvWorksProductTran';

USE [AdventureWorks2012]
EXEC sp_helparticle
@publication = @publication;
GO

See Also
View and Modify Article Properties
sp_addarticle (Transact-SQL)
sp_articlecolumn (Transact-SQL)
sp_changearticle (Transact-SQL)
sp_droparticle (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_helparticlecolumns (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns all columns in the underlying table. This stored procedure is executed at the Publisher on the publication
database. For Oracle Publishers, this stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_helparticlecolumns [ @publication = ] 'publication'
, [ @article = ] 'article'
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication =] 'publication'
Is the name of the publication that contains the article. publication is sysname, with no default.
[ @article=] 'article'
Is the name of the article that has its columns returned. article is sysname, with no default.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be specified when the requested article is published by a SQL Server Publisher.

Return Code Values


0 (columns that are not published) or 1 (columns that are published)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

column id int Identifier for the column.

column sysname Name of the column.

published bit Whether column is published:

0 = No

1 = Yes
COLUMN NAME DATA TYPE DESCRIPTION

publisher type sysname Data type of the column at the


Publisher.

subscriber type sysname Data type of the column at the


Subscriber.

Remarks
sp_helparticlecolumns is used in snapshot and transactional replication.
sp_helparticlecolumns is useful in checking a vertical partition.

Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role, or the publication access list
for the current publication can execute sp_helparticlecolumns.

See Also
Define and Modify a Column Filter
sp_addarticle (Transact-SQL)
sp_articlecolumn (Transact-SQL)
sp_changearticle (Transact-SQL)
sp_droparticle (Transact-SQL)
sp_droppublication (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helparticledts (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Used to get information on the correct custom task names to use when creating a transformation subscription
using Microsoft Visual Basic. This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_helparticledts [ @publication = ] 'publication', [ @article = ] 'article'

Arguments
[ @publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @article=] 'article'
Is the name of an article in the publication. article is sysname, with no default.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

pre_script_ignore_error_task_name sysname Task name for the programming task


that occurs before the snapshot data is
copied. Program execution should
continue if a script error is encountered.

pre_script_task_name sysname Task name for the programming task


that occurs before the snapshot data is
copied. Program execution halts on
error.

transformation_task_name sysname Task name for the programming task


when using a Data Driven Query task.

post_script_ignore_error_task_name sysname Task name for the programming task


that occurs after the snapshot data is
copied. Program execution should
continue if a script error is encountered.

post_script_task_name sysname Task name for the programming task


that occurs after the snapshot data is
copied. Program execution halts on
error.
Return Code Values
0 (success) or 1 (failure)

Remarks
sp_helparticledts is used in snapshot replication and transactional replication.
There are naming conventions, required by the replication agents, which must be followed when naming tasks in a
replication Data Transformation Services (DTS) program. For custom tasks, such as an Execute SQL task, the name
is a concatenated string consisting of the article name, a prefix, and an optional part. When writing the code, if you
are unsure what the task names should be, the result set gives the task names that should be used.

Permissions
Only members of the sysadmin fixed server role and the db_owner fixed database role can execute
sp_helparticledts.
sp_helpdatatypemap (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information on the defined data type mappings between Microsoft SQL Server and non- SQL Server
database management systems (DBMS). This stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_helpdatatypemap [ @source_dbms = ] 'source_dbms'
[ , [ @source_version = ] 'source_version' ]
[ , [ @source_type = ] 'source_type' ]
[ , [ @destination_dbms = ] 'destination_dbms' ]
[ , [ @destination_version = ] 'destination_version' ]
[ , [ @destination_type = ] 'destination_type' ]
[ , [ @defaults_only = ] defaults_only ]

Arguments
[ @source_dbms= ] 'source_dbms'
Is the name of the DBMS from which the data types are mapped. source_dbms is sysname, and can be one of the
following values.

VALUE DESCRIPTION

MSSQLSERVER The source is a SQL Server database.

ORACLE The source is an Oracle database.

[ @source_version= ] 'source_version'
Is the product version of the source DBMS. source_versionis varchar(10), and if not specified, the data type
mappings for all versions of the source DBMS are returned. Enables the result set to be filtered by the source
version of the DBMS.
[ @source_type= ] 'source_type'
Is the data type listed in the source DBMS. source_type is sysname, and if not specified, mappings for all data
types in the source DBMS are returned. Enables the result set to be filtered by data type in the source DBMS.
[ @destination_dbms = ] 'destination_dbms'
Is the name of the destination DBMS. destination_dbms is sysname, and can be one of the following values.

VALUE DESCRIPTION

MSSQLSERVER The destination is a SQL Server database.

ORACLE The destination is an Oracle database.


VALUE DESCRIPTION

DB2 The destination is an IBM DB2 database.

SYBASE The destination is a Sybase database.

[ @destination_version= ] 'destination_version'
Is the product version of the destination DBMS. destination_versionis varchar(10), and if not specified, mappings
for all versions of the destination DBMS are returned. Enables the result set to be filtered by the destination version
of the DBMS.
[ @destination_type= ] 'destination_type'
Is the data type listed in the destination DBMS. destination_typeis sysname, and if not specified, mappings for all
data types in the destination DBMS are returned. Enables the result set to be filtered by data type in the destination
DBMS.
[ @defaults_only= ] defaults_only
Is if only the default data type mappings are returned. defaults_only is bit, with a default of 0. 1 means that only
the default data type mappings are returned. 0 means that the default and any user-defined data type mappings
are returned.

Result Sets
COLUMN NAME DESCRIPTION

mapping_id Identifies a data type mapping.

source_dbms Is the name and version number of the source DBMS.

source_type Is the data type in the source DBMS.

destination_dbms Is the name of the destination DBMS.

destination_type Is the data type in the destination DBMS.

is_default Is if the mapping is a default or an alternative mapping. A


value of 0 indicates that this mapping is user-defined.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpdatatypemap defines data type mappings both from non-SQL Server Publishers and from SQL Server
Publishers to non- SQL Server Subscribers.
When the specified combination of source and destination DBMS is not supported, sp_helpdatatypemap returns
an empty result set.

Permissions
Only members of the sysadmin fixed server role at the Distributor or members of the db_owner fixed database
role on the distribution database can execute sp_helpdatatypemap.
See Also
sp_getdefaultdatatypemapping (Transact-SQL)
sp_setdefaultdatatypemapping (Transact-SQL)
sp_helpdistpublisher (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns properties of the Publishers using a Distributor. This stored procedure is executed at the Distributor on
any database.
Transact-SQL Syntax Conventions

Syntax
sp_helpdistpublisher [ [ @publisher=] 'publisher']
[ , [ @check_user = ] check_user

Arguments
[ @publisher= ] 'publisher'
Is the Publisher for which properties are returned. publisher is sysname, with a default of %.
[ @check_user= ] check_user
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

name sysname Name of Publisher.

distribution_db sysname Distribution database for the specified


Publisher.

security_mode int Security mode used by replication


agents to connect to the Publisher for
queued updating subscriptions, or with
a non- SQL Server Publisher.

0 = SQL Server Authentication

1 = Windows Authentication

login sysname Login name used by replication agents


to connect to the Publisher for queued
updating subscriptions, or with a non-
SQL Server Publisher.

password nvarchar(524) Password returned (in simple encrypted


form). Password is NULL for users other
than sysadmin.
COLUMN NAME DATA TYPE DESCRIPTION

active bit Whether a remote Publisher is using


the local server as a Distributor:

0 = No

1 = Yes

working_directory nvarchar(255) Name of the working directory.

trusted bit If the password is required when the


Publisher connects to the Distributor.
For Microsoft SQL Server 2005 and
later versions, this should always return
0, which means that the password is
required.

thirdparty_flag bit Whether the publication is enabled by


SQL Server or by a third party
application:

0 = SQL Server, Oracle, or Oracle


Gateway Publisher.

1 = Publisher has been integrated with


SQL Server using a third-party
application.

publisher_type sysname Type of Publisher; can be one of the


following:

MSSQLSERVER

ORACLE

ORACLE GATEWAY

publisher_data_source nvarchar(4000) Name of the OLE DB data source on


the Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpdistpublisher is used in all types of replication.
sp_helpdistpublisher will not display the publisher login or password in the result set for non-sysadmin logins.

Permissions
Members of the sysadmin fixed server role may execute sp_helpdistpublisher for any Publisher using the local
server as a Distributor. Members of the db_owner fixed database role or the replmonitor role in a distribution
database may execute sp_helpdistpublisher for any Publisher using that distribution database. Users in the
publication access list for a publication at the specified publisher may execute sp_helpdistpublisher. If publisher
is not specified, information is returned for all Publishers that the user has rights to access.
See Also
View and Modify Distributor and Publisher Properties
sp_adddistpublisher (Transact-SQL)
sp_changedistpublisher (Transact-SQL)
sp_dropdistpublisher (Transact-SQL)
sp_helpdistributiondb (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns properties of the specified distribution database. This stored procedure is executed at the Distributor on
the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_helpdistributiondb [ [ @database= ] 'database_name' ]

Arguments
[ @database=] 'database_name'
Is the database name for which properties are returned. database_name is sysname, with a default of % for all
databases associated with the Distributor and on which the user has permissions.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

name sysname Name of the distribution database.

min_distretention int Minimum retention period, in hours,


before transactions are deleted.

max_distretention int Maximum retention period, in hours,


before transactions are deleted.

history retention int Number of hours to retain history.

history_cleanup_agent sysname Name of the History Cleanup Agent.

distribution_cleanup_agent sysname Name of the Distribution Cleanup


Agent.

status int Internal use only.

data_folder nvarchar(255) Name of the directory used to store the


database files.

data_file nvarchar(255) Name of the database file.

data_file_size int Initial data file size in megabytes.


COLUMN NAME DATA TYPE DESCRIPTION

log_folder nvarchar(255) Name of the directory for the database


log file.

log_file nvarchar(255) Name of the log file.

log_file_size int Initial log file size in megabytes.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpdistributiondb is used in all types of replication.

Permissions
Members of the db_owner fixed database role or the replmonitor role in a distribution database and users in the
publication access list of a publication using the distribution database can execute sp_helpdistributiondb to
return file-related information. Members of the public role can execute sp_helpdistributiondb to return non-
file-related information for distribution databases to which they have access.

See Also
View and Modify Distributor and Publisher Properties
sp_adddistributiondb (Transact-SQL)
sp_changedistributiondb (Transact-SQL)
sp_dropdistributiondb (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpdistributor (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Lists information about the Distributor, distribution database, working directory, and Microsoft SQL Server Agent
user account. This stored procedure is executed at the Publisher on the publication database or any database.
Transact-SQL Syntax Conventions

Syntax
sp_helpdistributor [ [ @distributor= ] 'distributor' OUTPUT ]
[ , [ @distribdb= ] 'distribdb' OUTPUT ]
[ , [ @directory= ] 'directory' OUTPUT ]
[ , [ @account= ] 'account' OUTPUT ]
[ , [ @min_distretention= ] min_distretention OUTPUT ]
[ , [ @max_distretention= ] max_distretention OUTPUT ]
[ , [ @history_retention= ] history_retention OUTPUT ]
[ , [ @history_cleanupagent= ] 'history_cleanupagent' OUTPUT ]
[ , [ @distrib_cleanupagent = ] 'distrib_cleanupagent' OUTPUT ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @local = ] 'local' ]
[ , [ @rpcsrvname= ] 'rpcsrvname' OUTPUT ]
[ , [ @publisher_type = ] 'publisher_type' OUTPUT ]

Arguments
[ @distributor=] 'distributor' OUTPUT
Is the name of the Distributor. Distributor is sysname, with a default of %, which is the only value that returns a
result set.
[ @distribdb=] 'distribdb' OUTPUT
Is the name of the distribution database. distribdb is sysname, with a default of %, which is the only value that
returns a result set.
[ @directory=] 'directory' OUTPUT
Is the working directory. directory is nvarchar(255), with a default of %, which is the only value that returns a
result set.
[ @account=] 'account' OUTPUT
Is the Microsoft Windows user account. accountis nvarchar(255), with a default of %, which is the only value that
returns a result set.
[ @min_distretention=] min_distretentionOUTPUT
Is the minimum distribution retention period, in hours. min_distretention is int, with a default of -1.
[ @max_distretention=] max_distretentionOUTPUT
Is the maximum distribution retention period, in hours. max_distretention is int, with a default of -1.
[ @history_retention=] history_retentionOUTPUT
Is the history retention period, in hours. history_retention is int, with a default of -1.
[ @history_cleanupagent=] 'history_cleanupagent' OUTPUT
Is the name of the history cleanup agent. history_cleanupagent is nvarchar(100), with a default of %, which is
the only value that returns a result set.
[ @distrib_cleanupagent =] 'distrib_cleanupagent' OUTPUT
Is the name of the distribution cleanup agent. distrib_cleanupagent is nvarchar(100), with a default of %, which
is the only value that returns a result set.
[ @publisher=] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of NULL.
[ @local=] 'local'
Is whether SQL Server should get local server values. local is nvarchar(5), with a default of NULL.
[ @rpcsrvname=] 'rpcsrvname' OUTPUT
Is the name of the server that issues remote procedure calls. rpcsrvname is sysname, with a default of %, which
is the only value that returns a result set.
[ @publisher_type= ] 'publisher_type' OUTPUT
Is the publisher type of the Publisher. publisher_type is sysname, with a default of %, which is the only value that
returns a result set.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

distributor sysname Name of the Distributor.

distribution database sysname Name of the distribution database.

directory nvarchar(255) Name of the working directory.

account nvarchar(255) Name of the Windows user account.

min distrib retention int Minimum distribution retention period.

max distrib retention int Maximum distribution retention period.

history retention int History retention period.

history cleanup agent nvarchar(100) Name of the History Cleanup Agent.

distribution cleanup agent nvarchar(100) Name of the Distribution Cleanup


Agent.

rpc server name sysname Name of the remote or local


Distributor.

rpc login name sysname Login used for remote procedure calls
to the remote Distributor.
COLUMN NAME DATA TYPE DESCRIPTION

publisher type sysname Type of Publisher; can be one of the


following:

MSSQLSERVER

ORACLE

ORACLE GATEWAY

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpdistributor is used in all types of replication.
If one or more output parameters are specified when executing sp_helpdistributor, all output parameters set to
NULL are assigned values on exit and no result set is returned. If no output parameters are specified, a result set
is returned.

Permissions
The following result set columns or output parameters are returned to members of the sysadmin fixed server
role at the Publisher and the db_owner fixed database role on the publication database:

RESULT SET COLUMN OUTPUT PARAMETER

account @account

min distrib retention @min_distretention

max distrib retention @max_distretention

history retention @history_retention

history cleanup agent @history_cleanupagent

distribution cleanup agent @distrib_cleanupagent

rpc login name none

The following result set column is returned to users in the publication access list for a publication at the
Distributor:
directory
The following result set columns are returned to all users.

RESULT SET COLUMN OUTPUT PARAMETER

distributor @distributor
RESULT SET COLUMN OUTPUT PARAMETER

distribution database @distribdb

rpc server name @rpcsrvname

publisher type @publisher_type

See Also
View and Modify Distributor and Publisher Properties
sp_adddistpublisher (Transact-SQL)
sp_dropdistpublisher (Transact-SQL)
sp_helpdistributor_properties (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns Distributor properties. This stored procedure is executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_helpdistributor_properties

Result Set
COLUMN NAME DATA TYPE DESCRIPTION

heartbeat_interval int The maximum number of minutes that


an agent can go without logging a
progress message.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpdistributor_properties is used with all types of replication.

Permissions
Only members of the sysadmin fixed server role, members of the db_owner or replmonitor fixed database role
on the distribution database, and users in the publication access list (PAL) for a publication that uses this
Distributor can execute sp_helpdistributor_properties.

See Also
sp_changedistributor_property (Transact-SQL)
sp_helpdynamicsnapshot_job (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information on agent jobs that generate filtered data snapshots. This stored procedure is executed at the
Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_helpdynamicsnapshot_job [ [ @publication = ] 'publication' ]
[ , [ @dynamic_snapshot_jobname = ] 'dynamic_snapshot_jobname' ]
[ , [ @dynamic_snapshot_jobid = ] 'dynamic_snapshot_jobid' ]

Arguments
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with a default of %, which returns information on all
filtered data snapshot jobs that match the specified dynamic_snapshot_jobidand dynamic_snapshot_jobnamefor
all publications.
[ @dynamic_snapshot_jobname = ] 'dynamic_snapshot_jobname'
Is the name of a filtered data snapshot job. dynamic_snapshot_jobnameis sysname, with default of %', which
returns all dynamic jobs for a publication with the specified dynamic_snapshot_jobid. If a job name was not
explicitly specified when the job was created, the job name is in the following format:

'dyn_' + <name of the standard snapshot job> + <GUID>

[ @dynamic_snapshot_jobid = ] 'dynamic_snapshot_jobid'
Is an identifier for a filtered data snapshot job. dynamic_snapshot_jobidis uniqueidentifier, with default of NULL,
which returns all snapshot jobs that match the specified dynamic_snapshot_jobname.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

id int Identifies the filtered data snapshot job.

job_name sysname Name of the filtered data snapshot job.

job_id uniqueidentifier Identifies the Microsoft SQL Server


Agent job at the Distributor.
COLUMN NAME DATA TYPE DESCRIPTION

dynamic_filter_login sysname Value used for evaluating the


SUSER_SNAME function in a
parameterized row filter defined for the
publication.

dynamic_filter_hostname sysname Value used for evaluating the


HOST_NAME function in a
parameterized row filter defined for the
publication.

dynamic_snapshot_location nvarchar(255) Path to the folder where the snapshot


files are read from if a parameterized
row filter is used.

frequency_type int Is the frequency with which the agent is


scheduled to run, which can be one of
these values.

1 = One time

2 = On demand

4 = Daily

8 = Weekly

16 = Monthly

32 = Monthly relative

64 = Autostart

128 = Recurring

frequency_interval int The days that the agent runs, which can
be one of these values.

1 = Sunday

2 = Monday

3 = Tuesday

4 = Wednesday

5 = Thursday

6 = Friday

7 = Saturday

8 = Day

9 = Weekdays

10 = Weekend days
COLUMN NAME DATA TYPE DESCRIPTION

frequency_subday_type int Is the type that defines how often the


agent runs when frequency_type is 4
(daily), and can be one of these values.

1 = At the specified time

2 = Seconds

4 = Minutes

8 = Hours

frequency_subday_interval int Number of intervals of


frequency_subday_type that occur
between scheduled execution of the
agent.

frequency_relative_interval int Is the week that the agent runs in a


given month when frequency_type is 32
(monthly relative), and can be one of
these values.

1 = First

2 = Second

4 = Third

8 = Fourth

16 = Last

frequency_recurrence_factor int Number of weeks or months between


the scheduled execution of the agent.

active_start_date int Date when the agent is first scheduled


to run, formatted as YYYYMMDD.

active_end_date int Date when the agent is last scheduled


to run, formatted as YYYYMMDD.

active_start_time int Time when the agent is first scheduled


to run, formatted as HHMMSS.

active_end_time int Time when the agent is last scheduled


to run, formatted as HHMMSS.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpdynamicsnapshot_job is used in merge replication.
If all of the default parameter values are used, information on all partitioned data snapshot jobs for the entire
publication database is returned.
Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role, and the publication access list
for the publication can execute sp_helpdynamicsnapshot_job.

See Also
System Stored Procedures (Transact-SQL)
sp_helplogreader_agent (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns properties of the Log Reader Agent job for the publication database. This stored procedure is executed at
the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_helplogreader_agent [ [ @publisher = ] 'publisher' ]

Arguments
[ @publisher= ] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of NULL.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

id int ID of the agent.

name nvarchar(100) Name of the agent.

publisher_security_mode smallint Security mode used by the agent when


connecting to the Publisher, which can
be one of the following:

0 = SQL Server Authentication

1 = Windows Authentication.

publisher_login sysname Login used when connecting to the


Publisher.

publisher_password nvarchar(524) For security reasons, a value of


*********\* is always returned.

job_id uniqueidentifier Unique ID of the agent job.

job_login nvarchar(512) Is the Windows account under which


the Log Reader Agent runs, which is
returned in the format
domain\username.
COLUMN NAME DATA TYPE DESCRIPTION

job_password sysname For security reasons, a value of


*********\* is always returned.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helplogreader_agent is used in transactional replication.

Permissions
Only members of the sysadmin fixed server role at the Publisher or members of the db_owner fixed database
role on the publication database can execute sp_helplogreader_agent.

See Also
View and Modify Replication Security Settings
sp_addlogreader_agent (Transact-SQL)
sp_changelogreader_agent (Transact-SQL)
sp_helpmergealternatepublisher (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a list of all servers enabled as alternate Publishers for merge publications. This stored procedure is
executed at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_helpmergealternatepublisher [ @publisher = ] 'publisher', [ @publisher_db = ] 'publisher_db', [
@publication = ] 'publication'

Arguments
[ @publisher=] 'publisher'
Is the name of the alternate Publisher.publisher is sysname, with no default.
[ @publisher_db=] 'publisher_db'
Is the name of the publication database.publisher_db is sysname, with no default.
[ @publication=] 'publication'
Is the name of the publication.publication is sysname, with no default.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

alternate_publisher sysname Name of the alternate Publisher.

alternate_publisher_db sysname Name of the publication database.

alternate_publication sysname Name of the publication.

alternate_distributor sysname Name of the distributor.

friendly_name nvarchar(255) Description of the alternate Publisher.

enabled bit Specifies if the server is an alternate


Publisher. 1 specifies that the Publisher
is enabled as an alternate Publisher. 0
specifies that it is not enabled.

Return Code Values


0 (success) or 1 (failure)
Remarks
sp_helpmergealternatepublisher is used in merge replication.
During every merge session, the system queries both the Publisher and Subscriber for each one's list of alternate
publishers. The merge process adds or drops entries in the list of alternate publishers, the result of which is that the
list of alternate publishers at both the Subscriber and Publisher match.

Permissions
Only members of the publication access list for the publication can execute sp_helpmergealternatepublisher.

See Also
System Stored Procedures (Transact-SQL)
sp_helpmergearticle (Transact-SQL)
11/21/2017 • 5 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about an article. This stored procedure is executed at the Publisher on the publication
database or at a republishing Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_helpmergearticle [ [ @publication = ] 'publication' ]
[ , [ @article= ] 'article' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication about which to retrieve information. publicationis sysname, with a default of %,
which returns information about all merge articles contained in all publications in the current database.
[ @article=] 'article'
Is the name of the article for which to return information. articleis sysname, with a default of %, which returns
information about all merge articles in the given publication.

Result Set
COLUMN NAME DATA TYPE DESCRIPTION

id int Article identifier.

name sysname Name of the article.

source_owner sysname Name of the owner of the source


object.

source_object sysname Name of the source object from which


to add the article.

sync_object_owner sysname Name of the owner of the view that


defines the published article.

sync_object sysname Name of the custom object used to


establish the initial data for the
partition.

description nvarchar(255) Description of the article.


COLUMN NAME DATA TYPE DESCRIPTION

status tinyint Status of the article, which can be one


of the following:

1 = inactive

2 = active

5 = data definition language (DDL)


operation pending

6 = DDL operation with a newly


generated snapshot

Note: When an article is reinitialized,


values of 5 and 6 are changed to 2.

creation_script nvarchar(255) Path and name of an optional article


schema script used to create the article
in the subscription database.

conflict_table nvarchar(270) Name of the table storing the insert or


update conflicts.

article_resolver nvarchar(255) Custom resolver for the article.

subset_filterclause nvarchar(1000) WHERE clause specifying the horizontal


filtering.

pre_creation_command tinyint Pre-creation method, which can be one


of the following:

0 = none

1 = drop

2 = delete

3 = truncate

schema_option binary(8) Bitmap of the schema generation


option for the article. For information
about this bitmap option, see
sp_addmergearticle or
sp_changemergearticle.

type smallint Type of article, which can be one of the


following:

10 = table

32 = stored procedure

64 = view or indexed view

128 = user defined function

160 = synonym schema only


COLUMN NAME DATA TYPE DESCRIPTION

column_tracking int Setting for column-level tracking; where


1 means that column-level tracking is
on, and 0 means that column-level
tracking is off.

resolver_info nvarchar(255) Name of the article resolver.

vertical_partition bit If the article is vertically partitioned;


where 1 means that the article is
vertically partitioned, and 0 means that
it is not.

destination_owner sysname Owner of the destination object.


Applicable to merge stored procedures,
views, and user-defined function (UDF)
schema articles only.

identity_support int If automatic identity range handling is


enabled; where 1 is enabled and 0 is
disabled.

pub_identity_range bigint The range size to use when assigning


new identity values. For more
information, see the "Merge
Replication" section of Replicate Identity
Columns.

identity_range bigint The range size to use when assigning


new identity values. For more
information, see the "Merge
Replication" section of Replicate Identity
Columns.

threshold int Percentage value used for Subscribers


running SQL Server Compact or
previous versions of SQL Server.
threshold controls when the Merge
Agent assigns a new identity range.
When the percentage of values
specified in threshold is used, the
Merge Agent creates a new identity
range. For more information, see the
"Merge Replication" section of Replicate
Identity Columns.

verify_resolver_signature int If a digital signature is verified before


using a resolver in merge replication;
where 0 means that the signature is
not verified, and 1 means that the
signature is verified to see if it is from a
trusted source.

destination_object sysname Name of the destination object.


Applicable to merge stored procedures,
views, and UDF schema articles only.
COLUMN NAME DATA TYPE DESCRIPTION

allow_interactive_resolver int If the Interactive Resolver is used on an


article; where 1 means that this resolver
is used, and 0 means that it is not used.

fast_multicol_updateproc int Enables or disables the Merge Agent to


apply changes to multiple columns in
the same row in one UPDATE
statement; where 1 means that
multiple columns are updated in one
statement, and 0 means that separate
UPDATE statements are issues for each
updated column.

check_permissions int Integer value that represents the


bitmap of the table-level permissions
that are verified. For a list of possible
values, see sp_addmergearticle
(Transact-SQL).

processing_order int The order in which data changes are


applied to articles in a publication.

upload_options tinyint Defines restrictions on updates made at


a Subscriber with a client subscription,
which can be one of the following
values.

0 = There are no restrictions on


updates made at a Subscriber with a
client subscription; all changes are
uploaded to the Publisher.

1 = Changes are allowed at a


Subscriber with a client subscription,
but they are not uploaded to the
Publisher.

2 = Changes are not allowed at a


Subscriber with a client subscription.

For more information, see Optimize


Merge Replication Performance with
Download-Only Articles.

identityrangemanagementoption int If automatic identity range handling is


enabled; where 1 is enabled and 0 is
disabled.

delete_tracking bit If deletes are replicated; where 1 means


that deletes are replicated, and 0
means that they are not.

compensate_for_errors bit Indicates if compensating actions are


taken when errors are encountered
during synchronization; where 1
indicates that compensating actions are
taken, and 0 means that compensating
actions are not taken.
COLUMN NAME DATA TYPE DESCRIPTION

partition_options tinyint Defines the way in which data in the


article is partitioned, which enables
performance optimizations when all
rows belong in only one partition or in
only one subscription.
partition_options can be one of the
following values.

0 = The filtering for the article either is


static or does not yield a unique subset
of data for each partition; that is, it is
an "overlapping" partition.

1 = The partitions are overlapping, and


data manipulation language (DML)
updates made at the Subscriber cannot
change the partition to which a row
belongs.

2 = The filtering for the article yields


non-overlapping partitions, but
multiple Subscribers can receive the
same partition.

3 = The filtering for the article yields


non-overlapping partitions that are
unique for each subscription.

artid uniqueidentifier An identifier that uniquely identifies the


article.

pubid uniqueidentifier An identifier that uniquely identifies the


publication in which the article is
published.

stream_blob_columns bit Is if the data stream optimization is


being used when replicating binary
large object columns. 1 means that the
optimization is being used, and 0
means that the optimization is not
being used.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpmergearticle is used in merge replication.

Permissions
Only members of the db_owner fixed database role in the publication database, the replmonitor role in the
distribution database, or the publication access list for a publication can execute sp_helpmergearticle.

Example
DECLARE @publication AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';

USE [AdventureWorks2012]
EXEC sp_helpmergearticle
@publication = @publication;
GO

See Also
View and Modify Article Properties
sp_addmergearticle (Transact-SQL)
sp_changemergearticle (Transact-SQL)
sp_dropmergearticle (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_helpmergearticlecolumn (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the list of columns in the specified table or view article for a merge publication. Because stored procedures
do not have columns, this stored procedure returns an error if a stored procedure is specified as the article. This
stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_helpmergearticlecolumn [ @publication = ] 'publication' ]
, [ @article= ] 'article' ]

Arguments
[ @publication=] 'publication'
Is the name of the publication.publication is sysname, with no default.
[ @article=] 'article'
Is the name of a table or view that is the article to retrieve information on.article is sysname, with no default.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

column_id sysname Identifies the column.

column_name sysname Is the name of the column for a table or


view.

published bit Specifies if the column name is


published.

1 specifies that the column is being


published.

0 specifies that it is not published.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpmergearticlecolumn is used in merge replication.
Permissions
Only members of the replmonitor fixed database role in the distribution database or the publication access list for
the publication can execute sp_helpmergearticlecolumn.

See Also
System Stored Procedures (Transact-SQL)
sp_helpmergearticleconflicts (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the articles in the publication that have conflicts. This stored procedure is executed at the Publisher on the
publication database, or at the Subscriber on the merge subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_helpmergearticleconflicts [ [ @publication = ] 'publication' ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @publisher_db = ] 'publsher_db' ]

Arguments
[ @publication=] 'publication'
Is the name of the merge publication.publication is sysname, with a default of %, which returns all articles in the
database that have conflicts.
[ @publisher=] 'publisher'
Is the name of the Publisher.publisher is sysname, with a default of NULL.
[ @publisher_db=] 'publisher_db'
Is the name of the publisher database.publisher_db is sysname, with a default of NULL.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

article sysname Name of the article.

source_owner sysname Owner of the source object.

source_object nvarchar(386) Name of the source object.

conflict_table nvarchar(258) Name of the table storing the insert or


update conflicts.

guidcolname sysname Name of the RowGuidCol for the source


object.

centralized_conflicts int Whether conflict records are stored on


the given Publisher.

If the article has only delete conflicts and no conflict_table rows, the name of the conflict_table in the result set
is NULL.
Return Code Values
0 (success) or 1 (failure)

Remarks
sp_helpmergearticleconflicts is used in merge replication.

Permissions
Only members of the sysadmin fixed server role and the db_owner fixed database role can execute
sp_helpmergearticleconflicts.

See Also
System Stored Procedures (Transact-SQL)
sp_helpmergeconflictrows (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the rows in the specified conflict table. This stored procedure is run on the computer where the conflict
table is stored.
Transact-SQL Syntax Conventions

Syntax
sp_helpmergeconflictrows [ [ @publication = ] 'publication' ]
, [ @conflict_table = ] 'conflict_table'
[ , [ @publisher = ] 'publisher' ]
[ , [ @publisher_db = ] 'publsher_db' ]
[ , [ @logical_record_conflicts = ] logical_record_conflicts ]

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of %. If the publication is specified, all
conflicts qualified by the publication are returned. For example, if the MSmerge_conflict_Customers table has
conflict rows for the WA and the CA publications, passing in a publication name CA retrieves conflicts that pertain
to the CA publication.
[ @conflict_table=] 'conflict_table'
Is the name of the conflict table. conflict_table is sysname, with no default. In Microsoft SQL Server 2005 and later
versions, conflict tables are named using the format names with MSmerge_conflict_publication_*article*, with
one table for each published article.
[ @publisher=] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of NULL.
[ @publisher_db=] 'publisher_db'
Is the name of the publisher database.publisher_db is sysname, with a default of NULL.
[ @logical_record_conflicts= ] logical_record_conflicts
Indicates whether the result set contains information about logical record conflicts. logical_record_conflicts is int,
with a default value of 0. 1 means that logical record conflict information is returned.

Result Sets
sp_helpmergeconflictrows returns a result set consisting of the base table structure and these additional
columns.

COLUMN NAME DATA TYPE DESCRIPTION

origin_datasource varchar(255) Origin of the conflict.


COLUMN NAME DATA TYPE DESCRIPTION

conflict_type int Code indicating the type of conflict:

1 = Update Conflict: The conflict is


detected at the row level.

2 = Column Update Conflict: The


conflict detected at the column level.

3 = Update Delete Wins Conflict: The


delete wins the conflict.

4 = Update Wins Delete Conflict: The


deleted rowguid that loses the conflict is
recorded in this table.

5 = Upload Insert Failed: The insert


from Subscriber could not be applied at
the Publisher.

6 = Download Insert Failed: The insert


from Publisher could not be applied at
the Subscriber.

7 = Upload Delete Failed: The delete at


Subscriber could not be uploaded to the
Publisher.

8 = Download Delete Failed: The delete


at Publisher could not be downloaded
to the Subscriber.

9 = Upload Update Failed: The update


at Subscriber could not be applied at
the Publisher.

10 = Download Update Failed: The


update at Publisher could not be
applied to the Subscriber.

12 = Logical Record Update Wins


Delete: The deleted logical record that
loses the conflict is recorded in this
table.

13 = Logical Record Conflict Insert


Update: Insert to a logical record
conflicts with an update.

14 = Logical Record Delete Wins


Update Conflict: The updated logical
record that loses the conflict is recorded
in this table.

reason_code int Error code that can be context-sensitive.

reason_text varchar(720) Error description that can be context-


sensitive.

pubid uniqueidentifier Publication identifier.


COLUMN NAME DATA TYPE DESCRIPTION

MSrepl_create_time datetime Time the conflict information was


added.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpmergeconflictrows is used in merge replication.

Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role, and the replmonitor role in
the distribution database can execute sp_helpmergeconflictrows.

See Also
View Conflict Information for Merge Publications (Replication Transact-SQL Programming)
Replication Stored Procedures (Transact-SQL)
sp_helpmergedeleteconflictrows (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns information on data rows that lost delete conflicts. This stored procedure is executed at the Publisher on
the publication database or at the Subscriber on the subscription database when decentralized conflict logging is
used.
Transact-SQL Syntax Conventions

Syntax
sp_helpmergedeleteconflictrows [ [ @publication = ] 'publication']
[ , [ @source_object = ] 'source_object']
[ , [ @publisher = ] 'publisher'
[ , [ @publisher_db = ] 'publsher_db'

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of %. If the publication is specified, all
conflicts qualified by the publication are returned.
[ @source_object=] 'source_object'
Is the name of the source object. source_object is nvarchar(386), with a default of NULL.
[ @publisher=] 'publisher'
Is the name of the Publisher.publisher is sysname, with a default of NULL.
[ @publisher_db=] 'publisher_db'
Is the name of the publisher database.publisher_db is sysname, with a default of NULL.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

source_object nvarchar(386) Source object for the delete conflict.

rowguid uniqueidentifier Row identifier for the delete conflict.


COLUMN NAME DATA TYPE DESCRIPTION

conflict_type int Code indicating type of conflict:

1 = UpdateConflict: Conflict is detected


at the row level.

2 = ColumnUpdateConflict: Conflict
detected at the column level.

3 = UpdateDeleteWinsConflict: Delete
wins the conflict.

4 = UpdateWinsDeleteConflict: The
deleted rowguid that loses the conflict is
recorded in this table.

5 = UploadInsertFailed: Insert from


Subscriber could not be applied at the
Publisher.

6 = DownloadInsertFailed: Insert from


Publisher could not be applied at the
Subscriber.

7 = UploadDeleteFailed: Delete at
Subscriber could not be uploaded to the
Publisher.

8 = DownloadDeleteFailed: Delete at
Publisher could not be downloaded to
the Subscriber.

9 = UploadUpdateFailed: Update at
Subscriber could not be applied at the
Publisher.

10 = DownloadUpdateFailed: Update at
Publisher could not be applied to the
Subscriber.

reason_code Int Error code that can be context-sensitive.

reason_text varchar(720) Error description that can be context-


sensitive.

origin_datasource varchar(255) Origin of the conflict.

pubid uniqueidentifier Publication identifier.

MSrepl_create_time datetime Time the conflict information was


added.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpmergedeleteconflictrows is used in merge replication.
Permissions
Only members of the sysadmin fixed server role and the db_owner fixed database role can execute
sp_helpmergedeleteconflictrows.

See Also
System Stored Procedures (Transact-SQL)
sp_helpmergefilter (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about merge filters. This stored procedure is executed at the Publisher on any database.
Transact-SQL Syntax Conventions

Syntax
sp_helpmergefilter [ @publication= ] 'publication'
[ , [ @article= ] 'article']
[ , [ @filtername= ] 'filtername']

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @article=] 'article'
Is the name of the article. article is sysname, with a default of %, which returns the names of all articles.
[ @filtername=] 'filtername'
Is the name of the filter about which to return information. filtername is sysname, with a default of %, which
returns information about all the filters defined on the article or publication.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

join_filterid int ID of the join filter.

filtername sysname Name of the filter.

join article name sysname Name of the join article.

join_filterclause nvarchar(2000) Filter clause qualifying the join.

join_unique_key int Whether the join is on a unique key.

base table owner sysname Name of the owner of the base table.

base table name sysname Name of the base table.

join table owner sysname Name of the owner of the table being
joined to the base table.
COLUMN NAME DATA TYPE DESCRIPTION

join table name sysname Name of the table being joined to the
base table.

article name sysname Name of the table article being joined


to the base table.

filter_type tinyint Type of merge filter, which can be one


of the following:

1 = join filter only

2 = logical record relationship

3 = both

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpmergefilter is used in merge replication.

Permissions
Only members of the sysadmin fixed server role and the db_owner fixed database role can execute
sp_helpmergefilter.

See Also
sp_addmergefilter (Transact-SQL)
sp_changemergefilter (Transact-SQL)
sp_dropmergefilter (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpmergepartition (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns partition information for the specified merge publication. This stored procedure is executed at the
Publisher on any database.
Transact-SQL Syntax Conventions

Syntax
sp_helpmergepartition [ @publication= ] 'publication'
[ , [ @suser_sname = ] 'suser_sname' ]
[ , [ @host_name = ] 'host_name' ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @suser_sname= ] 'suser_sname'
Is the SUSER_SNAME value used to define a partition. suser_sname is sysname, with a default value of NULL.
Supply this parameter to limit the result set to only partitions where SUSER_SNAME resolves to the supplied value.

NOTE
When suser_sname is supplied, host_name must be NULL

[ @host_name= ] 'host_name'
Is the HOST_NAME value used to define a partition. host_name is sysname, with a default value of NULL. Supply
this parameter to limit the result set to only partitions where HOST_NAME resolves to the supplied value.

NOTE
When suser_sname is supplied, host_name must be NULL

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

partition int Identifies the Subscriber partition.

host_name sysname Value used when creating the partition


for a subscription that is filtered by the
value of the HOST_NAME function at
the Subscriber.
COLUMN NAME DATA TYPE DESCRIPTION

suser_sname sysname Value used when creating the partition


for a subscription that is filtered by the
value of the SUSER_SNAME function at
the Subscriber.

dynamic_snapshot_location nvarchar(255) Location of the filtered data snapshot


for the Subscriber's partition.

date_refreshed datetime Last date that the snapshot job was run
to generate the filtered data snapshot
for the partition.

dynamic_snapshot_jobid uniqueidentifier Identifies the job that creates the


filtered data snapshot for a partition.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpmergepartition is used in merge replication.

Permissions
Only members of the sysadmin fixed server role and the db_owner fixed database role can execute
sp_helpmergepartition.

See Also
sp_addmergepartition (Transact-SQL)
sp_dropmergepartition (Transact-SQL)
sp_helpmergepublication (Transact-SQL)
11/21/2017 • 8 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about a merge publication. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_helpmergepublication [ [ @publication = ] 'publication' ]
[ , [ @found = ] 'found' OUTPUT ]
[ , [ @publication_id = ] 'publication_id' OUTPUT ]
[ , [ @reserved = ] 'reserved' ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @publisher_db = ] 'publisher_db' ]

Arguments
[ @publication**=** ] 'publication'
The name of the publication. publicationis sysname, with a default of %, which returns information about all
merge publications in the current database.
[ @found**=** ] 'found' OUTPUT
A flag to indicate returning rows. foundis int and an OUTPUT parameter, with a default of NULL. 1 indicates the
publication is found. 0 indicates the publication is not found.
[ @publication_id**=**] 'publication_id' OUTPUT
The publication identification number. publication_id is uniqueidentifier and an OUTPUT parameter, with a
default of NULL.
[ @reserved**=**] 'reserved'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed. reserved is
nvarchar(20), with a default of NULL.
[ @publisher**=** ] 'publisher'
The name of the Publisher. publisher is sysname, with a default of NULL.
[@publisher_db**=** ] 'publisher_db'
The name of the publication database. publisher_db is sysname, with a default of NULL.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

id int Sequential order of the publication in


the result set list.
COLUMN NAME DATA TYPE DESCRIPTION

name sysname Name of the publication.

description nvarchar(255) Description of the publication.

status tinyint Indicates when publication data is


available.

retention int Amount of time to save metadata


about changes for articles in the
publication. The units for this time
period can be days, weeks, months, or
years. For information about units, see
the retention_period_unit column.

sync_mode tinyint Synchronization mode of this


publication:

0 = Native bulk copy program (bcp


utility)

1 = Character bulk copy

allow_push int Determines whether push subscriptions


can be created for the given
publication. 0 means that a push
subscription is not allowed.

allow_pull int Determines whether pull subscriptions


can be created for the given
publication. 0 means that a pull
subscription is not allowed.

allow_anonymous int Determines whether anonymous


subscriptions can be created for the
given publication. 0 means that an
anonymous subscription is not allowed.

centralized_conflicts int Determines whether conflict records are


stored on the given Publisher:

0 = conflict records are stored at both


the publisher and at the subscriber that
caused the conflict.

1 = all conflict records are stored at the


Publisher.

priority float(8) Priority of the loop-back subscription.

snapshot_ready tinyint Indicates whether the snapshot of this


publication is ready:

0 = Snapshot is ready for use.

1 = Snapshot is not ready for use.


COLUMN NAME DATA TYPE DESCRIPTION

publication_type int Type of publication:

0 = Snapshot.

1 = Transactional.

2 = Merge.

pubid uniqueidentifier Unique identifier of this publication.

snapshot_jobid binary(16) Job ID of the Snapshot Agent. To


obtain the entry for the snapshot job in
the sysjobs system table, you must
convert this hexadecimal value to
uniqueidentifier.

enabled_for_internet int Determines whether the publication is


enabled for the Internet. If 1, the
synchronization files for the publication
are put into the
C:\Program Files\Microsoft SQL
Server\MSSQL\Repldata\Ftp
directory. The user must create the File
Transfer Protocol (FTP) directory. If 0,
the publication is not enabled for
Internet access.

dynamic_filter int Indicates shether a parameterized row


filter is used. 0 means a parameterized
row filter is not used.

has_subscription bit Indicates whether the publication has


any subscriptions. 0 means there are
currently no subscriptions to this
publication.

snapshot_in_default_folder bit Specifies if the snapshot files are stored


in the default folder.

If 1, snapshot files can be found in the


default folder.

If 0, snapshot files are stored in the


alternate location specified by
alt_snapshot_folder. Alternate
locations can be on another server, on
a network drive, or on a removable
media (such as CD-ROM or removable
disks). You can also save the snapshot
files to a FTP site, for retrieval by the
Subscriber at a later time.

Note: This parameter can be true and


still have a location in the
alt_snapshot_folder parameter. That
combination specifies that the snapshot
files are stored in both the default and
alternate locations.
COLUMN NAME DATA TYPE DESCRIPTION

alt_snapshot_folder nvarchar(255) Specifies the location of the alternate


folder for the snapshot.

pre_snapshot_script nvarchar(255) Specifies a pointer to an .sql file that


the Merge Agent runs before any of
the replicated object scripts when
applying the snapshot at a Subscriber.

post_snapshot_script nvarchar(255) Specifies a pointer to an .sql file that


the Merge Agent runs after all the
other replicated object scripts and data
have been applied during an initial
synchronization.

compress_snapshot bit Specifies that the snapshot that is


written to the alt_snapshot_folder
location is compressed into the
Microsoft CAB format.

ftp_address sysname Is the network address of the FTP


service for the Distributor. Specifies
where publication snapshot files are
located for the Merge Agent to pick up.

ftp_port int Is the port number of the FTP service


for the Distributor. ftp_port has a
default of 21. Specifies where the
publication snapshot files are located
for the Merge Agent to pick up.

ftp_subdirectory nvarchar(255) Specifies where the snapshot files are


available for the Merge Agent to pick
up when the snapshot is delivered
using FTP.

ftp_login sysname Is the username used to connect to the


FTP service.

conflict_retention int Specifies the retention period, in days,


for which conflicts are retained. After
the specified number of days has
passed, the conflict row is purged from
the conflict table.
COLUMN NAME DATA TYPE DESCRIPTION

keep_partition_changes int Specifies whether synchronization


optimization is occurring for this
publication. keep_partition_changes
has a default of 0. A value of 0 means
that synchronization is not optimized,
and the partitions sent to all
Subscribers are verified when data
changes in a partition.

1 means that synchronization is


optimized, and only Subscribers having
rows in the changed partition are
affected.

Note: By default, merge publications


use precomputed partitions, which
provides a greater degree of
optimization than this option. For more
information, see Parameterized Row
Filters and Optimize Parameterized
Filter Performance with Precomputed
Partitions.

allow_subscription_copy int Specifies whether the ability to copy the


subscription databases that subscribe
to this publication has been enabled. A
value of 0 means copying is not
allowed.

allow_synctoalternate int Specifies whether an alternate


synchronization partner is allowed to
synchronize with this Publisher. A value
of 0 means a synchronization partner is
not allowed.

validate_subscriber_info nvarchar(500) Lists the functions that are being used


to retrieve Subscriber information and
validate the parameterized row filtering
criteria on the Subscriber. Assists in
verifying that the information is
partitioned consistently with each
merge.

backward_comp_level int Database compatibility level, and can be


one of the following:

90 = SQL Server 2005

90 = SQL Server 2005 SP1

90 = SQL Server 2005 SP2

100 = SQL Server 2008


COLUMN NAME DATA TYPE DESCRIPTION

publish_to_activedirectory bit Specifies if the publication information


is published to Active Directory. A value
of 0 means the publication information
is not available from Active Directory.

This parameter has been deprecated


and is only supported for the backward
compatibility of scripts. You can no
longer add publication information to
Active Directory.

max_concurrent_merge int The number of concurrent merge


processes. If 0, there is no limit to the
number of concurrent merge processes
running at any given time.

max_concurrent_dynamic_snapshots int The maximum number of concurrent


filtered data snapshot sessions that can
be running against the merge
publication. If 0, there is no limit to the
maximum number of concurrent filtered
data snapshot sessions that can run
simultaneously against the publication
at any given time.

use_partition_groups int Determines if precomputed partitions


are used. A value of 1 means that
precomputed partitions are used.

num_of_articles int Number of articles in the publication.

replicate_ddl int If schema changes to published tables


are replicated. A value of 1 means that
schema changes are replicated.

publication_number smallint Number assigned to this publication.

allow_subscriber_initiated_snapshot bit Determines if Subscribers can initiate


the filtered data snapshot generation
process. A value of 1 means that
Subscribers can initiate the snapshot
process.

allow_web_synchronization bit Determines if the publication is enabled


for Web synchronization. A value of 1
means that Web synchronization is
enabled.

web_synchronization_url nvarchar(500) Internet URL that is used for Web


synchronization.
COLUMN NAME DATA TYPE DESCRIPTION

allow_partition_realignment bit Determines if deletes are sent to the


subscriber when modification of the
row on the publisher causes it to
change its partition. A value of 1 means
that deletes are sent to the Subscriber.
For more information, see
sp_addmergepublication (Transact-
SQL).

retention_period_unit tinyint Defines the unit that is used when


defining retention. This can be one of
the following values:

0 = day

1 = week

2 = month

3 = year

has_downloadonly_articles bit Indicates if any articles that belong to


the publication are download-only
articles. A value of 1 indicates that there
are download-only articles.

decentralized_conflicts int Indicates whether the conflict records


are stored at the Subscriber that caused
the conflict. A value of 0 indicates that
conflict records are not stored at the
Subscriber. A value of 1 indicates that
conflict records are stored at the
Subscriber.

generation_leveling_threshold int Specifies the number of changes that


are contained in a generation. A
generation is a collection of changes
that are delivered to a Publisher or
Subscriber

automatic_reinitialization_policy bit Indicates whether changes are


uploaded from the Subscriber before an
automatic reinitialization occurs. A value
of 1 indicates that changes are
uploaded from the Subscriber before an
automatic reinitialization occurs. A value
of 0 indicates that changes are not
uploaded before an automatic
reinitialization.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpmergepublication is used in merge replication.
Permissions
Members of the publication access list for a publication can execute sp_helpmergepublication for that publication.
Members of the db_owner fixed database role on the publication database can execute sp_helpmergepublication
for information on all publications.

Example
DECLARE @publication AS sysname;
SET @publication = N'AdvWorksSalesOrdersMerge';

USE [AdventureWorks2012]
EXEC sp_helpmergepublication @publication = @publication;
GO

See Also
View and Modify Publication Properties
sp_addmergepublication (Transact-SQL)
sp_changemergepublication (Transact-SQL)
sp_dropmergepublication (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_helpmergepullsubscription (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about pull subscriptions that exist at a Subscriber. This stored procedure is executed at the
Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_helpmergepullsubscription [ [ @publication=] 'publication']
[ , [ @publisher=] 'publisher']
[ , [ @publisher_db=] 'publisher_db']
[ , [ @subscription_type=] 'subscription_type']

Argument
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of %. If publication is %, information about
all merge publications and subscriptions in the current database is returned.
[ @publisher=] 'publisher'
Is the name of the Publisher. publisheris sysname, with a default of %.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_dbis sysname, with a default of %.
[ @subscription_type=] 'subscription_type'
Is whether to show pull subscriptions. subscription_typeis nvarchar(10), with a default of 'pull'. Valid values are
'push', 'pull', or 'both'.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

subscription_name nvarchar(1000) Name of the subscription.

publication sysname Name of the publication.

publisher sysname Name of the Publisher.

publisher_db sysname Name of the Publisher database.

subscriber sysname Name of the Subscriber.

subscription_db sysname Name of the subscription database.


COLUMN NAME DATA TYPE DESCRIPTION

status int Subscription status:

0 = Inactive subscription

1 = Active subscription

2 = Deleted subscription

3 = Detached subscription

4 = Attached subscription

5 = Subscription has been marked for


reinitialization with upload

6 = Attaching the subscription failed

7 = Subscription restored from backup

subscriber_type int Type of Subscriber:

1 = Global

2 = Local

3 = Anonymous

subscription_type int Type of subscription:

0 = Push

1 = Pull

2 = Anonymous

priority float(8) Subscription priority. The value must be


less than 100.00.

sync_type tinyint Subscription synchronization type:

1 = Automatic

2 = Snapshot is not used.

description nvarchar(255) Brief description of the pull


subscription.

merge_jobid binary(16) Job ID of the Merge Agent.

enabled_for_syncmgr int Whether the subscription can be


synchronized through the Microsoft
Synchronization Manager.

last_updated nvarchar(26) Time that the Merge Agent last


successfully synchronized the
subscription.
COLUMN NAME DATA TYPE DESCRIPTION

publisher_login sysname The Publisher login name.

publisher_password sysname The Publisher password.

publisher_security_mode int Specifies the security mode of the


Publisher:

0 = SQL Server Authentication

1 = Windows Authentication

distributor sysname Name of the Distributor.

distributor_login sysname The Distributor login name.

distributor_password sysname The Distributor password.

distributor_security_mode int Specifies the security mode of the


Distributor:

0 = SQL Server Authentication

1 = Windows Authentication

ftp_address sysname Available for backward compatibility


only. Is the network address of the file
transfer protocol (FTP) service for the
Distributor.

ftp_port int Available for backward compatibility


only. Is the port number of the FTP
service for the Distributor.

ftp_login sysname Available for backward compatibility


only. Is the username used to connect
to the FTP service.

ftp_password sysname Available for backward compatibility


only. Is the user password used to
connect to the FTP service.

alt_snapshot_folder nvarchar(255) Location where snapshot folder is


stored if the location is other than or in
addition to the default location.

working_directory nvarchar(255) Fully-qualified path to the directory


where snapshot files are transferred
using FTP when that option is specified.

use_ftp bit Subscription is subscribing to


publication over the Internet, and FTP
addressing properties are configured. If
0, Subscription is not using FTP. If 1,
subscription is using FTP.
COLUMN NAME DATA TYPE DESCRIPTION

offload_agent bit Specifies if the agent can be activated


and run remotely. If 0, the agent
cannot be remotely activated.

offload_server sysname Name of the server used for remote


activation.

use_interactive_resolver int Returns whether or not the interactive


resolver is used during reconciliation. If
0, the interactive resolver is not used.

subid uniqueidentifier ID of the Subscriber.

dynamic_snapshot_location nvarchar(255) The path to the folder where the


snapshot files are saved.

last_sync_status int Synchronization status:

1 = Starting

2 = Succeeded

3 = In progress

4 = Idle

5 = Retrying after a previous failure

6 = Failed

7 = Failed validation

8 = Passed validation

9 = Requested a shutdown

last_sync_summary sysname Description of last synchronization


results.

use_web_sync bit Specifies if the subscription can be


synchronized over HTTPS, where a
value of 1 means that this feature is
enabled.

internet_url nvarchar(260) URL that represents the location of the


replication listener for Web
synchronization.

internet_login nvarchar(128) Login that the Merge Agent uses when


connecting to the Web server that is
hosting Web synchronization using
Basic Authentication.
COLUMN NAME DATA TYPE DESCRIPTION

internet_password nvarchar(524) Password for the login that the Merge


Agent uses when connecting to the
Web server that is hosting Web
synchronization using Basic
Authentication.

internet_security_mode int The authentication mode used when


connecting to the Web server that is
hosting Web synchronization. A value
of 1 means Windows Authentication,
and a value of 0 means SQL Server
Authentication.

internet_timeout int Length of time, in seconds, before a


Web synchronization request expires.

hostname nvarchar(128) Specifies an overloaded value for


HOST_NAME when this function is used
in the WHERE clause of a parameterized
row filter.

job_login nvarchar(512) Is the Windows account under which


the Merge agent runs, which is
returned in the format
domain\username.

job_password sysname For security reasons, a value of


"*********\*" is always returned.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpmergepullsubscription is used in merge replication. In the result set, the date returned in last_updated
is formatted as YYYYMMDD hh:mm:ss.fff.

Permissions
Only members of the sysadmin fixed server role and the db_owner fixed database role can execute
sp_helpmergepullsubscription.

See Also
sp_addmergepullsubscription (Transact-SQL)
sp_changemergepullsubscription (Transact-SQL)
sp_dropmergepullsubscription (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_helpmergesubscription (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about a subscription to a merge publication, both push and pull. This stored procedure is
executed at the Publisher on the publication database or at a republishing Subscriber on the subscription
database.
Transact-SQL Syntax Conventions

Syntax
sp_helpmergesubscription [ [ @publication=] 'publication']
[ , [ @subscriber=] 'subscriber']
[ , [ @subscriber_db=] 'subscriber_db']
[ , [ @publisher=] 'publisher']
[ , [ @publisher_db=] 'publisher_db']
[ , [ @subscription_type=] 'subscription_type']
[ , [ @found=] 'found' OUTPUT]

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of %. The publication must already exist and
conform to the rules for identifiers. If NULL or %, information about all merge publications and subscriptions in
the current database is returned.
[ @subscriber=] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of %. If NULL or %, information about all
subscriptions to the given publication is returned.
[ @subscriber_db=] 'subscriber_db'
Is the name of the subscription database. subscriber_dbis sysname, with a default of %, which returns information
about all subscription databases.
[ @publisher=] 'publisher'
Is the name of the Publisher. The Publisher must be a valid server. publisheris sysname, with a default of %, which
returns information about all Publishers.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_dbis sysname, with a default of %, which returns information
about all Publisher databases.
[ @subscription_type=] 'subscription_type'
Is the type of subscription. subscription_typeis nvarchar(15), and can be one of these values.

VALUE DESCRIPTION

push (default) Push subscription


VALUE DESCRIPTION

pull Pull subscription

both Both a push and pull subscription

[ @found=] 'found'OUTPUT
Is a flag to indicate returning rows. foundis int and an OUTPUT parameter, with a default of NULL. 1 indicates the
publication is found. 0 indicates the publication is not found.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

subscription_name sysname Name of the subscription.

publication sysname Name of the publication.

publisher sysname Name of the Publisher.

publisher_db sysname Name of the Publisher database.

subscriber sysname Name of the Subscriber.

subscriber_db sysname Name of the subscription database.

status int Status of the subscription:

0 = All jobs are waiting to start

1 = One or more jobs are starting

2 = All jobs have executed successfully

3 = At least one job is executing

4 = All jobs are scheduled and idle

5 = At least one job is attempting to


execute after a previous failure

6 = At least one job has failed to


execute successfully

subscriber_type int Type of Subscriber.

subscription_type int Type of subscription:

0 = Push

1 = Pull

2 = Both

priority float(8) Number indicating the priority for the


subscription.
COLUMN NAME DATA TYPE DESCRIPTION

sync_type tinyint Subscription sync type.

description nvarchar(255) Brief description of this merge


subscription.

merge_jobid binary(16) Job ID of the Merge Agent.

full_publication tinyint Whether the subscription is to a full or


filtered publication.

offload_enabled bit Specifies if offload execution of a


replication agent has been set to run at
the Subscriber. If NULL, execution is run
at the Publisher.

offload_server sysname Name of the server to where the agent


is running.

use_interactive_resolver int Returns whether or not the interactive


resolver is used during reconciliation. If
0, the interactive resolver not is used.

hostname sysname Value supplied when a subscription is


filtered by the value of the
HOST_NAME function.

subscriber_security_mode smallint Is the security mode at the Subscriber,


where 1 means Windows
Authentication, and 0 means Microsoft
SQL Server Authentication.

subscriber_login sysname Is the login name at the Subscriber.

subscriber_password sysname Actual Subscriber password is never


returned. The result is masked by a
"*****\*" string.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpmergesubscription is used in merge replication to return subscription information stored at the
Publisher or republishing Subscriber.
For anonymous subscriptions, the subscription_typevalue is always 1 (pull). However, you must execute
sp_helpmergepullsubscription at the Subscriber for information on anonymous subscriptions.

Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role or the publication access list
for the publication to which the subscription belongs can execute sp_helpmergesubscription.
See Also
sp_addmergesubscription (Transact-SQL)
sp_changemergesubscription (Transact-SQL)
sp_dropmergesubscription (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helppeerrequests (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information on all status requests received by participants in a peer-to-peer replication topology, where
these requests were initiated by executing sp_requestpeerresponse (Transact-SQL) at any published database in
the topology. This stored procedure is executed on the publication database at a Publisher participating in a peer-
to-peer replication topology. For more information, see Peer-to-Peer Transactional Replication.
Transact-SQL Syntax Conventions

Syntax
sp_helppeerrequests [ @publication = ] 'publication'
[ , [ @description = ] 'description'

Arguments
[ @publication= ] 'publication'
Is the name of the publication in a peer-to-peer topology for which status requests were sent. publication is
sysname, with no default.
[ @description= ] 'description'
Value that can be used to identify individual status requests, which enables you to filter returned responses based
on user defined information supplied when calling sp_requestpeerresponse (Transact-SQL). description is
nvarchar(4000), with a default of %. By default, all status requests for the publication are returned. This parameter
is used to return only status requests with a description matching the value supplied in description, where
character strings are matched using a LIKE (Transact-SQL) clause.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

id int Identifies a request.

publication sysname Name of the publication for which the


status request was sent.

sent_date datetime Date and time that the status request


was sent.

description nvarchar(4000) User defined information that can be


used to identify individual status
requests.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helppeerrequests is used in peer-to-peer transactional replication.
sp_helppeerrequests is used when restoring a database published in a peer-to-peer topology.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_helppeerrequests.

See Also
sp_deletepeerrequesthistory (Transact-SQL)
sp_helppeerresponses (Transact-SQL)
sp_helppeerresponses (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns all responses to a specific status request received from a participant in a peer-to-peer replication topology,
where the request was initiated by executing sp_helppeerrequests at any published database in the topology. This
stored procedure is executed on the publication database at a Publisher participating in a peer-to-peer replication
topology. For more information, see Peer-to-Peer Transactional Replication.
Transact-SQL Syntax Conventions

Syntax
sp_helppeerresponses [ @request_id = ] request_id

Arguments
[ @request_id= ] request_id
Is the ID of a specific status request. request_id is int, with no default.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

request_id int ID of the status request.

peer sysname The name of the peer that generated


the response.

peer_db sysname The database name at the peer that


generated the response.

received_date datetime Date and time that the requestor


received the response from the peer
that sent it.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helppeerresponses is used in peer-to-peer transactional replication.
sp_helppeerresponses procedure is used when restoring a database published in a peer-to-peer topology.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_helppeerresponses.

See Also
sp_deletepeerrequesthistory (Transact-SQL)
sp_helppeerrequests (Transact-SQL)
sp_helppublication (Transact-SQL)
11/21/2017 • 7 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns information about a publication. For a Microsoft SQL Server publication, this stored procedure is executed
at the Publisher on the publication database. For an Oracle publication, this stored procedure is executed at the
Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_helppublication [ [ @publication = ] 'publication' ]
[ , [ @found=] found OUTPUT]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication = ] 'publication'
Is the name of the publication to be viewed. publication is sysname, with a default of %, which returns information
about all publications.
[ @found = ] 'found' OUTPUT
Is a flag to indicate returning rows. foundis int and an OUTPUT parameter, with a default of 23456. 1 indicates the
publication is found. 0 indicates the publication is not found.
[ @publisher = ] 'publisher'
Specifies a non- SQL Server publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be specified when requesting publication information from a SQL Server Publisher.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

pubid int ID for the publication.

name sysname Name of the publication.

restricted int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.
COLUMN NAME DATA TYPE DESCRIPTION

status tinyint The current status of the publication.

0 = Inactive.

1 = Active.

task Used for backward compatibility.

replication frequency tinyint Type of replication frequency:

0 = Transactional

1 = Snapshot

synchronization method tinyint Synchronization mode:

0 = Native bulk copy program (bcp


utility)

1 = Character bulk copy

3 = Concurrent, which means that


native bulk copy (bcputility) is used but
tables are not locked during the
snapshot

4 = Concurrent_c, which means that


character bulk copy is used but tables
are not locked during the snapshot

description nvarchar(255) Optional description for the publication.

immediate_sync bit Whether the synchronization files are


created or re-created each time the
Snapshot Agent runs.

enabled_for_internet bit Whether the synchronization files for


the publication are exposed to the
Internet, through file transfer protocol
(FTP) and other services.

allow_push bit Whether push subscriptions are allowed


on the publication.

allow_pull bit Whether pull subscriptions are allowed


on the publication.

allow_anonymous bit Whether anonymous subscriptions are


allowed on the publication.

independent_agent bit Whether there is a stand-alone


Distribution Agent for this publication.
COLUMN NAME DATA TYPE DESCRIPTION

immediate_sync_ready bit Whether or not the Snapshot Agent


generated a snapshot that is ready to
be used by new subscriptions. This
parameter is defined only if the
publication is set to always have a
snapshot available for new or
reinitialized subscriptions.

allow_sync_tran bit Whether immediate-updating


subscriptions are allowed on the
publication.

autogen_sync_procs bit Whether to automatically generate


stored procedures to support
immediate-updating subscriptions.

snapshot_jobid binary(16) Scheduled task ID.

retention int Amount of change, in hours, to save for


the given publication.

has subscription bit If the publication has an active


subscriptions. 1 means that the
publication has active subscriptions,
and 0 means that the publication has
no subscriptions.

allow_queued_tran bit Specifies whether disables queuing of


changes at the Subscriber until they can
be applied at the Publisher has been
enabled. If 0, changes at the Subscriber
are not queued.

snapshot_in_defaultfolder bit Specifies whether snapshot files are


stored in the default folder. If 0,
snapshot files have been stored in the
alternate location specified by
alternate_snapshot_folder. If 1,
snapshot files can be found in the
default folder.

alt_snapshot_folder nvarchar(255) Specifies the location of the alternate


folder for the snapshot.

pre_snapshot_script nvarchar(255) Specifies a pointer to an .sql file


location. The Distribution Agent will run
the pre-snapshot script before running
any of the replicated object scripts
when applying a snapshot at a
Subscriber.

post_snapshot_script nvarchar(255) Specifies a pointer to an .sql file


location. The Distribution Agent will run
the post-snapshot script after all the
other replicated object scripts and data
have been applied during an initial
synchronization.
COLUMN NAME DATA TYPE DESCRIPTION

compress_snapshot bit Specifies that the snapshot that is


written to the alt_snapshot_folder
location is to be compressed into the
Microsoft CAB format. 0 specifies that
the snapshot will not be compressed.

ftp_address sysname The network address of the FTP service


for the Distributor. Specifies where
publication snapshot files are located
for the Distribution Agent or Merge
Agent of a subscriber to pick up.

ftp_port int The port number of the FTP service for


the Distributor.

ftp_subdirectory nvarchar(255) Specifies where the snapshot files will


be available for the Distribution Agent
or Merge Agent of subscriber to pick
up if the publication supports
propagating snapshots using FTP.

ftp_login sysname The username used to connect to the


FTP service.

allow_dts bit Specifies that the publication allows


data transformations. 0 specifies that
DTS transformations are not allowed.

allow_subscription_copy bit Specifies whether the ability to copy the


subscription databases that subscribe
to this publication has been enabled. 0
means that copying is not allowed.

centralized_conflicts bit Specifies whether conflict records are


stored on the Publisher:

0 = Conflict records are stored at both


the publisher and at the subscriber that
caused the conflict.

1 = Conflict records are stored at the


Publisher.

conflict_retention int Specifies the conflict retention period, in


days.

conflict_policy int Specifies the conflict resolution policy


followed when the queued updating
subscriber option is used. Can be one
of these values:

1 = Publisher wins the conflict.

2 = Subscriber wins the conflict.

3 = Subscription is reinitialized.
COLUMN NAME DATA TYPE DESCRIPTION

queue_type Specifies which type of queue is used.


Can be one of these values:

msmq = Use Microsoft Message


Queuing to store transactions.

sql = Use SQL Server to store


transactions.

Note: Support for Message Queuing


has been discontinued.

backward_comp_level Database compatibility level, and can be


one of the following:

90 = Microsoft SQL Server 2005

100 = Microsoft SQL Server 2008

publish_to_AD bit Specifies whether the publication is


published in the Microsoft Active
Directory™. A value of 1 indicates that
it is published, and a value of 0
indicates that it is not published.

allow_initialize_from_backup bit Indicates if Subscribers can initialize a


subscription to this publication from a
backup rather than an initial snapshot.
1 means that subscriptions can be
initialized from a backup, and 0 means
that they cannot. For more information,
see Initialize a Transactional
Subscription Without a Snapshot a
transactional Subscriber without a
snapshot.

replicate_ddl int Indicates if schema replication is


supported for the publication. 1
indicates that data definition language
(DDL) statements executed at the
publisher are replicated, and 0 indicates
that DDL statements are not replicated.
For more information, see Make
Schema Changes on Publication
Databases.

enabled_for_p2p int If the publication can be used in a peer-


to-peer replication topology. 1 indicates
that the publication supports peer-to-
peer replication. For more information,
see Peer-to-Peer Transactional
Replication.

publish_local_changes_only int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.
COLUMN NAME DATA TYPE DESCRIPTION

enabled_for_het_sub int Specifies whether the publication


supports non- SQL Server Subscribers.
A value of 1 means that non- SQL
Server Subscribers are supported. A
value of 0 means that only SQL Server
Subscribers are supported. For more
information, see Non-SQL Server
Subscribers.

enabled_for_p2p_conflictdetection int Specifies whether the Distribution


Agent detects conflicts for a publication
that is enabled for peer-to-peer
replication. A value of 1 means that
conflicts are detected. For more
information, see Conflict Detection in
Peer-to-Peer Replication.

originator_id int Specifies an ID for a node in a peer-to-


peer topology. This ID is used for
conflict detection if
enabled_for_p2p_conflictdetection is
set to 1. For a list of IDs that have
already been used, query the
Mspeer_originatorid_history system
table.

p2p_continue_onconflict int Specifies whether The Distribution


Agent continues to process changes
when a conflict is detected. A value of 1
means that the agent continues to
process changes.

** Caution *\* We recommend that


you use the default value of 0. When
this option is set to 1, the Distribution
Agent tries to converge data in the
topology by applying the conflicting
row from the node that has the highest
originator ID. This method does not
guarantee convergence. You should
make sure that the topology is
consistent after a conflict is detected.
For more information, see "Handling
Conflicts" in Conflict Detection in Peer-
to-Peer Replication.

alllow_partition_switch int Specifies whether ALTER TABLE…


SWITCH statements can be executed
against the published database. For
more information, see Replicate
Partitioned Tables and Indexes.

replicate_partition_switch int Specifies whether ALTER TABLE…


SWITCH statements that are executed
against the published database should
be replicated to Subscribers. This option
is valid only if allow_partition_switch is
set to 1.
Return Code Values
0 (success) or 1 (failure)

Remarks
sp_helppublication is used in snapshot and transactional replication.
sp_helppublication will return information on all publications that are owned by the user executing this procedure.

Example
DECLARE @myTranPub AS sysname
SET @myTranPub = N'AdvWorksProductTran'

USE [AdventureWorks2012]
EXEC sp_helppublication @publication = @myTranPub
GO

Permissions
Only members of the sysadmin fixed server role at the Publisher or members of the db_owner fixed database role
on the publication database or users in the publication access list (PAL) can execute sp_helppublication.
For a non- SQL Server Publisher, only members of the sysadmin fixed server role at the Distributor or members of
the db_owner fixed database role on the distribution database or users in the PAL can execute sp_helppublication.

See Also
View and Modify Publication Properties
sp_addpublication (Transact-SQL)
sp_changepublication (Transact-SQL)
sp_droppublication (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_helppublication_snapshot (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns information on the Snapshot agent for a given publication. This stored procedure is executed at the
Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_helppublication_snapshot [ @publication = ] 'publication'
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @publisher = ] 'publisher'
Specifies a non- SQL Server publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when adding an article to a SQL Server Publisher.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

id int ID of the Snapshot Agent.

name nvarchar(100) Name of the Snapshot Agent.

publisher_security_mode smallint Security mode used by the agent when


connecting to the Publisher, which can
be one of the following:

0 = SQL Server Authentication

1 = Windows Authentication.

publisher_login sysname Login used when connecting to the


Publisher.

publisher_password nvarchar(524) For security reasons, a value of


*********\* is always returned.
COLUMN NAME DATA TYPE DESCRIPTION

job_id uniqueidentifier Unique ID of the agent job.

job_login nvarchar(512) Is the Windows account under which


the Snapshot agent runs, which is
returned in the format
DOMAIN\username.

job_password sysname For security reasons, a value of


*********\* is always returned.

schedule_name sysname Name of the schedule used for this


agent job.

frequency_type int Is the frequency with which the agent is


scheduled to run, which can be one of
these values.

1 = One time

2 = On demand

4 = Daily

8 = Weekly

16 = Monthly

32 = Monthly relative

64 = Autostart

128 = Recurring

frequency_interval int The days that the agent runs, which can
be one of these values.

1 = Sunday

2 = Monday

3 = Tuesday

4 = Wednesday

5 = Thursday

6 = Friday

7 = Saturday

8 = Day

9 = Weekdays

10 = Weekend days
COLUMN NAME DATA TYPE DESCRIPTION

frequency_subday_type int Is the type that defines how often the


agent runs when frequency_type is 4
(daily), and can be one of these values.

1 = At the specified time

2 = Seconds

4 = Minutes

8 = Hours

frequency_subday_interval int Number of intervals of


frequency_subday_type that occur
between scheduled execution of the
agent.

frequency_relative_interval int Is the week that the agent runs in a


given month when frequency_type is 32
(monthly relative), and can be one of
these values.

1 = First

2 = Second

4 = Third

8 = Fourth

16 = Last

frequency_recurrence_factor int Number of weeks or months between


the scheduled execution of the agent.

active_start_date int Date when the agent is first scheduled


to run, formatted as YYYYMMDD.

active_end_date int Date when the agent is last scheduled


to run, formatted as YYYYMMDD.

active_start_time int Time when the agent is first scheduled


to run, formatted as HHMMSS.

active_end_time int Time when the agent is last scheduled


to run, formatted as HHMMSS.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_help_publication_snapshot is used in all types of replication.

Permissions
Only members of the sysadmin fixed server role at the Publisher or members of the db_owner fixed database
role on the publication database can execute sp_help_publication_snapshot.

See Also
View and Modify Publication Properties
sp_addpublication_snapshot (Transact-SQL)
sp_changepublication_snapshot (Transact-SQL)
sp_dropmergepublication (Transact-SQL)
sp_droppublication (Transact-SQL)
sp_helppullsubscription (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Displays information about one or more subscriptions at the Subscriber. This stored procedure is executed at the
Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_helppullsubscription [ [ @publisher = ] 'publisher' ]
[ , [ @publisher_db = ] 'publisher_db' ]
[ , [ @publication = ] 'publication' ]
[ , [ @show_push = ] 'show_push' ]

Arguments
[ @publisher=] 'publisher'
Is the name of the remote server. publisher is sysname, with a default of %, which returns information for all
Publishers.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default of %, which returns all the
Publisher databases.
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of %, which returns all the publications. If
this parameter equals to ALL, only pull subscriptions with independent_agent = 0 are returned.
[ @show_push=] 'show_push'
Is whether all push subscriptions are to be returned. show_pushis nvarchar(5), with a default of FALSE, which
does not return push subscriptions.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

publisher sysname Name of the Publisher.

publisher database sysname Name of the Publisher database.

publication sysname Name of the publication.

independent_agent bit Indicates whether there is a stand-


alone Distribution Agent for this
publication.
COLUMN NAME DATA TYPE DESCRIPTION

subscription type int Subscription type to the publication.

distribution agent nvarchar(100) Distribution Agent handling the


subscription.

publication description nvarchar(255) Description of the publication.

last updating time date Time the subscription information was


updated. This is a UNICODE string of
ISO date (114) + ODBC time (121). The
format is yyyymmdd hh:mi:sss.mmm
where 'yyyy' is year, 'mm' is month, 'dd'
is day, 'hh' is hour, 'mi' is minute, 'sss' is
seconds, and 'mmm' is milliseconds.

subscription name varchar(386) Name of the subscription.

last transaction timestamp varbinary(16) Timestamp of the last replicated


transaction.

update mode tinyint Type of updates allowed.

distribution agent job_id int Job ID of the Distribution Agent.

enabled_for_synmgr int Whether the subscription can be


synchronized through the Microsoft
Synchronization Manager.

subscription guid binary(16) Global identifier for the version of the


subscription on the publication.

subid binary(16) Global identifier for an anonymous


subscription.

immediate_sync bit Whether the synchronization files are


created or re-created each time the
Snapshot Agent runs.

publisher login sysname Login ID used at the Publisher for SQL


Server Authentication.

publisher password nvarchar(524) Password (encrypted) used at the


Publisher for SQL Server
Authentication.
COLUMN NAME DATA TYPE DESCRIPTION

publisher security_mode int Security mode implemented at the


Publisher:

0 = SQL Server Authentication

1 = Windows Authentication

2 = The synchronization triggers use a


static sysservers entry to do remote
procedure call (RPC), and publisher
must be defined in the sysservers table
as a remote server or linked server.

distributor sysname Name of the Distributor.

distributor_login sysname Login ID used at the Distributor for


SQL Server Authentication.

distributor_password nvarchar(524) Password (encrypted) used at the


Distributor for SQL Server
Authentication.

distributor_security_mode int Security mode implemented at the


Distributor:

0 = SQL Server Authentication

1 = Windows Authentication

ftp_address sysname For backward compatibility only.

ftp_port int For backward compatibility only.

ftp_login sysname For backward compatibility only.

ftp_password nvarchar(524) For backward compatibility only.

alt_snapshot_folder nvarchar(255) Location where snapshot folder is


stored if the location is other than or in
addition to the default location.

working_directory nvarchar(255) Fully qualified path to the directory


where snapshot files are transferred
using File Transfer Protocol (FTP) when
that option is specified.

use_ftp bit Subscription is subscribing to


Publication over the Internet and FTP
addressing properties are configured. If
0, Subscription is not using FTP. If 1,
subscription is using FTP.
COLUMN NAME DATA TYPE DESCRIPTION

publication_type int Specifies the replication type of the


publication:

0 = Transactional replication

1 = Snapshot replication

2 = Merge replication

dts_package_name sysname Specifies the name of the Data


Transformation Services (DTS) package.

dts_package_location int Location where the DTS package is


stored:

0 = Distributor

1 = Subscriber

offload_agent bit Specifies if the agent can be activated


remotely. If 0, the agent cannot be
activated remotely.

offload_server sysname Specifies the network name of the


server used for remote activation.

last_sync_status int Subscription status:

0 = All jobs are waiting to start

1 = One or more jobs are starting

2 = All jobs have executed successfully

3 = At least one job is executing

4 = All jobs are scheduled and idle

5 = At least one job is attempting to


execute after a previous failure

6 = At least one job has failed to


execute successfully

last_sync_summary sysname Description of last synchronization


results.

last_sync_time datetime Time the subscription information was


updated. This is a UNICODE string of
ISO date (114) + ODBC time (121). The
format is yyyymmdd hh:mi:sss.mmm
where 'yyyy' is year, 'mm' is month, 'dd'
is day, 'hh' is hour, 'mi' is minute, 'sss' is
seconds, and 'mmm' is milliseconds.
COLUMN NAME DATA TYPE DESCRIPTION

job_login nvarchar(512) Is the Windows account under which


the Distribution agent runs, which is
returned in the format
domain\username.

job_password sysname For security reasons, a value of


"*********\*" is always returned.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helppullsubscription is used in snapshot and transactional replication.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_helppullsubscription .

See Also
sp_addpullsubscription (Transact-SQL)
sp_droppullsubscription (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpqreader_agent (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns properties of the Queue Reader agent. This stored procedure is executed at the Distributor on the
distribution database or at the Publisher on any database.
Transact-SQL Syntax Conventions

Syntax
sp_helpqreader_agent [ [ @frompublisher = ] frompublisher ]

Arguments
[ @frompublisher= ] frompublisher
Specifies whether the stored procedure is called at the Publisher or at the Distributor. frompublisher is bit, with a
default value of 0. 1 means that the stored procedure is called from the Publisher, and 0 means that the stored
procedure is called from the Distributor.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

id int ID of the agent.

name nvarchar(100) Name of the agent.

job_id uniqueidentifier Unique ID of the agent job.

job_login nvarchar(512) Is the Windows account under which


the Distribution agent runs, which is
returned in the format
DOMAIN\username.

job_password sysname For security reasons, a value of


*********\* is always returned.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpqreader_agent is used in transactional replication.
Permissions
When the value of frompublisher is 1, only members of the sysadmin fixed server role at the Publisher or
members of the db_owner fixed database role on the publication database can execute sp_helpqreader_agent.
Otherwise, only members of the sysadmin fixed server role at the Distributor or members of the db_owner fixed
database role on the distribution database can execute sp_helpqreader_agent.

See Also
Enable Updating Subscriptions for Transactional Publications
sp_helpreplfailovermode (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Displays the current failover mode of a subscription. This stored procedure is executed at the Subscriber on any
database. For more information about failover modes, see Updatable Subscriptions for Transactional Replication.
Transact-SQL Syntax Conventions

Syntax
sp_helpreplfailovermode [ @publisher= ] 'publisher'
[ , [ @publisher_db = ] 'publisher_db' ]
[ , [ @publication = ] 'publication' ]
[ , [ @failover_mode_id= ] 'failover_mode_id'OUTPUT]
[ , [ @failover_mode = ] 'failover_mode'OUTPUT]

Arguments
[ @publisher=] 'publisher'
Is the name of the Publisher that is participating in the update of this Subscriber. publisher is sysname, with no
default. The Publisher must already be configured for publishing.
[ @publisher_db =] 'publisher_db'
Is the name of the publication database. publisher_db is sysname, with no default.
[ @publication=] 'publication'
Is the name of the publication that is participating in the update of this Subscriber. publicationis sysname, with no
default.
[ @failover_mode_id=] 'failover_mode_id' OUTPUT
Returns the integer value of the failover mode and is an OUTPUT parameter. failover_mode_id is a tinyint with a
default of 0. It returns 0 for immediate updating and 1 for queued updating.
[@failover_mode=] 'failover_mode'OUTPUT
Returns the mode in which data modifications are made at the Subscriber. failover_mode is a nvarchar(10) with a
default of NULL. Is an OUTPUT parameter.

VALUE DESCRIPTION

immediate Immediate updating: updates made at the Subscriber are


immediately propagated to the Publisher using two-phase
commit protocol (2PC).

queued Queued updating: updates made at the Subscriber are stored


in a queue.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpreplfailovermode is used in snapshot replication or transactional replication for which subscriptions are
enabled for immediate updating with queued updating as failover, in case of failure.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_helpreplfailovermode.

See Also
sp_setreplfailovermode (Transact-SQL)
sp_helpreplicationdboption (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Shows whether databases at the Publisher are enabled for replication. This stored procedure is executed at the
Publisher on any database. Not supported for Oracle Publishers.
Transact-SQL Syntax Conventions

Syntax
sp_helpreplicationdboption [ [ @dbname =] 'dbname' ]
[ , [ @type = ] 'type' ]
[ , [ @reserved = ] reserved ]

Arguments
[ @dbname=] 'dbname'
Is the name of the database. dbname is sysname, with a default of %. If %, then the result set contains all
databases at the Publisher, otherwise only information on the specified database is returned. Information is not
returned for any databases on which the user does not have the appropriate permissions, as described below.
[ @type=] 'type'
Restricts the result set to contain only databases on which the specified replication option type value has been
enabled. type is sysname, and can be one of the following values.

VALUE DESCRIPTION

publish Transactional replication allowed.

merge publish Merge replication allowed.

replication allowed (default) Either transactional or merge replication allowed.

[ @reserved= ] reserved
Specifies whether information on existing publications and subscriptions is returned. reserved is bit, with a default
value of 0. If 1, the result set includes information on whether the database specified has any existing publications
or subscriptions.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

name sysname Name of the database.

id int Database identifier.


COLUMN NAME DATA TYPE DESCRIPTION

transpublish bit If the database has been enabled for


snapshot or transactional publishing;
where a value of 1 means that snapshot
or transactional publishing is enabled.

mergepublish bit If the database has been enabled for


merge publishing; where a value of 1
means that merge publishing is
enabled.

dbowner bit If the user is a member of the


db_owner fixed database role; where a
value of 1 indicates that the user is a
member of this role.

dbreadonly bit Is if the database is marked as read-


only; where a value of 1 means that the
database is read-only.

haspublications bit Is if the database has any existing


publications; where a value of 1 means
that there are existing publications.

haspullsubscriptions bit Is if the database has any existing pull


subscriptions; where a value of 1 means
that there are existing pull
subscriptions.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpreplicationdboption is used in snapshot, transactional, and merge replication.

Permissions
Members of the sysadmin fixed server role can execute sp_helpreplicationdboption for any database. Members
of the db_owner fixed database role can execute sp_helpreplicationdboption for that database.

See Also
sp_replicationdboption (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpreplicationoption (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Shows the types of replication options enabled for a server. This stored procedure is executed at any server on any
database.
Transact-SQL Syntax Conventions

Syntax
sp_helpreplicationoption [ [ @optname =] 'option_name' ]

Arguments
[ @optname =] 'option_name'
Is the name of the replication option to query for. option_name is sysname, with a default of NULL.

VALUE DESCRIPTION

transactional A result set is returned when transactional replication is


enabled.

merge A result set is returned when merge replication is enabled.

NULL (default) A result set is not returned.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

optname sysname Name of the replication option and can


be one of the following:

transactional

merge

value bit Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.

major_version int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.
COLUMN NAME DATA TYPE DESCRIPTION

minor_version int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.

revision int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.

install_failures int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpreplicationoption is used to get information about replication options enabled on a particular server. To
get information on a particular database, use sp_helpreplicationdboption.

Permissions
Execute permissions default to the public role.

See Also
System Stored Procedures (Transact-SQL)
sp_helpsubscriberinfo (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Displays information about a Subscriber. This stored procedure is executed at the Publisher on any database.
Transact-SQL Syntax Conventions

Syntax
sp_helpsubscriberinfo [ [ @subscriber =] 'subscriber']
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @subscriber = ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of %, which returns all information.
[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, and defaults to the name of the current server.

NOTE
publisher should not be specified, except when it is an Oracle Publisher.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

publisher sysname Name of the Publisher.

subscriber sysname Name of the Subscriber.

type tinyint Type of Subscriber:

0 = Microsoft SQL Server database 1 =


ODBC data source

login sysname Login ID for SQL Server Authentication.

password sysname Password for SQL Server


Authentication.

commit_batch_size int Not supported.

status_batch_size int Not supported.


COLUMN NAME DATA TYPE DESCRIPTION

flush_frequency int Not supported.

frequency_type int Frequency with which the Distribution


Agent is run:

1 = One time

2 = On demand

4 = Daily

8 = Weekly

16 = Monthly

32 = Monthly relative

64 = Autostart

128 = Recurring

frequency_interval int Value applied to the frequency set by


frequency_type.

frequency_relative_interval int Date of the Distribution Agent used


when frequency_type is set to 32
(monthly relative):

1 = First

2 = Second

4 = Third

8 = Fourth

16 = Last

frequency_recurrence_factor int Recurrence factor used by


frequency_type.

frequency_subday int How often to reschedule during the


defined period:

1 = Once

2 = Second

4 = Minute

8 = Hour

frequency_subday_interval int Interval for frequency_subday.

active_start_time_of_day int Time of day when the Distribution


Agent is first scheduled, formatted as
HHMMSS.
COLUMN NAME DATA TYPE DESCRIPTION

active_end_time_of_day int Time of day when the Distribution


Agent stops being scheduled,
formatted as HHMMSS.

active_start_date int Date when the Distribution Agent is


first scheduled, formatted as
YYYYMMDD.

active_end_date int Date when the Distribution Agent


stops being scheduled, formatted as
YYYYMMDD.

retryattempt int Not supported.

retrydelay int Not supported.

description nvarchar(255) Text description of the Subscriber.

security_mode int Implemented security mode:

0 = SQL Server Authentication

1 = Microsoft Windows Authentication

frequency_type2 int Frequency with which the Merge Agent


is run:

1 = One time

2 = On demand

4 = Daily

8 = Weekly

16 = Monthly

32 = Monthly relative

64 = Autostart

128 = Recurring

frequency_interval2 int Value applied to the frequency set by


frequency_type.
COLUMN NAME DATA TYPE DESCRIPTION

frequency_relative_interval2 int Date of the Merge Agent used when


frequency_type is set to 32(monthly
relative):

1 = First

2 = Second

4 = Third

8 = Fourth

16 = Last

frequency_recurrence_factor2 int Recurrence factor used by


frequency_type.

frequency_subday2 int How often to reschedule during the


defined period:

1 = Once

2 = Second

4 = Minute

8 = Hour

frequency_subday_interval2 int Interval for frequency_subday.

active_start_time_of_day2 int Time of day when the Merge Agent is


first scheduled, formatted as HHMMSS.

active_end_time_of_day2 int Time of day when the Merge Agent


stops being scheduled, formatted as
HHMMSS.

active_start_date2 int Date when the Merge Agent is first


scheduled, formatted as YYYYMMDD.

active_end_date2 int Date when the Merge Agent stops


being scheduled, formatted as
YYYYMMDD.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpsubscriberinfo is used in snapshot replication, transactional replication, and merge replication.

Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role, or the publication access list
for the publication can execute sp_helpsubscriberinfo.
See Also
sp_adddistpublisher (Transact-SQL)
sp_addpullsubscription (Transact-SQL)
sp_changesubscriber (Transact-SQL)
sp_dropsubscriber (Transact-SQL)
sp_helpdistributor (Transact-SQL)
sp_helpserver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpsubscription (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Lists subscription information associated with a particular publication, article, Subscriber, or set of subscriptions.
This stored procedure is executed at a Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_helpsubscription [ [ @publication = ] 'publication' ]
[ , [ @article = ] 'article' ]
[ , [ @subscriber = ] 'subscriber' ]
[ , [ @destination_db = ] 'destination_db' ]
[ , [ @found=] found OUTPUT ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication = ] 'publication'
Is the name of the associated publication. publication is sysname, with a default of %, which returns all
subscription information for this server.
[ @article= ] 'article'
Is the name of the article. article is sysname, with a default of %, which returns all subscription information for
the selected publications and Subscribers. If all, only one entry is returned for the full subscription on a
publication.
[ @subscriber= ] 'subscriber'
Is the name of the Subscriber on which to obtain subscription information. subscriber is sysname, with a default
of %, which returns all subscription information for the selected publications and articles.
[ @destination_db= ] 'destination_db'
Is the name of the destination database. destination_db is sysname, with a default of %.
[ @found= ] 'found'OUTPUT
Is a flag to indicate returning rows. foundis int and an OUTPUT parameter, with a default of 23456.
1 indicates the publication is found.
0 indicates the publication is not found.
[ @publisher= ] 'publisher'
Is the name of the Publisher. publisher is sysname, and defaults to the name of the current server.

NOTE
publisher should not be specified, except when it is an Oracle Publisher.
Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

subscriber sysname Name of the Subscriber.

publication sysname Name of the publication.

article sysname Name of the article.

destination database sysname Name of the destination database in


which replicated data is placed.

subscription status tinyint Subscription status:

0 = Inactive

1 = Subscribed

2 = Active

synchronization type tinyint Subscription synchronization type:

1 = Automatic

2 = None

subscription type int Type of subscription:

0 = Push

1 = Pull

2 = Anonymous

full subscription bit Whether subscription is to all articles in


the publication:

0 = No

1 = Yes

subscription name nvarchar(255) Name of the subscription.

update mode int 0 = Read-only

1 = Immediate-updating subscription

distribution job id binary(16) Job ID of the Distribution Agent.


COLUMN NAME DATA TYPE DESCRIPTION

loopback_detection bit Loopback detection determines


whether the Distribution Agent sends
transactions originated at the
Subscriber back to the Subscriber:

0 = Sends back.

1 = Does not send back.

Used with bidirectional transactional


replication. For more information, see
Bidirectional Transactional Replication.

offload_enabled bit Specifies whether offload execution of a


replication agent has been set to run at
the Subscriber.

If 0, agent is run at the Publisher.

If 1, agent is run at the Subscriber.

offload_server sysname Name of the server enabled for remote


agent activation. If NULL, then the
current offload_server listed in
MSdistribution_agents table is used.

dts_package_name sysname Specifies the name of the Data


Transformation Services (DTS) package.

dts_package_location int Location of the DTS package, if one is


assigned to the subscription. If there is
a package, a value of 0 specifies the
package location at the distributor. A
value of 1 specifies the subscriber.

subscriber_security_mode smallint Is the security mode at the Subscriber,


where 1 means Windows
Authentication, and 0 means SQL
Server Authentication.

subscriber_login sysname Is the login name at the Subscriber.

subscriber_password Actual Subscriber password is never


returned. The result is masked by a
"*****\*" string.

job_login sysname Name of the Windows account under


which the Distribution Agent runs.

job_password Actual job password is never returned.


The result is masked by a "*****\*"
string.

distrib_agent_name nvarchar(100) Name of the agent job that


synchronizes the subscription.
COLUMN NAME DATA TYPE DESCRIPTION

subscriber_type tinyint Type of Subscriber, which can be one of


the following:

0 = SQL Server Subscriber

1 = ODBC data source server

2 = Microsoft JET database


(deprecated)

3 = OLE DB provider

subscriber_provider sysname Unique programmatic identifier


(PROGID) with which the OLE DB
provider for the non-SQL Server data
source is registered.

subscriber_datasource nvarchar(4000) Name of the data source as understood


by the OLE DB provider.

subscriber_providerstring nvarchar(4000) OLE DB provider-specific connection


string that identifies the data source.

subscriber_location nvarchar(4000) Location of the database as understood


by the OLE DB provider

subscriber_catalog sysname Catalog to be used when making a


connection to the OLE DB provider.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpsubscription is used in snapshot and transactional replication.

Permissions
Execute permissions default to the public role. Users are only returned information for subscriptions that they
created. Information on all subscriptions is returned to members of the sysadmin fixed server role at the
Publisher or members of the db_owner fixed database role on the publication database.

See Also
sp_addsubscription (Transact-SQL)
sp_changesubstatus (Transact-SQL)
sp_dropsubscription (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_helpsubscription_properties (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Retrieves security information from the MSsubscription_properties table. This stored procedure is executed at the
Subscriber.
Transact-SQL Syntax Conventions

Syntax
sp_helpsubscription_properties [ [ @publisher = ] 'publisher' ]
[ , [ @publisher_db =] 'publisher_db' ]
[ , [ @publication =] 'publication' ]
[ , [ @publication_type = ] publication_type ]

Arguments
[ @publisher=] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of %, which returns information on all
Publishers.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default of %, which returns information
on all Publisher databases.
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of %, which returns information on all
publications.
[ @publication_type=] publication_type
Is the type of publication.publication_type is int, with a default of NULL. If supplied, publication_type must be one
of the following values:

VALUE DESCRIPTION

0 Transactional publication

1 Snapshot publication

2 Merge publication

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

publisher sysname Name of the Publisher.


COLUMN NAME DATA TYPE DESCRIPTION

publisher_db sysname Name of the Publisher database.

publication sysname Name of the publication.

publication_type int Type of publication:

0 = Transactional

1 = Snapshot

2 = Merge

publisher_login sysname Login ID used at the Publisher for SQL


Server Authentication.

publisher_password nvarchar(524) Password used at the Publisher for SQL


Server Authentication (encrypted).

publisher_security_mode int Security mode used at the Publisher:

0 = SQL Server Authentication

1 = Windows Authentication

distributor sysname Name of the Distributor.

distributor_login sysname Distributor login.

distributor_password nvarchar(524) Distributor password (encrypted).

distributor_security_mode int Security mode used at the Distributor:

0 = SQL Server Authentication

1 = Windows Authentication

ftp_address sysname For backward compatibility only.


Network address of the file transfer
protocol (FTP) service for the
Distributor.

ftp_port int For backward compatibility only. Port


number of the FTP service for the
Distributor.

ftp_login sysname For backward compatibility only. User


name used to connect to the FTP
service.

ftp_password nvarchar(524) For backward compatibility only. User


password used to connect to the FTP
service.

alt_snapshot_folder nvarchar(255) Specifies the location of the alternate


folder for the snapshot.
COLUMN NAME DATA TYPE DESCRIPTION

working_directory nvarchar(255) Name of the working directory used to


store data and schema files.

use_ftp bit Specifies the use of FTP instead of the


regular protocol to retrieve snapshots.
If 1, FTP is used.

dts_package_name sysame Specifies the name of the Data


Transformation Services (DTS) package.

dts_package_password nvarchar(524) Specifies the password on the package,


if there is one.

dts_package_location int Location where the DTS package is


stored.

0 = the package location is at the


Distributor.

1 = the package location is at the


Subscriber.

offload_agent bit Specifies if the agent can be activated


remotely. If 0, the agent cannot be
activated remotely.

offload_server sysname Specifies the network name of the


server used for remote activation.

dynamic_snapshot_location nvarchar(255) Specifies the path to the folder where


the snapshot files are saved.

use_web_sync bit Specifies if the subscription can be


synchronized over HTTPS, where a
value of 1 means that this feature is
enabled.

internet_url nvarchar(260) URL that represents the location of the


replication listener for Web
synchronization.

internet_login nvarchar(128) Login that the Merge Agent uses when


connecting to the Web server that is
hosting Web synchronization using
Basic Authentication.

internet_password nvarchar(524) Password for the login that the Merge


Agent uses when connecting to the
Web server that is hosting Web
synchronization using Basic
Authentication.
COLUMN NAME DATA TYPE DESCRIPTION

internet_security_mode int The authentication mode used when


connecting to the Web server that is
hosting Web synchronization, where a
value of 1 means Windows
Authentication, and a value of 0 means
Basic Authentication.

internet_timeout int Length of time, in seconds, before a


Web synchronization request expires.

hostname nvarchar(128) Specifies the value for HOST_NAME()


when this function is used in the
WHERE clause parameterized row filter.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpsubscription_properties is used in snapshot replication, transactional replication, and merge replication.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_helpsubscription_properties.

See Also
System Stored Procedures (Transact-SQL)
sp_helpsubscriptionerrors (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns all transactional replication errors for a given subscription. This stored procedure is executed at the
Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_helpsubscriptionerrors [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
, [ @subscriber = ] 'subscriber'
, [ @subscriber_db = ] 'subscriber_db'

Arguments
[ @publisher= ] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db= ] 'publisher_db'
Is the name of the publication database. publisher_db is sysname, with no default.
[ @publication= ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @subscriber= ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with no default.
[ @subscriber_db= ] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with no default.

Result Set
COLUMN NAME DATA TYPE DESCRIPTION

id int ID of the error.

time datetime Time the error occurred.

error_type_id int Identified for informational purposes


only. Not supported. Future
compatibility is not guaranteed.

source_type_id int Error source type ID.

source_name nvarchar(100) Name of the error source.


COLUMN NAME DATA TYPE DESCRIPTION

error_code sysname Error code.

error_text ntext Error message.

xact_seqno varbinary(16) Starting transaction log sequence


number of the failed execution batch.
Used only by the Distribution Agents,
this is the transaction log sequence
number of the first transaction in the
failed execution batch.

command_id int Command ID of the failed execution


batch. Used only by the Distribution
Agents, this is the command ID of the
first command in the failed execution
batch.

session_id int ID of the agent session in which the


error occurred.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpsubscriptionerrors is used with snapshot and transactional replication.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_helpsubscriptionerrors.

See Also
sp_helpsubscription (Transact-SQL)
sp_helpsubscription_properties (Transact-SQL)
sp_helptracertokens (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns one row for each tracer token that has been inserted into a publication to determine latency. This stored
procedure is executed at the Publisher on the publication database or at the Distributor on the distribution
database.
Transact-SQL Syntax Conventions

Syntax
sp_helptracertokens [ @publication = ] 'publication'
[ , [ @publisher = ] 'publisher' ]
[ , [ @publisher_db = ] 'publisher_db' ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication in which tracer tokens were inserted. publication is sysname, with no default.
[ @publisher= ] 'publisher'
The name of the Publisher. publisher is sysname, with a default of NULL.

NOTE
This parameter should only be specified for non- Microsoft SQL Server Publishers.

[ @publisher_db= ] 'publisher_db'
The name of the publication database. publisher_db is sysname, with a default value of NULL. This parameter is
ignored if the stored procedure is executed at the Publisher.

Result Set
COLUMN NAME DATA TYPE DESCRIPTION

tracer_id int Identifies a tracer token record.

publisher_commit datetime The date and time that the token


record was committed at the Publisher
in the publication database.

Return Code Values


0 (success) or 1 (failure)
Remarks
sp_helptracertokens is used in transactional replication.
sp_helptracertokens is used to obtain tracer token IDs when executing sp_helptracertokenhistory (Transact-SQL).

Example
DECLARE @publication AS sysname;
DECLARE @tokenID AS int;
SET @publication = N'AdvWorksProductTran';

USE [AdventureWorks2012]

-- Insert a new tracer token in the publication database.


EXEC sys.sp_posttracertoken
@publication = @publication,
@tracer_token_id = @tokenID OUTPUT;
SELECT 'The ID of the new tracer token is ''' +
CONVERT(varchar,@tokenID) + '''.'
GO

-- Wait 10 seconds for the token to make it to the Subscriber.


WAITFOR DELAY '00:00:10';
GO

-- Get latency information for the last inserted token.


DECLARE @publication AS sysname;
DECLARE @tokenID AS int;
SET @publication = N'AdvWorksProductTran';

CREATE TABLE #tokens (tracer_id int, publisher_commit datetime)

-- Return tracer token information to a temp table.


INSERT #tokens (tracer_id, publisher_commit)
EXEC sys.sp_helptracertokens @publication = @publication;
SET @tokenID = (SELECT TOP 1 tracer_id FROM #tokens
ORDER BY publisher_commit DESC)
DROP TABLE #tokens

-- Get history for the tracer token.


EXEC sys.sp_helptracertokenhistory
@publication = @publication,
@tracer_id = @tokenID;
GO

Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role in the publication database,
or db_owner fixed database or replmonitor roles in the distribution database can execute
sp_helptracertokenhistory.

See Also
Measure Latency and Validate Connections for Transactional Replication
sp_deletetracertokenhistory (Transact-SQL)
sp_helptracertokenhistory (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns detailed latency information for specified tracer tokens, with one row being returned for each Subscriber.
This stored procedure is executed at the Publisher on the publication database or at the Distributor on the
distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_helptracertokenhistory [ @publication = ] 'publication'
, [ @tracer_id = ] tracer_id
[ , [ @publisher = ] 'publisher' ]
[ , [ @publisher_db = ] 'publisher_db' ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication in which the tracer token was inserted. publication is sysname, with no default.
[ @tracer_id= ] tracer_id
Is the ID of the tracer token in the MStracer_tokens (Transact-SQL) table for which history information is returned.
tracer_id is int, with no default.
[ @publisher= ] 'publisher'
The name of the Publisher. publisher is sysname, with a default of NULL.

NOTE
This parameter should only be specified for non- Microsoft SQL Server Publishers.

[ @publisher_db= ] 'publisher_db'
The name of the publication database. publisher_db is sysname, with a default value of NULL. This parameter is
ignored if the stored procedure is executed at the Publisher.

Result Set
COLUMN NAME DATA TYPE DESCRIPTION

distributor_latency bigint Number of seconds between the tracer


token record being committed at the
Publisher and the record being
committed at the Distributor.

subscriber sysname Name of the Subscriber that received


the tracer token.
COLUMN NAME DATA TYPE DESCRIPTION

subscriber_db sysname Name of the subscription database into


which the tracer token record was
inserted.

subscriber_latency bigint Number of seconds between the tracer


token record being committed at the
Distributor and the record being
committed at the Subscriber.

overall_latency bigint Number of seconds between the tracer


token record being committed at the
Publisher and token record being
committed at the Subscriber.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helptracertokenhistory is used in transactional replication.
Execute sp_helptracertokens (Transact-SQL) to obtain a list of tracer tokens for the publication.
A value of NULL in the result set means that latency statistics cannot be calculated. This is because the tracer token
has not been received at the Distributor or one of the Subscribers.

Example
DECLARE @publication AS sysname;
DECLARE @tokenID AS int;
SET @publication = N'AdvWorksProductTran';

USE [AdventureWorks2012]

-- Insert a new tracer token in the publication database.


EXEC sys.sp_posttracertoken
@publication = @publication,
@tracer_token_id = @tokenID OUTPUT;
SELECT 'The ID of the new tracer token is ''' +
CONVERT(varchar,@tokenID) + '''.'
GO

-- Wait 10 seconds for the token to make it to the Subscriber.


WAITFOR DELAY '00:00:10';
GO

-- Get latency information for the last inserted token.


DECLARE @publication AS sysname;
DECLARE @tokenID AS int;
SET @publication = N'AdvWorksProductTran';

CREATE TABLE #tokens (tracer_id int, publisher_commit datetime)

-- Return tracer token information to a temp table.


INSERT #tokens (tracer_id, publisher_commit)
EXEC sys.sp_helptracertokens @publication = @publication;
SET @tokenID = (SELECT TOP 1 tracer_id FROM #tokens
ORDER BY publisher_commit DESC)
DROP TABLE #tokens

-- Get history for the tracer token.


EXEC sys.sp_helptracertokenhistory
@publication = @publication,
@tracer_id = @tokenID;
GO

Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role in the publication database,
or db_owner fixed database or replmonitor roles in the distribution database can execute
sp_helptracertokenhistory.

See Also
Measure Latency and Validate Connections for Transactional Replication
sp_deletetracertokenhistory (Transact-SQL)
sp_helpxactsetjob (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Displays information on the Xactset job for an Oracle Publisher. This stored procedure is executed at the Distributor
on any database.
Transact-SQL Syntax Conventions

Syntax
sp_helpxactsetjob [ @publisher = ] 'publisher'

Arguments
[@publisher = ] 'publisher'
Is the name of the non- SQL Server Publisher to which the job belongs. publisher is sysname, with no default.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

jobnumber int Oracle job number.

lastdate varchar(22) Last date that the job ran.

thisdate varchar(22) Time of change

nextdate varchar(22) Next date that the job will run.

broken varchar(1) Flag indicating if the job is broken.

interval varchar(200) Interval for the job.

failures int Number of failures for the job.

xactsetjobwhat varchar(200) Name of procedure executed by the job.

xactsetjob varchar(1) Status of the job, which can be one of


the following:

1 - the job is enabled.

0 - the job is disabled.

xactsetlonginterval int Long interval for the job.


COLUMN NAME DATA TYPE DESCRIPTION

xactsetlongthreshold int Long threshold for the job.

xactsetshortinterval int Short interval for the job.

xactsetshortthreshold int Short threshold for the job.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_helpxactsetjob is used in snapshot replication and transactional replication for an Oracle Publishers.
sp_helpxactsetjob always returns the current settings for the Xactset job (HREPL_XactSetJob) at the publisher. If
the Xactset job is currently in the job queue, it additionally returns attributes of the job from the USER_JOB data
dictionary view created under the administrator account at the Oracle Publisher.

Permissions
Only a member of the sysadmin fixed server role can execute sp_helpxactsetjob.

See Also
Configure the Transaction Set Job for an Oracle Publisher (Replication Transact-SQL Programming)
sp_publisherproperty (Transact-SQL)
sp_ivindexhasnullcols (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Validates that the clustered index of the indexed view is unique, and does not contain any column that can be null
when the indexed view is going to be used to create a transactional publication. This stored procedure is executed
at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_ivindexhasnullcols [ @viewname = ] 'view_name'
, [ @fhasnullcols= ] field_has_null_columns OUTPUT

Arguments
[ @viewname= ] 'view_name'
Is the name of the view to verify. view_name is sysname, with no default.
[ @fhasnullcols= ] field_has_null_columns OUTPUT
Is the flag indicating whether the view index has columns that allow NULL. view_name is sysname, with no default.
Returns a value of 1 if the view index has columns that allow NULL. Returns a value of 0 if the view does not
contain columns that allow NULLS.

NOTE
If the stored procedure itself returns a return code of 1, meaning the stored procedure execution had a failure, this value is 0
and should be ignored.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_ivindexhasnullcols is used by transactional replication.
By default, indexed view articles in a publication are created as tables at the Subscribers. However, when the
indexed column allows NULL values, the indexed view is created as an indexed view at the Subscriber instead of a
table. By executing this stored procedure, it can alert the user to whether or not this problem exists with the current
indexed view.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_ivindexhasnullcols.
See Also
System Stored Procedures (Transact-SQL)
sp_link_publication (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Sets the configuration and security information used by synchronization triggers of immediate updating
subscriptions when connecting to the Publisher. This stored procedure is executed at the Subscriber on the
subscription database.

IMPORTANT
When configuring a Publisher with a remote Distributor, the values supplied for all parameters, including job_login and
job_password, are sent to the Distributor as plain text. You should encrypt the connection between the Publisher and its
remote Distributor before executing this stored procedure. For more information, see Enable Encrypted Connections to the
Database Engine (SQL Server Configuration Manager).

IMPORTANT
Under certain conditions, this stored procedure can fail if the Subscriber is running Microsoft SQL Server 2005 Service Pack 1
or later, and the Publisher is running an earlier version. If the stored procedure fails in this scenario, upgrade the Publisher to
SQL Server 2005 Service Pack 1 or later.

Transact-SQL Syntax Conventions

Syntax
sp_link_publication [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
, [ @security_mode = ] security_mode
[ , [ @login = ] 'login' ]
[ , [ @password = ]'password' ]
[ , [ @distributor = ] 'distributor' ]

Arguments
[ @publisher= ] 'publisher'
Is the name of the Publisher to link to. publisher is sysname, with no default.
[ @publisher_db= ] 'publisher_db'
Is the name of the Publisher database to link to. publisher_db is sysname, with no default.
[ @publication= ] 'publication'
Is the name of the publication to link to. publication is sysname, with no default.
[ @security_mode= ] security_mode
Is the security mode used by the Subscriber to connect to a remote Publisher for immediate updating.
security_mode is int, and can be one of these values. When possible, use Windows Authentication.
VALUE DESCRIPTION

0 Uses SQL Server Authentication with the login specified in this


stored procedure as login and password.

Note: In previous versions of SQL Server, this option was used


to specify a dynamic remote procedure call (RPC).

1 Uses the security context ( SQL Server Authentication or


Windows Authentication) of the user making the change at
the Subscriber.

Note: This account must also exist at the Publisher with


sufficient privileges. When using Windows Authentication,
security account delegation must be supported.

2 Uses an existing, user-defined linked server login created


using sp_link_publication.

[ @login= ] 'login'
Is the login. login is sysname, with a default of NULL. This parameter must be specified when security_mode is 0.
[ @password= ] 'password'
Is the password. password is sysname, with a default of NULL. This parameter must be specified when
security_mode is 0.
[ @distributor= ] 'distributor'
Is the name of the Distributor. distributor is sysname, with a default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_link_publication is used by immediate updating subscriptions in transactional replication.
sp_link_publication can be used for both push and pull subscriptions. It can be called before or after the
subscription is created. An entry is inserted or updated in the MSsubscription_properties (Transact-SQL) system
table.
For push subscriptions, the entry can be cleaned up by sp_subscription_cleanup (Transact-SQL). For pull
subscriptions, the entry can be cleaned up by sp_droppullsubscription (Transact-SQL) or sp_subscription_cleanup
(Transact-SQL). You can also call sp_link_publication with a NULL password to clear the entry in the
MSsubscription_properties (Transact-SQL) system table for security concerns.
The default mode used by an immediate updating Subscriber when it connects to the Publisher does not allow a
connection using Windows Authentication. To connect with a mode of Windows Authentication, a linked server has
to be set up to the Publisher, and the immediate updating Subscriber should use this connection when updating
the Subscriber. This requires the sp_link_publication to be run with security_mode = 2. When using Windows
Authentication, security account delegation must be supported.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

-- Execute this batch at the Subscriber.


DECLARE @publication AS sysname;
DECLARE @publicationDB AS sysname;
DECLARE @publisher AS sysname;
DECLARE @login AS sysname;
DECLARE @password AS nvarchar(512);
SET @publication = N'AdvWorksProductTran';
SET @publicationDB = N'AdventureWorks2012';
SET @publisher = $(PubServer);
SET @login = $(Login);
SET @password = $(Password);

-- At the subscription database, create a pull subscription to a transactional


-- publication using immediate updating with queued updating as a failover.
EXEC sp_addpullsubscription
@publisher = @publisher,
@publication = @publication,
@publisher_db = @publicationDB,
@update_mode = N'failover',
@subscription_type = N'pull';

-- Add an agent job to synchronize the pull subscription,


-- which uses Windows Authentication when connecting to the Distributor.
EXEC sp_addpullsubscription_agent
@publisher = @publisher,
@publisher_db = @publicationDB,
@publication = @publication,
@job_login = @login,
@job_password = @password;

-- Add a Windows Authentication-based linked server that enables the


-- Subscriber-side triggers to make updates at the Publisher.
EXEC sp_link_publication
@publisher = @publisher,
@publication = @publication,
@publisher_db = @publicationDB,
@security_mode = 0,
@login = @login,
@password = @password;
GO

USE AdventureWorks2012
GO

-- Execute this batch at the Publisher.


DECLARE @publication AS sysname;
DECLARE @subscriptionDB AS sysname;
DECLARE @subscriber AS sysname;
SET @publication = N'AdvWorksProductTran';
SET @subscriptionDB = N'AdventureWorks2012Replica';
SET @subscriber = $(SubServer);

-- At the Publisher, register the subscription, using the defaults.


USE [AdventureWorks2012]
EXEC sp_addsubscription
@publication = @publication,
@subscriber = @subscriber,
@destination_db = @subscriptionDB,
@subscription_type = N'pull',
@update_mode = N'failover';
GO

Permissions
Only members of the sysadmin fixed server role can execute sp_link_publication.

See Also
sp_droppullsubscription (Transact-SQL)
sp_helpsubscription_properties (Transact-SQL)
sp_subscription_cleanup (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_lookupcustomresolver (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the information on a business logic handler or the class identifier (CLSID) value of a COM-based custom
resolver component that is registered at the Distributor. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_lookupcustomresolver [ @article_resolver = ] 'article_resolver'
[, [ @resolver_clsid = ] 'resolver_clsid' OUTPUT ]
[ , [ @is_dotnet_assembly = ] is_dotnet_assembly OUTPUT ]
[ , [ @dotnet_assembly_name = ] 'dotnet_assembly_name' OUTPUT ]
[ , [ @dotnet_class_name = ] 'dotnet_class_name' OUTPUT ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @article_resolver = ] 'article_resolver'
Specifies the name of the custom business logic being unregistered. article_resolver is nvarchar(255), with no
default. If the business logic being removed is a COM component, then this parameter is the friendly name of the
component. If the business logic is a Microsoft .NET Framework assembly, then this parameter is the name of the
assembly.
[ @resolver_clsid= ] 'resolver_clsid' OUTPUT
Is the CLSID value of the COM object associated with the name of the custom business logic specified in the
article_resolver parameter. resolver_clsid is nvarchar(50), with a default of NULL.
[ @is_dotnet_assembly= ] 'is_dotnet_assembly' OUTPUT
Specifies the type of custom business logic that is being registered. is_dotnet_assembly is bit, with a default of 0. 1
indicates that the custom business logic being registered is a business logic handler Assembly; 0 indicates that it is
a COM component.
[ @dotnet_assembly_name= ] 'dotnet_assembly_name' OUTPUT
Is the name of the assembly that implements the business logic handler. dotnet_assembly_name is
nvarchar(255), with a default value of NULL.
[ @dotnet_class_name= ] 'dotnet_class_name' OUTPUT
Is the name of the class that overrides BusinessLogicModule to implement the business logic handler.
dotnet_class_name is nvarchar(255), with a default value of NULL.
[ @publisher= ] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default value of NULL. Use this parameter when the
stored procedure is not called from the Publisher. If not specified, it is assumed that the local server is the
Publisher.
Return Code Values
0 (success) or 1 (failure)

Remarks
sp_lookupcustomresolver is used in merge replication.
sp_lookupcustomresolver returns a NULL value for resolver_clsid when the component is not registered at the
Distribution and a value of "00000000-0000-0000-0000-000000000000" when the registration belongs to a .NET
Framework assembly registered as a business logic handler.
sp_lookupcustomresolver is called by sp_addmergearticle and sp_changemergearticle to validate the specified
article_resolver.

Permissions
Only members of the db_owner fixed database role on the publication database can execute
sp_lookupcustomresolver.

See Also
Advanced Merge Replication Conflict Detection and Resolution
Execute Business Logic During Merge Synchronization
Implement a Business Logic Handler for a Merge Article
Specify a Merge Article Resolver
sp_registercustomresolver (Transact-SQL)
sp_unregistercustomresolver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_markpendingschemachange (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Used for supportability of merge publications by enabling an administrator to skip selected pending schema
changes so that they will not be replicated. This stored procedure is executed at the Publisher on the publication
database.
Cau t i on

This stored procedure can cause schema changes not to be replicated. It should only be used to resolve issues after
other methods, such as reinitialization, have already been tried or are too expensive in terms of performance.

Syntax
sp_markpendingschemachange [@publication = ] 'publication'
[ , [ @schemaversion = ] schemaversion ]
[ , [ @status = ] 'status' ]

Arguments
[@publication= ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @schemaversion= ] schemaversion
Identifies a pending schema change. schemaversion is int, with a default value of 0. Use
sp_enumeratependingschemachanges (Transact-SQL) to list the pending schema changes for the publication.
[ @status= ] 'status'
Is whether a pending schema change will be skipped. status is nvarchar(10) with a default value of active. If the
value of status is skipped, then the selected schema change will not be replicated.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_markpendingschemachange is used with merge replication.
sp_markpendingschemachange is a stored procedure intended for the supportability of merge replication and
should be used only when other corrective actions, such as reinitialization, have failed to correct the situation or
are too expensive in terms of performance.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_markpendingschemachange.
See Also
sysmergeschemachange (Transact-SQL)
sp_marksubscriptionvalidation (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Marks the current open transaction to be a subscription-level validation transaction for the specified subscriber.
This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_marksubscriptionvalidation [ @publication = ] 'publication'
, [ @subscriber = ] 'subscriber'
, [ @destination_db = ] 'destination_db'
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @subscriber= ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with no default.
[ @destination_db=] 'destination_db'
Is the name of the destination database. destination_db is sysname, with no default.
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used for a publication that belongs to a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_marksubscriptionvalidation is used in transactional replication.
sp_marksubscriptionvalidation does not support non- SQL Server Subscribers.
For non- SQL Server Publishers, you cannot execute sp_marksubscriptionvalidation from within an explicit
transaction. This is because explicit transactions are not supported over the linked server connection used to access
the Publisher.
sp_marksubscriptionvalidation must be used together with sp_article_validation (Transact-SQL), specifying a
value of 1 for subscription_level, and can be used with other calls to sp_marksubscriptionvalidation to mark the
current open transaction for other subscribers.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_marksubscriptionvalidation.

Example
The following query can be applied to the publishing database to post subscription-level validation commands.
These commands are picked up by the Distribution Agents of specified Subscribers. Note that the first transaction
validates article 'art1', while the second transaction validates 'art2'. Also note that the calls to
sp_marksubscriptionvalidation and sp_article_validation (Transact-SQL) have been encapsulated in a
transaction. We recommend only one call to sp_article_validation (Transact-SQL) per transaction. This is because
sp_article_validation (Transact-SQL) holds a shared table lock on the source table for the duration of the
transaction. You should keep the transaction short to maximize concurrency.

begin tran

exec sp_marksubscriptionvalidation @publication = 'pub1',


@subscriber = 'Sub', @destination_db = 'SubDB'

exec sp_marksubscriptionvalidation @publication = 'pub1',


@subscriber = 'Sub2', @destination_db = 'SubDB'

exec sp_article_validation @publication = 'pub1', @article = 'art1',


@rowcount_only = 0, @full_or_fast = 0, @shutdown_agent = 0,
@subscription_level = 1

commit tran

begin tran

exec sp_marksubscriptionvalidation @publication = 'pub1',


@subscriber = 'Sub', @destination_db = 'SubDB'

exec sp_marksubscriptionvalidation @publication = 'pub1',


@subscriber = 'Sub2', @destination_db = 'SubDB'

exec sp_article_validation @publication = 'pub1', @article = 'art2',


@rowcount_only = 0, @full_or_fast = 0, @shutdown_agent = 0,
@subscription_level = 1

commit tran

See Also
System Stored Procedures (Transact-SQL)
Validate Replicated Data
sp_mergearticlecolumn (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Partitions a merge publication vertically. This stored procedure is executed at the Publisher on the publication
database.
Transact-SQL Syntax Conventions

Syntax
sp_mergearticlecolumn [ @publication = ] 'publication'
, [ @article = ] 'article'
[ , [ @column = ] 'column'
[ , [ @operation = ] 'operation'
[ , [ @schema_replication = ] 'schema_replication' ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]

Arguments
[ @publication =] 'publication'
Is the name of the publication. Publication is sysname, with no default.
[ @article =] 'article'
Is the name of the article in the publication. article is sysname, with no default.
[ @column =] 'column'
Identifies the columns on which to create the vertical partition. column is sysname, with a default of NULL. If NULL
and @operation = N'add' , all columns in the source table are added to the article by default. column cannot be
NULL when operation is set to drop. To exclude columns from an article, execute sp_mergearticlecolumn and
specify column and @operation = N'drop' for each column to be removed from the specified article.
[ @operation =] 'operation'
Is the replication status. operation is nvarchar(4), with a default of ADD. add marks the column for replication.
drop clears the column.
[ @schema_replication=] 'schema_replication'
Specifies that a schema change will be propagated when the Merge Agent runs. schema_replication is
nvarchar(5), with a default of FALSE.

NOTE
Only FALSE is supported for schema_replication.

[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Enables or disables the ability to have a snapshot invalidated. force_invalidate_snapshot is a bit, with a default of 0.
0 specifies that changes to the merge article will not cause the snapshot to be invalid.
1 specifies that changes to the merge article may cause the snapshot to be invalid, and if that is the case, a value of
1 gives permission for the new snapshot to occur.
[ @force_reinit_subscription = ]force_reinit_subscription
Enables or disables the ability to have the subscription reinitializated. force_reinit_subscription is a bit with a default
of 0.
0 specifies that changes to the merge article will not cause the subscription to be reinitialized.
1 specifies that changes to the merge article may cause the subscription to be reinitialized, and if that is the case, a
value of 1 gives permission for the subscription reinitialization to occur.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_mergearticlecolumn is used in merge replication.
An identity column cannot be dropped from the article if automatic identity range management is being used. For
more information, see Replicate Identity Columns.
If an application sets a new vertical partition after the initial snapshot is created, a new snapshot must be generated
and reapplied to each subscription. Snapshots are applied when the next scheduled snapshot and distribution or
merge agent run.
If row tracking is used for conflict detection (the default), the base table can include a maximum of 1,024 columns,
but columns must be filtered from the article so that a maximum of 246 columns is published. If column tracking is
used, the base table can include a maximum of 246 columns.

Example
DECLARE @publication AS sysname;
DECLARE @table1 AS sysname;
DECLARE @table2 AS sysname;
DECLARE @table3 AS sysname;
DECLARE @salesschema AS sysname;
DECLARE @hrschema AS sysname;
DECLARE @filterclause AS nvarchar(1000);
SET @publication = N'AdvWorksSalesOrdersMerge';
SET @table1 = N'Employee';
SET @table2 = N'SalesOrderHeader';
SET @table3 = N'SalesOrderDetail';
SET @salesschema = N'Sales';
SET @hrschema = N'HumanResources';
SET @filterclause = N'Employee.LoginID = HOST_NAME()';

-- Add a filtered article for the Employee table.


EXEC sp_addmergearticle
@publication = @publication,
@article = @table1,
@source_object = @table1,
@type = N'table',
@source_owner = @hrschema,
@schema_option = 0x0004CF1,
@description = N'article for the Employee table',
@subset_filterclause = @filterclause;

-- Add an article for the SalesOrderHeader table that is filtered


-- based on Employee and horizontally filtered.
EXEC sp_addmergearticle
EXEC sp_addmergearticle
@publication = @publication,
@article = @table2,
@source_object = @table2,
@type = N'table',
@source_owner = @salesschema,
@vertical_partition = N'true',
@schema_option = 0x0034EF1,
@description = N'article for the SalesOrderDetail table';

-- Add an article for the SalesOrderDetail table that is filtered


-- based on SaledOrderHeader.
EXEC sp_addmergearticle
@publication = @publication,
@article = @table3,
@source_object = @table3,
@source_owner = @salesschema,
@description = 'article for the SalesOrderHeader table',
@identityrangemanagementoption = N'auto',
@pub_identity_range = 100000,
@identity_range = 100,
@threshold = 80,
@schema_option = 0x0004EF1;

-- Add all columns to the SalesOrderHeader article.


EXEC sp_mergearticlecolumn
@publication = @publication,
@article = @table2,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Remove the credit card Approval Code column.


EXEC sp_mergearticlecolumn
@publication = @publication,
@article = @table2,
@column = N'CreditCardApprovalCode',
@operation = N'drop',
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Add a merge join filter between Employee and SalesOrderHeader.


EXEC sp_addmergefilter
@publication = @publication,
@article = @table2,
@filtername = N'SalesOrderHeader_Employee',
@join_articlename = @table1,
@join_filterclause = N'Employee.BusinessEntityID = SalesOrderHeader.SalesPersonID',
@join_unique_key = 1,
@filter_type = 1,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;

-- Add a merge join filter between SalesOrderHeader and SalesOrderDetail.


EXEC sp_addmergefilter
@publication = @publication,
@article = @table3,
@filtername = N'SalesOrderDetail_SalesOrderHeader',
@join_articlename = @table2,
@join_filterclause = N'SalesOrderHeader.SalesOrderID = SalesOrderDetail.SalesOrderID',
@join_unique_key = 1,
@filter_type = 1,
@force_invalidate_snapshot = 1,
@force_reinit_subscription = 1;
GO

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_mergearticlecolumn.

See Also
Define and Modify a Join Filter Between Merge Articles
Define and Modify a Parameterized Row Filter for a Merge Article
Filter Published Data
Replication Stored Procedures (Transact-SQL)
sp_mergecleanupmetadata (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Should be used only in replication topologies that include servers running versions of Microsoft SQL Server prior
to SQL Server 2000 Service Pack 1.sp_mergecleanupmetadata allows administrators to clean up metadata in the
MSmerge_genhistory, MSmerge_contents and MSmerge_tombstone system tables. This stored procedure is
executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_mergecleanupmetadata [ [ @publication = ] 'publication' ]
[ , [ @reinitialize_subscriber = ] 'reinitialize_subscriber' ]

Arguments
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with a default of %, which cleans up metadata for all
publications. The publication must already exist if explicitly specified.
[ @reinitialize_subscriber = ] 'subscriber'
Specifies whether to reinitialize the Subscriber. subscriber is nvarchar(5), can be TRUE or FALSE, with a default of
TRUE. If TRUE, subscriptions are marked for reinitialization. If FALSE, the subscriptions are not marked for
reinitialization.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_mergecleanupmetadata should be used only in replication topologies that include servers running versions
of SQL Server prior to SQL Server 2000 Service Pack 1. Topologies that include only SQL Server 2000 Service Pack
1 or later should use automatic retention based metadata cleanup. When running this stored procedure, be aware
of the necessary and potentially large growth of the log file on the computer on which the stored procedure is
running.
Cau t i on

After sp_mergecleanupmetadata is executed, by default, all subscriptions at the Subscribers of publications that
have metadata stored in MSmerge_genhistory, MSmerge_contents and MSmerge_tombstone are marked for
reinitialization, any pending changes at the Subscriber are lost, and the current snapshot is marked obsolete.
NOTE
If there are multiple publications on a database, and any one of those publications uses an infinite publication retention
period (@retention=0), running sp_mergecleanupmetadata does not clean up the merge replication change tracking
metadata for the database. For this reason, use infinite publication retention with caution.

When executing this stored procedure, you can choose whether to reinitialize Subscribers by setting the
@reinitialize_subscriber parameter to TRUE (the default) or FALSE. If sp_mergecleanupmetadata is executed
with the @reinitialize_subscriber parameter set to TRUE, a snapshot is reapplied at the Subscriber even if the
subscription was created without an initial snapshot (for example, if the snapshot data and schema were manually
applied or already existed at the Subscriber). Setting the parameter to FALSE should be used with caution, because
if the publication is not reinitialized, you must ensure that data at the Publisher and Subscriber is synchronized.
Regardless of the value of @reinitialize_subscriber, sp_mergecleanupmetadata fails if there are ongoing
merge processes that are attempting to upload changes to a Publisher or a republishing Subscriber at the time the
stored procedure is invoked.
Executing sp_mergecleanupmetadata with @reinitialize_subscriber = TRUE:
1. It is recommended, but not required, that you stop all updates to the publication and subscription databases.
If updates continue, any updates made at a Subscriber since the last merge are lost when the publication is
reinitialized, but data convergence is maintained.
2. Execute a merge by running the Merge Agent. We recommend that you use the –Validate agent command
line option at each Subscriber when you run the Merge Agent. If you are running continuous mode merges,
see Special Considerations for Continuous Mode Merges later in this section.
3. After all merges have completed, execute sp_mergecleanupmetadata.
4. Execute sp_reinitmergepullsubscription on all subscribers using named or anonymous pull subscription
to ensure data convergence.
5. If you are running continuous mode merges, see Special Considerations for Continuous Mode Merges later
in this section.
6. Regenerate snapshot files for all merge publications involved at all levels. If you try to merge without
regenerating the snapshot first, you receive a prompt to regenerate the snapshot.
7. Back up the publication database. Failure to do so can cause a merge failure after a restore of the publication
database.
Executing sp_mergecleanupmetadata with @reinitialize_subscriber = FALSE:
8. Stop all updates to the publication and subscription databases.
9. Execute a merge by running the Merge Agent. We recommend that you use the –Validate agent command
line option at each Subscriber when you run the Merge Agent. If you are running continuous mode merges,
see Special Considerations for Continuous Mode Merges later in this section.
10. After all merges have completed, execute sp_mergecleanupmetadata.
11. If you are running continuous mode merges, see Special Considerations for Continuous Mode Merges later
in this section.
12. Regenerate snapshot files for all merge publications involved at all levels. If you try to merge without
regenerating the snapshot first, you receive a prompt to regenerate the snapshot.
13. Back up the publication database. Failure to do so can cause a merge failure after a restore of the publication
database.
Special Considerations for Continuous Mode Merges
If you are running continuous-mode merges, you must either:
Stop the Merge Agent, and then perform another merge without the -Continuous parameter specified.
Deactivate the publication with sp_changemergepublication to ensure that any continuous-mode merges
that are polling for the publication status fail.

EXEC central..sp_changemergepublication @publication = 'dynpart_pubn', @property = 'status', @value =


'inactive'

When you have completed step 3 of running sp_mergecleanupmetadata, resume continuous mode
merges based on how you stopped them. Either:
Add the –Continuous parameter back for the Merge Agent.
Reactivate the publication with sp_changemergepublication.

EXEC central..sp_changemergepublication @publication = 'dynpart_pubn', @property = 'status', @value =


'active'

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_mergecleanupmetadata.
To use this stored procedure, the Publisher must be running SQL Server 2000. The Subscribers must be running
either SQL Server 2000 or Microsoft SQL Server 7.0, Service Pack 2.

See Also
MSmerge_genhistory (Transact-SQL)
MSmerge_contents (Transact-SQL)
MSmerge_tombstone (Transact-SQL)
sp_mergedummyupdate (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Does a dummy update on the given row so that it is sent again during the next merge. This stored procedure can
be executed at the Publisher, on the publication database, or at the Subscriber, on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_mergedummyupdate [ @source_object =] 'source_object', [ @rowguid =] 'rowguid'

Arguments
[ @source_object=] 'source_object'
Is the name of the source object. source_objectis nvarchar(386), with no default.
[ @rowguid=] 'rowguid'
Is the row identifier. rowguid is uniqueidentifier, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_mergedummyupdate is used in merge replication.
sp_mergedummyupdate is useful if you write your own alternative to the Replication Conflict Viewer
(Wzcnflct.exe).

Permissions
Only members of the db_owner fixed database role can execute sp_mergedummyupdate.

See Also
System Stored Procedures (Transact-SQL)
sp_mergemetadataretentioncleanup (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Performs a manual cleanup of metadata in the MSmerge_genhistory, MSmerge_contents, MSmerge_tombstone,
MSmerge_past_partition_mappings, and MSmerge_current_partition_mappings system tables. This stored
procedure is executed at each Publisher and Subscriber in the topology.
Transact-SQL Syntax Conventions

Syntax
sp_mergemetadataretentioncleanup [ [ @num_genhistory_rows = ] num_genhistory_rows OUTPUT ]
[ , [ @num_contents_rows = ] num_contents_rows OUTPUT ]
[ , [ @num_tombstone_rows = ] num_tombstone_rows OUTPUT ]
[ , [ @aggressive_cleanup_only = ] aggressive_cleanup_only ]

Arguments
[ @num_genhistory_rows= ] num_genhistory_rows OUTPUT
Returns the number of rows cleaned-up from the MSmerge_genhistory table. num_genhistory_rows is int, with a
default of 0.
[ @num_contents_rows= ] num_contents_rows OUTPUT
Returns the number of rows cleaned-up from the MSmerge_contents table. num_contents_rows is int, with a
default of 0.
[ @num_tombstone_rows= ] num_tombstone_rows OUTPUT
Returns the number of rows cleaned-up from the MSmerge_tombstone table. num_tombstone_rows is int, with a
default of 0.
[ @aggressive_cleanup_only= ] aggressive_cleanup_only
Internal use only.

Return Code Values


0 (success) or 1 (failure)

Remarks
IMPORTANT
If there are multiple publications on a database, and any one of those publications uses an infinite publication retention
period, running sp_mergemetadataretentioncleanup does not clean up the merge replication change tracking metadata
for the database. For this reason, use infinite publication retention with caution. To determine if a publication has an infinite
retention period, execute sp_helpmergepublication (Transact-SQL) at the Publisher and note any publications in the result set
with a value of 0 for retention.
Permissions
Only members of the db_owner fixed database role or users in the publication access list for a published database
can execute sp_mergemetadataretentioncleanup.

See Also
System Stored Procedures (Transact-SQL)
sp_mergesubscription_cleanup (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes metadata, such as triggers and entries, in sysmergesubscriptions and sysmergearticles after the
specified merge push subscription is removed at the Publisher. This stored procedure is run at the Subscriber on
the subscription database.

NOTE
For a pull subscription, metadata is removed when sp_dropmergepullsubscription (Transact-SQL) is executed.

Transact-SQL Syntax Conventions

Syntax
sp_mergesubscription_cleanup [ @publisher =] 'publisher'
, [ @publisher_db =] 'publisher_db'
, [ @publication =] 'publication'

Arguments
[ @publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[ @publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_mergesubscription_cleanup is used in merge replication.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_mergesubscription_cleanup.

See Also
Delete a Push Subscription
sp_expired_subscription_cleanup (Transact-SQL)
sp_subscription_cleanup (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_MSchange_distribution_agent_properties
(Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the properties of a Distribution Agent job that runs at a Microsoft SQL Server 2005 or later version
Distributor. This stored procedure is used to change properties when the Publisher runs on an instance of SQL
Server 2000. This stored procedure is executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_MSchange_distribution_agent_properties [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
, [ @subscriber = ] 'subscriber'
, [ @subscriber_db = ] 'subscriber_db'
, [ @property = ] 'property'
, [ @value = ] 'value' ]

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db= ] 'publisher_db'
Is the name of the publication database. publisher_db is sysname, with no default.
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @subscriber= ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with no default.
[ @subscriber_db= ] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with no default.
[ @property = ] 'property'
Is the publication property to change. property is sysname, with no default.
[ @value = ] 'value'
Is the new property value. value is nvarchar(524), with a default of NULL.
This table describes the properties of the Distribution Agent job that can be changed, and restrictions on the values
for those properties.
PROPERTY VALUE DESCRIPTION

distrib_job_login Login for the Microsoft Windows


account under which the agent runs.

distrib_job_password Password for the Windows account


under which the agent job runs.

subscriber_catalog Catalog to be used when making a


connection to the OLE DB provider. This
property is only valid for non- SQL
Server Subscribers.

subscriber_datasource Name of the data source as understood


by the OLE DB provider. This property
is only valid for non- SQL Server
Subscribers.

subscriber_location Location of the database as understood


by the OLE DB provider. This property
is only valid for non- SQL Server
Subscribers.

subscriber_login Login to use when connecting to a


Subscriber to synchronize the
subscription.

subscriber_password Subscriber password.

Do not use a blank password. Use a


strong password.

subscriber_provider Unique programmatic identifier


(PROGID) with which the OLE DB
provider for the non- SQL Server data
source is registered. This property is
only valid for non- SQL Server
Subscribers.

subscriber_providerstring OLE DB provider-specific connection


string that identifies the data source.
This property is only valid for non-SQL
Server Subscribers.

subscriber_security_mode 1 Windows Authentication.

When possible, use Windows


Authentication.

0 SQL Server Authentication.

subscriber_type 0 SQL Server Subscriber

1 ODBC data source server

3 OLE DB provider
PROPERTY VALUE DESCRIPTION

subscriptionstreams Denotes the number of connections


allowed per Distribution Agent to apply
batches of changes in parallel to a
Subscriber. Not supported for non- SQL
Server Subscribers, Oracle Publishers,
or peer-to-peer subscriptions.

NOTE
After changing an agent login or password, you must stop and restart the agent before the change takes effect.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_MSchange_distribution_agent_properties is used in snapshot replication and transactional replication.
When the Publisher runs on an instance of SQL Server 2005 or later version, you should use
sp_changesubscription to change properties of a Merge Agent job that synchronizes a push subscription that runs
at the Distributor.

Permissions
Only members of the sysadmin fixed server role at the Distributor can execute
sp_MSchange_distribution_agent_properties.

See Also
sp_addpushsubscription_agent (Transact-SQL)
sp_addsubscription (Transact-SQL)
sp_MSchange_merge_agent_properties (Transact-
SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the properties of a Merge Agent job that runs at a Microsoft SQL Server 2005 or later version Distributor.
This stored procedure is used to change properties when the Publisher runs on an instance of SQL Server 2000.
This stored procedure is executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_MSchange_merge_agent_properties [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
, [ @subscriber = ] 'subscriber'
, [ @subscriber_db = ] 'subscriber_db'
, [ @property = ] 'property'
, [ @value = ] 'value' ]

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db= ] 'publisher_db'
Is the name of the publication database. publisher_db is sysname, with no default.
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @subscriber= ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with no default.
[ @subscriber_db= ] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with no default.
[ @property = ] 'property'
Is the publication property to change. property is sysname, with no default.
[ @value = ] 'value'
Is the new property value. value is nvarchar(524), with a default of NULL.
This table describes the properties of the Merge Agent job that can be changed and restrictions on the values for
those properties.
PROPERTY VALUE DESCRIPTION

description A brief description of the subscription.

merge_job_login Login for the Microsoft Windows


account under which the agent runs.

merge_job_password Password for the Windows account


under which the agent job runs.

publisher_login Login to use when connecting to a


Publisher to synchronize the
subscription.

publisher_password Publisher password.

Do not use a blank password. Use a


strong password.

publisher_security_mode 1 Windows Authentication.

When possible, use Windows


Authentication.

0 SQL Server Authentication.

subscriber_login Login to use when connecting to a


Subscriber to synchronize the
subscription.

subscriber_password Subscriber password.

Do not use a blank password. Use a


strong password.

subscriber_security_mode 1 Windows Authentication.

When possible, use Windows


Authentication.

0 SQL Server Authentication.

NOTE
After changing an agent login or password, you must stop and restart the agent before the change takes effect.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_MSchange_merge_agent_properties is used in merge replication.
When the Publisher runs on an instance of SQL Server 2005 or later version, you should use
sp_changemergesubscription to change properties of a Merge Agent job that synchronizes a push subscription that
runs at the Distributor.

Permissions
Only members of the sysadmin fixed server role at the Distributor can execute
sp_MSchange_merge_agent_properties.

See Also
sp_addmergepushsubscription_agent (Transact-SQL)
sp_addmergesubscription (Transact-SQL)
sp_MSchange_logreader_agent_properties (Transact-
SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the properties of a Log Reader Agent job that runs at a Microsoft SQL Server 2005 or later version
Distributor. This stored procedure is used to change properties when the Publisher runs on an instance of SQL
Server 2000. This stored procedure is executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_MSchange_logreader_agent_properties [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publisher_security_mode = ] publisher_security_mode
, [ @publisher_login = ] 'publisher_login'
, [ @publisher_password = ] 'publisher_password'
, [ @job_login = ] 'job_login'
, [ @job_password = ] 'job_password'
, [ @publisher_type = ] 'publisher_type'

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db= ] 'publisher_db'
Is the name of the publication database. publisher_db is sysname, with no default.
[ @publisher_security_mode= ] publisher_security_mode
Is the security mode used by the agent when connecting to the Publisher. publisher_security_mode is smallint,
with no default.
0 specifies SQL Server Authentication.
1 specifies Windows Authentication.
[ @publisher_login= ] 'publisher_login'
Is the login used when connecting to the Publisher. publisher_login is sysname, with no default. publisher_login
must be specified when publisher_security_mode is 0. If publisher_login is NULL and publisher_security_mode is 1,
then the Windows account specified in job_login will be used when connecting to the Publisher.
[ @publisher_password= ] 'publisher_password'
Is the password used when connecting to the Publisher. publisher_password is sysname, with no default.
[ @job_login= ] 'job_login'
Is the login for the Windows account under which the agent runs. job_login is nvarchar(257), with no default. This
cannot be changed for a non- SQL Server publisher.
[ @job_password= ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with no default.
[ @publisher_type= ] 'publisher_type'
Specifies the Publisher type when the Publisher is not running in an instance of SQL Server. publisher_type is
sysname, and can be one of the following values.

VALUE DESCRIPTION

MSSQLSERVER Specifies a SQL Server Publisher.

ORACLE Specifies a standard Oracle Publisher.

ORACLE GATEWAY Specifies an Oracle Gateway Publisher.

For more information about the differences between an Oracle Publisher and an Oracle Gateway Publisher, see
Oracle Publishing Overview.

Remarks
sp_MSchange_logreader_agent_properties is used in transactional replication.
You must specify all parameters when executing sp_MSchange_logreader_agent_properties. Execute
sp_helplogreader_agent (Transact-SQL) to return the current properties of the Log Reader Agent job.
After changing an agent login or password, you must stop and restart the agent before the change takes effect.
When the Publisher runs on an instance of SQL Server 2005 or later version, you should use
sp_changelogreader_agent to change properties of the Log Reader Agent.

Permissions
Only members of the sysadmin fixed server role at the Distributor can execute
sp_MSchange_logreader_agent_properties.

See Also
sp_addlogreader_agent (Transact-SQL)
sp_MSchange_snapshot_agent_properties (Transact-
SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the properties of a Snapshot Agent job that runs at a Microsoft SQL Server 2005 or later version
Distributor. This stored procedure is used to change properties when the Publisher runs on an instance of
Microsoft SQL Server 2000. This stored procedure is executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_MSchange_snapshot_agent_properties [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
, [ @frequency_type= ] frequency_type
, [ @frequency_interval= ] frequency_interval
, [ @frequency_subday= ] frequency_subday
, [ @frequency_subday_interval= ] frequency_subday_interval
, [ @frequency_relative_interval= ] frequency_relative_interval
, [ @frequency_recurrence_factor= ] frequency_recurrence_factor
, [ @active_start_date= ] active_start_date
, [ @active_end_date= ] active_end_date
, [ @active_start_time_of_day= ] active_start_time_of_day
, [ @active_end_time_of_day= ] active_end_time_of_day
, [ @snapshot_job_name = ] 'snapshot_agent_name'
, [ @publisher_security_mode = ] publisher_security_mode
, [ @publisher_login = ] 'publisher_login'
, [ @publisher_password = ] 'publisher_password'
, [ @job_login = ] 'job_login'
, [ @job_password = ] 'job_password'
, [ @publisher_type = ] 'publisher_type'

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db= ] 'publisher_db'
Is the name of the publication database. publisher_db is sysname, with no default.
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @frequency_type = ] frequency_type
Is the frequency with which the Snapshot Agent is executed. frequency_type is int, and can be one of these values.

VALUE DESCRIPTION

1 Once
VALUE DESCRIPTION

2 On demand

4 Daily

8 Weekly

10 Monthly

20 Monthly, relative to the frequency interval

40 When SQL Server Agent starts

[ @frequency_interval = ] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with no default.
[ @frequency_subday = ] frequency_subday
Is the units for freq_subday_interval. frequency_subday is int, and can be one of these values.

VALUE DESCRIPTION

1 Once

2 Second

4 Minute

8 Hour

[ @frequency_subday_interval=] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with no default.
[ @frequency_relative_interval = ] frequency_relative_interval
Is the date the Snapshot Agent runs. frequency_relative_interval is int, with no default.
[ @frequency_recurrence_factor = ] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with no default.
[ @active_start_date = ] active_start_date
Is the date when the Snapshot Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with no
default.
[ @active_end_date = ] active_end_date
Is the date when the Snapshot Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with
no default.
[ @active_start_time_of_day=] active_start_time_of_day
Is the time of day when the Snapshot Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is
int, with no default.
[ @active_end_time_of_day=] active_end_time_of_day
Is the time of day when the Snapshot Agent stops being scheduled, formatted as HHMMSS.
active_end_time_of_day is int, with no default.
[ @snapshot_job_name = ] 'snapshot_agent_name'
Is the name of an existing Snapshot Agent job name if an existing job is being used. snapshot_agent_name is
nvarchar(100), with no default.
[ @publisher_security_mode= ] publisher_security_mode
Is the security mode used by the agent when connecting to the Publisher. publisher_security_mode is int, with no
default. 0 specifies SQL Server Authentication, and 1 specifies Windows Authentication. A value of 0 must be
specified for non- SQL Server Publishers. When possible, use Windows Authentication.
[ @publisher_login= ] 'publisher_login'
Is the login used when connecting to the Publisher. publisher_login is sysname, with no default. publisher_login
must be specified when publisher_security_mode is 0. If publisher_login is NULL and publisher_security_mode is 1,
then the Windows account specified in job_login will be used when connecting to the Publisher.
[ @publisher_password= ] 'publisher_password'
Is the password used when connecting to the Publisher. publisher_password is nvarchar(524), with no default.

IMPORTANT
Do not store authentication information in script files. To help improve security, we recommend that you provide login
names and passwords at run time.

[ @job_login= ] 'job_login'
Is the login for the Windows account under which the agent runs. job_login is nvarchar(257), with no default. This
Windows account is always used for agent connections to the Distributor. You must supply this parameter when
creating a new Snapshot Agent job. This cannot be changed for a non- SQL Server Publisher.
[ @job_password= ] 'job_password'
Is the password for the Windows account under which the agent runs. job_password is sysname, with no default.
You must supply this parameter when creating a new Snapshot Agent job.

IMPORTANT
Do not store authentication information in script files. To help improve security, we recommend that you provide login
names and passwords at run time.

[ @publisher_type= ] 'publisher_type'
Specifies the Publisher type when the Publisher is not running in an instance of SQL Server. publisher_type is
sysname, and can be one of the following values.

VALUE DESCRIPTION

MSSQLSERVER Specifies a SQL Server Publisher.

ORACLE Specifies a standard Oracle Publisher.

ORACLE GATEWAY Specifies an Oracle Gateway Publisher.

For more information about the differences between an Oracle Publisher and an Oracle Gateway Publisher, see
Oracle Publishing Overview.

Return Code Values


0 (success) or 1 (failure)
Remarks
sp_MSchange_snapshot_agent_properties is used in snapshot replication, transactional replication, and merge
replication.
You must specify all parameters when executing sp_MSchange_snapshot_agent_properties. Execute
sp_helppublication_snapshot to return the current properties of the Snapshot Agent job.
When the Publisher runs on an instance of SQL Server 2005 or later version, you should use
sp_changepublication_snapshot to change properties of a Snapshot Agent job.

Permissions
Only members of the sysadmin fixed server role at the Distributor can execute
sp_MSchange_snapshot_agent_properties.

See Also
sp_addpublication_snapshot (Transact-SQL)
sp_posttracertoken (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This procedure posts a tracer token into the transaction log at the Publisher and begins the process of tracking
latency statistics. Information is recorded when the tracer token is written to the transaction log, when it is picked
up by the Log Reader Agent, and when it is applied by the Distribution Agent. This stored procedure is executed at
the Publisher on the publication database. For more information, see Measure Latency and Validate Connections
for Transactional Replication.
Transact-SQL Syntax Conventions

Syntax
sp_posttracertoken [ @publication = ] 'publication'
[ , [ @tracer_token_id = ] tracer_token_id OUTPUT
[ , [ @publisher = ] 'publisher'

Arguments
[ @publication= ] 'publication'
Is the name of the publication for which latency is being measured. publication is sysname, with no default.
[ @tracer_token_id= ] tracer_token_idOUTPUT
Is the ID of the tracer token inserted. tracer_token_id is int with a default of NULL, and it is an OUTPUT parameter.
This value can be used to execute sp_helptracertokenhistory (Transact-SQL) or sp_deletetracertokenhistory
(Transact-SQL) without first executing sp_helptracertokens (Transact-SQL).
[ @publisher= ] 'publisher'
Specifies a non- Microsoft SQL Server Publisher. publisher is sysname, with a default of NULL and should not be
specified for a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_posttracertoken is used in transactional replication.

Example
DECLARE @publication AS sysname;
DECLARE @tokenID AS int;
SET @publication = N'AdvWorksProductTran';

USE [AdventureWorks2012]

-- Insert a new tracer token in the publication database.


EXEC sys.sp_posttracertoken
@publication = @publication,
@tracer_token_id = @tokenID OUTPUT;
SELECT 'The ID of the new tracer token is ''' +
CONVERT(varchar,@tokenID) + '''.'
GO

-- Wait 10 seconds for the token to make it to the Subscriber.


WAITFOR DELAY '00:00:10';
GO

-- Get latency information for the last inserted token.


DECLARE @publication AS sysname;
DECLARE @tokenID AS int;
SET @publication = N'AdvWorksProductTran';

CREATE TABLE #tokens (tracer_id int, publisher_commit datetime)

-- Return tracer token information to a temp table.


INSERT #tokens (tracer_id, publisher_commit)
EXEC sys.sp_helptracertokens @publication = @publication;
SET @tokenID = (SELECT TOP 1 tracer_id FROM #tokens
ORDER BY publisher_commit DESC)
DROP TABLE #tokens

-- Get history for the tracer token.


EXEC sys.sp_helptracertokenhistory
@publication = @publication,
@tracer_id = @tokenID;
GO

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_posttracertoken.

See Also
Measure Latency and Validate Connections for Transactional Replication
sp_publication_validation (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Initiates an article validation request for each article in the specified publication. This stored procedure is executed
at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_publication_validation [ @publication = ] 'publication'
[ , [ @rowcount_only = ] type_of_check_requested ]
[ , [ @full_or_fast = ] full_or_fast ]
[ , [ @shutdown_agent = ] shutdown_agent ]
[ , [ @publisher = ] 'publisher' ]

Arguments
[@publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@rowcount_only=] rowcount_only
Is whether to return only the rowcount for the table. rowcount_only is smallint and can be one of the following
values.

VALUE DESCRIPTION

0 Perform a SQL Server 7.0 compatible checksum.

Note: When an article is horizontally filtered, a rowcount


operation is performed instead of a checksum operation.

1 (default) Perform a rowcount check only.

2 Perform a rowcount and binary checksum.

Note: For SQL Server version 7.0 Subscribers, only a rowcount


validation is performed.

[@full_or_fast=] full_or_fast
Is the method used to calculate the rowcount. full_or_fast is tinyint and can be one of the following values.

VALUE DESCRIPTION

0 Does full count using COUNT(*).


VALUE DESCRIPTION

1 Does fast count from sysindexes.rows. Counting rows in


sys.sysindexes is much faster than counting rows in the actual
table. However, because sys.sysindexes is lazily updated, the
rowcount may not be accurate.

2 (default) Does conditional fast counting by first trying the fast method.
If fast method shows differences, reverts to full method. If
expected_rowcount is NULL and the stored procedure is being
used to get the value, a full COUNT(*) is always used.

[ @shutdown_agent=] shutdown_agent
Is whether the Distribution Agent should shut down immediately upon completion of the validation.
shutdown_agent is bit, with a default of 0. If 0, the replication agent does not shut down. If 1, the replication agent
shuts down after the last article is validated.
[ @publisher = ] 'publisher'
Specifies a non- SQL Server Publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used when requesting validation on a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_publication_validation is used in transactional replication.
sp_publication_validation can be called at any time after the articles associated with the publication have been
activated. The procedure can be run manually (one time) or as part of a regularly scheduled job that validates the
data.
If your application has immediate-updating Subscribers, sp_publication_validation may detect spurious errors.
sp_publication_validation first calculates the rowcount or checksum at the Publisher and then at the Subscriber.
Because the immediate-updating trigger could propagate an update from the Subscriber to the Publisher after the
rowcount or checksum is completed at the Publisher, but before the rowcount or checksum is completed at the
Subscriber, the values could change. To ensure that the values at the Subscriber and Publisher do not change while
validating a publication, stop the Microsoft Distributed Transaction Coordinator (MS DTC) service at the Publisher
during validation.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_publication_validation.

See Also
Validate Data at the Subscriber
sp_article_validation (Transact-SQL)
sp_table_validation (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_publisherproperty (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Displays or changes publisher properties for non- Microsoft SQL Server Publishers. This stored procedure is
executed at the Distributor.
Transact-SQL Syntax Conventions

Syntax
sp_publisherproperty [ @publisher = ] 'publisher'
[ , [ @propertyname = ] 'propertyname' ]
[ , [ @propertyvalue = ] 'propertyvalue' ]

Arguments
[@publisher = ] 'publisher'
Is the name of the heterogeneous Publisher. publisher is sysname, with no default.
[@propertyname = ] 'propertyname'
Is the name of the property being set. propertyname is sysname, and can be one of the following values.

VALUE DESCRIPTION

xactsetbatching If transactions at the Publisher are grouped into


transactionally consistent sets for subsequent processing,
known as Xactsets. A value of enabled means that Xactsets
can be created, which is the default. A value of disabled
means that existing Xactsets are processed by no new
Xactsets are created.

xactsetjob If the Xactset job is enabled for the creation of Xactsets. A


value of enabled means that the Xactset job runs periodically
to create Xactsets at the publisher. A value of disabled means
that the Xactsets are only created by the Log Reader Agent
when it polls the Publisher for changes.

xactsetjobinterval Interval between executions of the Xactset job, in minutes.

When propertyname is omitted all settable properties are returned.


[@propertyvalue = ] 'propertyvalue'
Is the new value for the property setting. propertyvalue is sysname, with a default value of NULL. When
propertyvalue is omitted, the current setting for the property is returned.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

propertyname sysname Returns the following publication


properties that can be set:

xactsetbatching

xactsetjob

xactsetjobinterval

propertyvalue sysname Is the current setting for the property in


the propertyname column.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_publisherproperty is used in transactional replication for non- SQL Server Publishers.
When only publisher is specified, the result set includes the current settings for all properties that can be set.
When propertyname is specified, only the named property appears in the result set.
When all parameters are specified, the property is changed and a result set is not returned.
When changing the xactsetjobinterval property for a running job, you must restart the job for the new interval to
take effect.

Permissions
Only members of the sysadmin fixed server role at the Distributor can execute sp_publisherproperty.

See Also
Configure the Transaction Set Job for an Oracle Publisher (Replication Transact-SQL Programming)
System Stored Procedures (Transact-SQL)
sp_redirect_publisher (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Specifies a redirected publisher for an existing publisher/database pair. If the publisher database belongs to an
Always On Availability Group, the redirected publisher is the availability group listener name associated with the
availability group.
Transact-SQL Syntax Conventions

Syntax
sp_redirect_publisher
[ @original_publisher = ] 'original_publisher',
[ @publisher_db = ] 'database_name'
[ , [ @redirected_publisher = ] 'new_publisher' ]

Arguments
[ @original_publisher = ] 'original_publisher'
The name of the instance of SQL Server that originally published the database. original_publisher is sysname, with
no default.
[ @publisher_db = ] 'publisher_db'
The name of the database being published. publisher_db is sysname, with no default.
[ @redirected_publisher = ] 'redirected_publisher'
The availability group listener name associated with the availability group that will be the new publisher.
redirected_publisher is sysname, with no default. When the availability group listener is configured to non-default
port, specify the port number along with listener name, such as 'Listenername,51433'

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_redirect_publisher is used to allow a replication publisher to be redirected to the current primary of an
Always On availability group by associating the publisher/database pair with an availability group’s listener.
Execute sp_redirect_publisher after the AG listener has been configured for the availability group that contains
the published database.
If the publication database at the original publisher is removed from an availability group at the primary replica,
execute sp_redirect_publisher without specifying a value for the @redirected_publisher parameter to remove the
redirection for the publisher/database pair. For more information about redirecting the publisher when, see
Maintaining an AlwaysOn Publication Database (SQL Server).

Permissions
Caller must either be a member of the sysadmin fixed server role, the db_owner fixed database role for the
distribution database, or a member of a publication access list for a defined publication associated with the
publisher database.

See Also
Replication Stored Procedures (Transact-SQL)
sp_validate_redirected_publisher (Transact-SQL)
sp_get_redirected_publisher (Transact-SQL)
sp_validate_replica_hosts_as_publishers (Transact-SQL)
sp_refreshsubscriptions (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Add subscriptions to new articles in a pull subscription for all the existing Subscribers to the publication. This
stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_refreshsubscriptions [ @publication = ] 'publication'

Arguments
[ @publication = ] 'publication'
Is the publication for which to refresh subscriptions. publication is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None

Remarks
sp_refreshsubscriptions is used in snapshot, transactional, and merge replication.
sp_refreshsubscriptions is called by sp_addarticle for an immediate-updating publication.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_refreshsubscriptions.

See Also
sp_addarticle (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_register_custom_scripting (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Replication allows user-defined custom stored procedures to replace one or more of the default procedures used
in transactional replication. When a schema change is made to a replicated table, these stored procedures are re-
created. sp_register_custom_scripting registers a stored procedure or Transact-SQL script file that is executed
when a schema change occurs to script out the definition for a new user-defined custom stored procedure. This
new user-defined custom stored procedure should reflect the new schema for the table.
sp_register_custom_scripting is executed at the Publisher on the publication database, and the registered script
file or stored procedure is executed at the Subscriber when a schema change occurs.
Transact-SQL Syntax Conventions

Syntax
sp_register_custom_scripting [ @type = ] 'type'
[ @value = ] 'value'
[ , [ @publication = ] 'publication' ]
[ , [ @article = ] 'article' ]

Arguments
[ @type = ] 'type'
Is the type of custom stored procedure or script being registered. type is varchar(16), with no default, and can be
one of the following values.

VALUE DESCRIPTION

insert Registered custom stored procedure is executed when an


INSERT statement is replicated.

update Registered custom stored procedure is executed when an


UPDATE statement is replicated.

delete Registered custom stored procedure is executed when a


DELETE statement is replicated.

custom_script Script is executed at the end of the data definition language


(DDL) trigger.

[ @value= ] 'value'
Name of a stored procedure or name and fully-qualified path to the Transact-SQL script file that is being
registered. value is nvarchar(1024), with no default.
NOTE
Specifying NULL for valueparameter will unregister a previously registered script, which is the same as running
sp_unregister_custom_scripting.

When the value of type is custom_script, the name and full path of a Transact-SQL script file is expected.
Otherwise, value must be the name of a registered stored procedure.
[ @publication= ] 'publication'
Name of the publication for which the custom stored procedure or script is being registered. publication is
sysname, with a default of NULL.
[ @article= ] 'article'
Name of the article for which the custom stored procedure or script is being registered. article is sysname, with a
default of NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_register_custom_scripting is used in snapshot and transactional replication.
This stored procedure should be executed prior to making a schema change to a replicated table. For more
information about using this stored procedure, see Regenerate Custom Transactional Procedures to Reflect
Schema Changes.

Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role, or the db_ddladmin fixed
database role can execute sp_register_custom_scripting.

See Also
sp_unregister_custom_scripting (Transact-SQL)
sp_registercustomresolver (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Registers a business logic handler or a COM-based custom resolver that can be invoked during the merge
replication synchronization process. This stored procedure is executed at the Distributor.
Transact-SQL Syntax Conventions

Syntax
sp_registercustomresolver [ @article_resolver = ] 'article_resolver'
[ , [ @resolver_clsid = ] 'resolver_clsid' ]
[ , [ @is_dotnet_assembly = ] 'is_dotnet_assembly' ]
[ , [ @dotnet_assembly_name = ] 'dotnet_assembly_name' ]
[ , [ @dotnet_class_name = ] 'dotnet_class_name' ]

Arguments
[ @article_resolver = ] 'article_resolver'
Specifies the friendly name for the custom business logic being registered. article_resolver is nvarchar(255), with
no default.
[ @resolver_clsid= ] 'resolver_clsid'
Specifies the CLSID value of the COM object that being registered. Custom business logic resolver_clsid is
nvarchar(50), with a default of NULL. This parameter must be set to a valid CLSID or set to NULL when registering
a business logic handler assembly.
[ @is_dotnet_assembly= ] 'is_dotnet_assembly'
Specifies the type of custom business logic that is being registered. is_dotnet_assembly is nvarchar(50), with a
default of FALSE. true indicates that the custom business logic being registered is a business logic handler
Assembly; false indicates that it is a COM component.
[ @dotnet_assembly_name= ] 'dotnet_assembly_name'
Is the name of the assembly that implements the business logic handler. dotnet_assembly_name is nvarchar(255),
with a default value of NULL. You must specify the full path to the assembly if it is not deployed in the same
directory as the Merge Agent executable, in the same directory as the application that synchronously starts the
Merge Agent, or in the global assembly cache (GAC).
[ @dotnet_class_name= ] 'dotnet_class_name'
Is the name of the class that overrides BusinessLogicModule to implement the business logic handler. The name
should be specified in the form Namespace.Classname. dotnet_class_name is nvarchar(255), with a default
value of NULL.

Return Code Values


0 (success) or 1 (failure)
Remarks
sp_registercustomresolver is used in merge replication.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_registercustomresolver.

See Also
Implement a Business Logic Handler for a Merge Article
Implement a Custom Conflict Resolver for a Merge Article
sp_lookupcustomresolver (Transact-SQL)
sp_unregistercustomresolver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_reinitmergepullsubscription (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Marks a merge pull subscription for reinitialization the next time the Merge Agent runs. This stored procedure is
executed at the Subscriber in the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_reinitmergepullsubscription [ [ @publisher = ] 'publisher' ]
[ , [ @publisher_db = ] 'publisher_db' ]
[ , [ @publication = ] 'publication' ]
[ , [ @upload_first = ] 'upload_first'

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of ALL.
[ @publisher_db = ] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default of ALL.
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with a default of ALL.
[ @upload_first = ] 'upload_first'
Is whether changes at the Subscriber are uploaded before the subscription is reinitialized. upload_first is
nvarchar(5), with a default of FALSE. If true, changes are uploaded before the subscription is reinitialized. If false,
changes are not uploaded.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_reinitmergepullsubscription is used in merge replication.
If you add, drop, or change a parameterized filter, pending changes at the Subscriber cannot be uploaded to the
Publisher during reinitialization. If you want to upload pending changes, synchronize all subscriptions before
changing the filter.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @publicationDB AS sysname;


DECLARE @publication AS sysname;
SET @publicationDB = N'AdventureWorks2012';
SET @publication = N'AdvWorksSalesOrdersMerge';

USE [AdventureWorks2012Replica]

-- Execute at the Subscriber to reinitialize the pull subscription.


-- Pending changes at the Subscrber are lost.
EXEC sp_reinitmergepullsubscription
@publisher = $(PubServer),
@publisher_db = @publicationDB,
@publication = @publication,
@upload_first = N'false';
GO

-- Start the Merge Agent.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @publicationDB AS sysname;


DECLARE @publication AS sysname;
SET @publicationDB = N'AdventureWorks2012';
SET @publication = N'AdvWorksSalesOrdersMerge';

USE [AdventureWorks2012Replica]

-- Execute at the Subscriber to reinitialize the pull subscription,


-- and upload pending changes at the Subscriber.
EXEC sp_reinitmergepullsubscription
@publisher = $(PubServer),
@publisher_db = @publicationDB,
@publication = @publication,
@upload_first = N'true';
GO

-- Start the Merge Agent.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_reinitmergepullsubscription.

See Also
Reinitialize a Subscription
Reinitialize Subscriptions
System Stored Procedures (Transact-SQL)
sp_reinitmergesubscription (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Marks a merge subscription for reinitialization the next time the Merge Agent runs. This stored procedure is
executed at the Publisher in the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_reinitmergesubscription [ [ @publication = ] 'publication'
[ , [ @subscriber = ] 'subscriber'
[ , [ @subscriber_db = ] 'subscriber_db'
[ , [ @upload_first = ] 'upload_first'

Arguments
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with a default of all.
[ @subscriber = ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of all.
[ @subscriber_db = ] 'subscriber_db'
Is the name of the Subscriber database. subscriber_db is sysname, with a default of all.
[ @upload_first = ] 'upload_first'
Is whether changes at the Subscriber are uploaded before the subscription is reinitialized. upload_first is
nvarchar(5), with a default of FALSE. If true, changes are uploaded before the subscription is reinitialized. If false,
changes are not uploaded.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_reinitmergesubscription is used in merge replication.
sp_reinitmergesubscription can be called from the Publisher to reinitialize merge subscriptions. We recommend
re-running the Snapshot Agent as well.
If you add, drop, or change a parameterized filter, pending changes at the Subscriber cannot be uploaded to the
Publisher during reinitialization. If you want to upload pending changes, synchronize all subscriptions before
changing the filter.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @subscriptionDB AS sysname;


DECLARE @publication AS sysname;
SET @subscriptionDB = N'AdventureWorks2012Replica';
SET @publication = N'AdvWorksSalesOrdersMerge';

USE [AdventureWorks2012Replica]

-- Execute at the Publisher to reinitialize the push subscription.


-- Pending changes at the Subscrber are lost.
EXEC sp_reinitmergesubscription
@subscriber = $(SubServer),
@subscriber_db = @subscriptionDB,
@publication = @publication,
@upload_first = N'false';
GO

-- Start the Merge Agent.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @subscriptionDB AS sysname;


DECLARE @publication AS sysname;
SET @subscriptionDB = N'AdventureWorks2012Replica';
SET @publication = N'AdvWorksSalesOrdersMerge';

USE [AdventureWorks2012Replica]

-- Execute at the Publisher to reinitialize the push subscription,


-- and upload pending changes at the Subscriber.
EXEC sp_reinitmergesubscription
@subscriber = $(SubServer),
@subscriber_db = @subscriptionDB,
@publication = @publication,
@upload_first = N'true';
GO

-- Start the Merge Agent.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_reinitmergesubscription.

See Also
Reinitialize Subscriptions
System Stored Procedures (Transact-SQL)
sp_reinitpullsubscription (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Marks a transactional pull or anonymous subscription for reinitialization the next time the Distribution Agent runs.
This stored procedure is executed at the Subscriber on the pull subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_reinitpullsubscription [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'

Arguments
[ @publisher=] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of all, which marks all subscriptions for
reinitialization.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_reinitpullsubscription is used in transactional replication.
sp_reinitpullsubscription is not supported for peer-to-peer transactional replication.
sp_reinitpullsubscription can be called from the Subscriber to reinitialize the subscription, during the next run of
the Distribution Agent.
Subscriptions to publications created with a value of false for @immediate_sync cannot be reinitialized from the
Subscriber.
You can reinitialize a pull subscription by either executing sp_reinitpullsubscription at the Subscriber or
sp_reinitsubscription at the Publisher.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @publicationDB AS sysname;


DECLARE @publication AS sysname;
SET @publicationDB = N'AdventureWorks2012';
SET @publication = N'AdvWorksProductTran';

USE [AdventureWorks2012Replica]

-- Execute at the Subscriber to reinitialize the pull subscription.


EXEC sp_reinitpullsubscription
@publisher = $(PubServer),
@publisher_db = @publicationDB,
@publication = @publication;
GO

-- Start the Distribution Agent.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_reinitpullsubscription.

See Also
Reinitialize a Subscription
Reinitialize Subscriptions
System Stored Procedures (Transact-SQL)
sp_reinitsubscription (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Marks the subscription for reinitialization. This stored procedure is executed at the Publisher for push subscriptions.
Transact-SQL Syntax Conventions

Syntax
sp_reinitsubscription [ [ @publication = ] 'publication' ]
[ , [ @article = ] 'article' ]
, [ @subscriber = ] 'subscriber'
[ , [ @destination_db = ] 'destination_db']
[ , [ @for_schema_change = ] 'for_schema_change']
[ , [ @publisher = ] 'publisher' ]
[ , [ @ignore_distributor_failure = ] ignore_distributor_failure ]
[ , [ @invalidate_snapshot = ] invalidate_snapshot ]

Arguments
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of all.
[ @article=] 'article'
Is the name of the article. article is sysname, with a default of all. For an immediate-updating publication, article
must be all; otherwise, the stored procedure skips the publication and reports an error.
[ @subscriber=] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with no default.
[ @destination_db=] 'destination_db'
Is the name of the destination database. destination_db is sysname, with a default of all.
[ @for_schema_change=] 'for_schema_change'
Indicates whether reinitialization occurs as a result of a schema change at the publication database.
for_schema_change is bit, with a default of 0. If 0, active subscriptions for publications that allow immediate
updating are reactivated as long as the whole publication, and not just some of its articles, are reinitialized. This
means that the reinitialization is being initiated as a result of schema changes. If 1, active subscriptions are not
reactivated until the Snapshot Agent runs.
[ @publisher= ] 'publisher'
Specifies a non- SQL Server publisher. publisher is sysname, with a default of NULL.

NOTE
publisher should not be used for SQL Server Publishers.

[ @ignore_distributor_failure= ] ignore_distributor_failure
Allows reinitialization even if the Distributor does not exist or is offline. ignore_distributor_failure is bit, with a
default of 0. If 0, reinitialization fails if the Distributor does not exist or is offline.
[ @invalidate_snapshot= ] invalidate_snapshot
Invalidates the existing publication snapshot. invalidate_snapshot is bit, with a default of 0. If 1, a new snapshot is
generated for the publication.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_reinitsubscription is used in transactional replication.
sp_reinitsubscription is not supported for peer-to-peer transactional replication.
For subscriptions where the initial snapshot is applied automatically and where the publication does not allow
updatable subscriptions, the Snapshot Agent must be run after this stored procedure is executed so that schema
and bulk copy program files are prepared and the Distribution Agents is then able to resynchronize the
subscriptions.
For subscriptions where the initial snapshot is applied automatically and the publication allows updatable
subscriptions, the Distribution Agent resynchronizes the subscription using the most recent schema and bulk copy
program files previously created by the Snapshot Agent. The Distribution Agent resynchronizes the subscription
immediately after the user executes sp_reinitsubscription, if the Distribution Agent is not busy; otherwise,
synchronization may occur after the message interval (specified by Distribution Agent command-prompt
parameter: MessageInterval).
sp_reinitsubscription has no effect on subscriptions where the initial snapshot is applied manually.
To resynchronize anonymous subscriptions to a publication, pass in all or NULL as subscriber.
Transactional replication supports subscription reinitialization at the article level. The snapshot of the article is
reapplied at the Subscriber during the next synchronization after the article is marked for reinitialization. However,
if there are dependent articles that are also subscribed to by the same Subscriber, reapplying the snapshot on the
article might fail unless dependent articles in the publication are also automatically reinitialized under certain
circumstances:
If the pre-creation command on the article is 'drop', articles for schema-bound views and schema-bound
stored procedures on the base object of that article is marked for reinitialization as well.
If the schema option on the article includes scripting of declared referential integrity on the primary keys,
articles that have base tables with foreign key relationships to base tables of the reinitialized article are
marked for reinitialization as well.

Example
-- This script uses sqlcmd scripting variables. They are in the form
-- $(MyVariable). For information about how to use scripting variables
-- on the command line and in SQL Server Management Studio, see the
-- "Executing Replication Scripts" section in the topic
-- "Programming Replication Using System Stored Procedures".

DECLARE @subscriptionDB AS sysname;


DECLARE @publication AS sysname;
SET @subscriptionDB = N'AdventureWorks2012Replica';
SET @publication = N'AdvWorksProductTran';

USE [AdventureWorks2012Replica]

-- Execute at the Publisher to reinitialize the push subscription.


EXEC sp_reinitsubscription
@subscriber = $(SubServer),
@destination_db = @subscriptionDB,
@publication = @publication;
GO

-- Start the Distribution Agent.

Permissions
Only members of the sysadmin fixed server role, members of the db_owner fixed database role, or the creator of
the subscription can execute sp_reinitsubscription.

See Also
Reinitialize a Subscription
Reinitialize Subscriptions
Replication Stored Procedures (Transact-SQL)
sp_removedbreplication (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
This stored procedure removes all replication objects on the publication database on the Publisher instance of SQL
Server or on the subscription database on the Subscriber instance of SQL Server. Execute in the appropriate
database, or if the execution is in the context of another database on the same instance, specify the database
where the replication objects should be removed. This procedure does not remove objects from other databases,
such as the distribution database.

NOTE
This procedure should be used only if other methods of removing replication objects have failed.

Transact-SQL Syntax Conventions

Syntax
sp_removedbreplication [ [ @dbname = ] 'dbname' ]
[ , [ @type = ] type ]

Arguments
[ @dbname=] 'dbname'
Is the name of the database. dbname is sysname, with a default value of NULL. When NULL, the current database
will be used.
[ @type = ] type
Is the type of replication for which database objects are being removed. type is nvarchar(5) and can be one of the
following values.

tran Removes transactional replication publishing objects.

merge Removes merge replication publishing objects.

both (default) Removes all replication publishing objects.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_removedbreplication is used in all types of replication.
sp_removedbreplication is useful when restoring a replicated database that has no replication objects needing
to be restored.
sp_removedbreplication cannot be used against a database that is marked as read-only.

Example
-- Remove replication objects from the subscription database on MYSUB.
DECLARE @subscriptionDB AS sysname
SET @subscriptionDB = N'AdventureWorks2012Replica'

-- Remove replication objects from a subscription database (if necessary).


USE master
EXEC sp_removedbreplication @subscriptionDB
GO

Permissions
Only members of the sysadmin fixed server role can execute sp_removedbreplication.

Example
-- Remove replication objects from the subscription database on MYSUB.
DECLARE @subscriptionDB AS sysname
SET @subscriptionDB = N'AdventureWorksReplica'

-- Remove replication objects from a subscription database (if necessary).


USE master
EXEC sp_removedbreplication @subscriptionDB
GO

See Also
Disable Publishing and Distribution
System Stored Procedures (Transact-SQL)
sp_removedistpublisherdbreplication (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes publishing metadata belonging to a specific publication at the Distributor. This stored procedure is
executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_removedistpublisherdbreplication [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'

Arguments
[ @publisher= ] 'publisher'
Is the name of the Publisher server. publisher is sysname, with no default.
[ @publisher_db= ] 'publisher_db'
Is the name of the publication database. publisher_db is sysname with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_removedistpublisherdbreplication is used by transactional and snapshot replication.
sp_removedistpublisherdbreplication is used when a published database must be recreated without also
dropping the distribution database. The following metadata is removed:
All publication metadata.
Metadata for all articles belong to the publication.
Metadata for all subscriptions to the publication.
Metadata for all replication agent jobs that belong to the publication.

Permissions
Only members of the sysadmin fixed server role at the Distributor or members of the db_owner fixed database
role in the distribution database can execute sp_removedistpublisherdbreplication.

See Also
System Stored Procedures (Transact-SQL)
sp_repladdcolumn (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Adds a column to an existing table article that has been published. Allows the new column to be added to all
publishers that publish this table, or just add the column to a specific publication that publishes the table. This
stored procedure is executed at the Publisher on the publication database.

IMPORTANT
This stored procedure has been deprecated and is being supported for backward-compatibility. It should only be used with
Microsoft SQL Server 2000 Publishers and SQL Server 2000 republishing Subscribers. This procedure should not be used on
columns with data types that were introduced in SQL Server 2005 or higher.

Transact-SQL Syntax Conventions

Syntax
sp_repladdcolumn [ @source_object = ] 'source_object', [ @column = ] 'column' ]
[ , [ @typetext = ] 'typetext' ]
[ , [ @publication_to_add = ] 'publication_to_add' ]
[ , [ @from_agent = ] from_agent ]
[ , [ @schema_change_script = ] 'schema_change_script' ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]

Arguments
[ @source_object =] 'source_object'
Is the name of the table article that contains the new column to add. source_object is nvarchar(358), with no
default.
[ @column =] 'column'
Is the name of the column in the table to be added for replication. column is sysname, with no default.
[ @typetext =] 'typetext'
Is the definition of the column being added. typetext is nvarchar(3000), with no default. For example, if the column
order_filled is being added, and it is a single character field, not NULL, and has a default value of N, order_filled
would be the column parameter, while the definition of the column, char(1) NOT NULL CONSTRAINT
constraint_name DEFAULT 'N' would be the typetext parameter value.
[ @publication_to_add =] 'publication_to_add'
Is the name of the publication to which the new column is added. publication_to_add is nvarchar(4000), with a
default of ALL. If ALL, then all publications containing this table are affected. If publication_to_add is specified, then
only this publication has the new column added.
[ @from_agent = ] from_agent
If the stored procedure is being executed by a replication agent. from_agent is int, with a default of 0, where a
value of 1 is used when this stored procedure is being executed by a replication agent, and in every other case the
default value of 0should be used.
[ @schema_change_script =] 'schema_change_script'
Specifies the name and path of a SQL Server script used to modify the system generated custom stored
procedures. schema_change_script is nvarchar(4000), with a default of NULL. Replication allows user-defined
custom stored procedures to replace one or more of the default procedures used in transactional replication.
schema_change_script is executed after a schema change is made to a replicated table article using
sp_repladdcolumn, and can be used to do one of the following:
If custom stored procedures are automatically regenerated, schema_change_script can be used to drop
these custom stored procedures and replace them with user-defined custom stored procedures that
supports the new schema.
If custom stored procedures are not automatically regenerated, schema_change_scriptcan be used to
regenerate these stored procedures or to create user-defined custom stored procedures.
[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Enables or disables the ability to have a snapshot invalidated. force_invalidate_snapshot is a bit, with a
default of 1.
1 specifies that changes to the article may cause the snapshot to be invalid, and if that is the case, a value of
1 gives permission for the new snapshot to occur.
0 specifies that changes to the article do not cause the snapshot to be invalid.
[ @force_reinit_subscription = ] force_reinit_subscription
Enables or disables the ability to have the subscription reinitializated. force_reinit_subscription is a bit with a
default of 0.
0 specifies that changes to the article do not cause the subscription to be reinitialized.
1 specifies that changes to the article may cause the subscription to be reinitialized, and if that is the case, a
value of 1 gives permission for the subscription reinitialization to occur.

Return Code Values


0 (success) or 1 (failure)

Permissions
Only members of the sysadmin fixed server role and the db_owner fixed database role can execute
sp_repladdcolumn.

See Also
Deprecated Features in SQL Server Replication
System Stored Procedures (Transact-SQL)
sp_replcmds (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the commands for transactions marked for replication. This stored procedure is executed at the Publisher
on the publication database.

IMPORTANT
The sp_replcmds procedure should be run only to troubleshoot problems with replication.

Transact-SQL Syntax Conventions

Syntax
sp_replcmds [ @maxtrans = ] maxtrans

Arguments
[ @maxtrans=] maxtrans
Is the number of transactions to return information about. maxtrans is int, with a default of 1, which specifies the
next transaction waiting for distribution.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

article id int The ID of the article.

partial_command bit Indicates whether this is a partial


command or not.

command varbinary(1024) The command value.

xactid binary(10) Transaction ID.

xact_seqno varbinary(16) The transaction sequence number.

publication_id int The ID of the publication.

command_id int ID of the command in


MSrepl_commands.

command_type int Type of command.


COLUMN NAME DATA TYPE DESCRIPTION

originator_srvname sysname Server where the transaction originated.

originator_db sysname Database where the transaction


originated.

pkHash int Internal use only.

originator_publication_id int ID of the publication where the


transaction originated.

originator_db_version int Version of the database where the


transaction originated.

originator_lsn varbinary(16) Identifies the log sequence number


(LSN) for the command in the
originating publication.

Remarks
sp_replcmds is used by the log reader process in transactional replication.
Replication treats the first client that runs sp_replcmds within a given database as the log reader.
This procedure can generate commands for owner-qualified tables or not qualify the table name (the default).
Adding qualified table names allows replication of data from tables owned by a specific user in one database to
tables owned by the same user in another database.

NOTE
Because the table name in the source database is qualified by the owner name, the owner of the table in the target
database must be the same owner name.

Clients who attempt to run sp_replcmds within the same database receive error 18752 until the first client
disconnects. After the first client disconnects, another client can run sp_replcmds, and becomes the new log
reader.
A warning message number 18759 is added to both the Microsoft SQL Server error log and the Microsoft
Windows application log if sp_replcmds is unable to replicate a text command because the text pointer was not
retrieved in the same transaction.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_replcmds.

See Also
Error Messages
sp_repldone (Transact-SQL)
sp_replflush (Transact-SQL)
sp_repltrans (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_replcounters (Transact-SQL)
12/8/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns replication statistics about latency, throughput, and transaction count for each published database. This
stored procedure is executed at the Publisher on any database.
Transact-SQL Syntax Conventions

Syntax
sp_replcounters

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

Database sysname Name of the database.

Replicated transactions int Number of transactions in the log


awaiting delivery to the distribution
database.

Replication rate trans/sec float Average number of transactions per


second delivered to the distribution
database.

Replication latency float Average time, in seconds, that


transactions were in the log before
being distributed.

Replbeginlsn binary(10) Log sequence number (LSN) of the


current truncation point in the log.

Replnextlsn binary(10) LSN of the next commit record awaiting


delivery to the distribution database.

Remarks
sp_replcounters is used in transactional replication.

Permissions
Requires membership in the db_owner fixed database role or sysadmin fixed server role.

See Also
sp_replcmds (Transact-SQL)
sp_repldone (Transact-SQL)
sp_replflush (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_repldone (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Updates the record that identifies the last distributed transaction of the server. This stored procedure is executed
at the Publisher on the publication database.
Cau t i on

If you execute sp_repldone manually, you can invalidate the order and consistency of delivered transactions.
sp_repldone should only be used for troubleshooting replication as directed by an experienced replication
support professional.
Transact-SQL Syntax Conventions

Syntax
sp_repldone [ @xactid= ] xactid
, [ @xact_seqno= ] xact_seqno
[ , [ @numtrans= ] numtrans ]
[ , [ @time= ] time
[ , [ @reset= ] reset ]

Arguments
[ @xactid=] xactid
Is the log sequence number (LSN) of the first record for the last distributed transaction of the server. xactid is
binary(10), with no default.
[ @xact_seqno=] xact_seqno
Is the LSN of the last record for the last distributed transaction of the server. xact_seqno is binary(10), with no
default.
[ @numtrans=] numtrans
Is the number of transactions distributed. numtrans is int, with no default.
[ @time=] time
Is the number of milliseconds, if provided, needed to distribute the last batch of transactions. time is int, with no
default.
[ @reset=] reset
Is the reset status. reset is int, with no default. If 1, all replicated transactions in the log are marked as distributed. If
0, the transaction log is reset to the first replicated transaction and no replicated transactions are marked as
distributed. reset is valid only when both xactid and xact_seqno are NULL.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_repldone is used in transactional replication.
sp_repldone is used by the log reader process to track which transactions have been distributed.
With sp_repldone, you can manually tell the server that a transaction has been replicated (sent to the Distributor).
It also allows you to change the transaction marked as the next one awaiting replication. You can move forward or
backward in the list of replicated transactions. (All transactions less than or equal to that transaction are marked as
distributed.)
The required parameters xactid and xact_seqno can be obtained by using sp_repltrans or sp_replcmds.

Permissions
Members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_repldone.

Examples
When xactid is NULL, xact_seqno is NULL, and reset is 1, all replicated transactions in the log are marked as
distributed. This is useful when there are replicated transactions in the transaction log that are no longer valid and
you want to truncate the log, for example:

EXEC sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0, @time = 0, @reset = 1

Cau t i on

This procedure can be used in emergency situations to allow truncation of the transaction log when transactions
pending replication are present.

See Also
sp_replcmds (Transact-SQL)
sp_replflush (Transact-SQL)
sp_repltrans (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_repldropcolumn (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Drops a column from an existing table article that has been published. This stored procedure is executed at the
Publisher on the publication database.

IMPORTANT
This stored procedure has been deprecated and is being supported mainly for backward-compatibility. It should only be used
with Microsoft SQL Server 2000 Publishers and SQL Server 2000 republishing Subscribers. This procedure should not be
used on columns with data types that were introduced in SQL Server 2005 or higher.

Transact-SQL Syntax Conventions

Syntax
sp_repldropcolumn [ @source_object = ] 'source_object', [ @column = ] 'column'
[ , [ @from_agent = ] from_agent]
[ , [ @schema_change_script = ] 'schema_change_script' ]
[ , [ @force_invalidate_snapshot = ] force_invalidate_snapshot ]
[ , [ @force_reinit_subscription = ] force_reinit_subscription ]

Arguments
[ @source_object = ] 'source_object'
Is the name of the table article that contains the column to drop. source_object is nvarchar(258), with no default.
[ @column = ] 'column'
Is the name of the column in the table to be dropped. column is sysname, with no default.
[ @from_agent = ] from_agent
If the stored procedure is being executed by a replication agent. from_agent is int, with a default of 0, where a value
of 1 is used when this stored procedure is being executed by a replication agent, and in every other case the default
value of 0 should be used.
[ @schema_change_script = ] 'schema_change_script'
Specifies the name and path of a SQL Server script used to modify the system generated custom stored
procedures. schema_change_script is nvarchar(4000), with a default of NULL. Replication allows user-defined
custom stored procedures to replace one or more of the default procedures used in transactional replication.
schema_change_script is executed after a schema change is made to a replicated table article using
sp_repldropcolumn, and can be used to do one of the following:
If custom stored procedures are automatically regenerated, schema_change_script can be used to drop
these custom stored procedures and replace them with user-defined custom stored procedures that
supports the new schema.
If custom stored procedures are not automatically regenerated, schema_change_scriptcan be used to
regenerate these stored procedures or to create user-defined custom stored procedures.
[ @force_invalidate_snapshot = ] force_invalidate_snapshot
Enables or disables the ability to have a snapshot invalidated. force_invalidate_snapshot is a bit, with a
default of 1.
1 specifies that changes to the article may cause the snapshot to be invalid, and if that is the case, a value of
1 gives permission for the new snapshot to occur.
0 specifies that changes to the article do not cause the snapshot to be invalid.
[ @force_reinit_subscription = ] force_reinit_subscription
Enables or disables the ability to have the subscription reinitializated. force_reinit_subscription is a bit with a
default of 0.
0 specifies that changes to the article do not cause the subscription to be reinitialized.
1 specifies that changes to the article may cause the subscription to be reinitialized, and if that is the case, a
value of 1 gives permission for the subscription reinitialization to occur.

Return Code Values


0 (success) or 1 (failure)

Permissions
Only members of the sysadmin fixed server role at the Publisher or members of the db_owner or db_ddladmin
fixed database roles on the publication database can execute sp_repldropcolumn.

See Also
Deprecated Features in SQL Server Replication
System Stored Procedures (Transact-SQL)
sp_replflush (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Flushes the article cache. This stored procedure is executed at the Publisher on the publication database.

IMPORTANT
You should not have to execute this procedure manually. sp_replflush should only be used for troubleshooting replication
as directed by an experienced replication support professional.

Transact-SQL Syntax Conventions

Syntax
sp_replflush

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replflush is used in transactional replication.
Article definitions are stored in the cache for efficiency. sp_replflush is used by other replication stored
procedures whenever an article definition is modified or dropped.
Only one client connection can have log reader access to a given database. If a client has log reader access to a
database, executing sp_replflush causes the client to release its access. Other clients can then scan the transaction
log using sp_replcmds or sp_replshowcmds.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_replflush.

See Also
sp_replcmds (Transact-SQL)
sp_repldone (Transact-SQL)
sp_repltrans (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_replication_agent_checkup (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Checks each distribution database for replication agents that are running but have not logged history within the
specified heartbeat interval. This stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_replication_agent_checkup [ [ @heartbeat_interval = ] heartbeat_interval ]

Arguments
[ @heartbeat_interval = ] 'heartbeat_interval'
Is the maximum number of minutes that an agent can go without logging a progress message. heartbeat_interval
is int, with a default of 10 minutes.

Return Code Values


sp_replication_agent_checkup raises error 14151 for each agent it detects as suspect. It also logs a failure
history message about the agents.

Remarks
sp_replication_agent_checkup is used in snapshot replication, transactional replication, and merge replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_replication_agent_checkup.

See Also
System Stored Procedures (Transact-SQL)
sp_replicationdboption (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Sets a replication database option for the specified database. This stored procedure is executed at the Publisher or
Subscriber on any database.
Transact-SQL Syntax Conventions

Syntax
sp_replicationdboption [ @dbname= ] 'db_name'
, [ @optname= ] 'optname'
, [ @value= ] 'value'
[ , [ @ignore_distributor= ] ignore_distributor ]
[ , [ @from_scripting = ] from_scripting ]

Arguments
[@dbname=] 'dbname'
Is the database for which the replication database option is being set. db_name is sysname, with no default.
[@optname=] 'optname'
Is the replication database option to enable or disable. optname is sysname, and can be one of these values.

VALUE DESCRIPTION

merge publish Database can be used for merge publications.

publish Database can be used for other types of publications.

subscribe Database is a subscription database.

sync with backup Database is enabled for coordinated backup. For more
information, see Enable Coordinated Backups for
Transactional Replication (Replication Transact-SQL
Programming).

[ @value=] 'value'
Is whether to enable or disable the given replication database option. value is sysname, and can be true or false.
When this value is false and optname is merge publish, subscriptions to the merge published database are also
dropped.
[ @ignore_distributor=] ignore_distributor
Indicates whether this stored procedure is executed without connecting to the Distributor. ignore_distributor is bit,
with a default of 0, meaning the Distributor should be connected to and updated with the new status of the
publishing database. The value 1 should be specified only if the Distributor is inaccessible and
sp_replicationdboption is being used to disable publishing.
[ @from_scripting=] from_scripting
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replicationdboption is used in snapshot replication, transactional replication, and merge replication.
This procedure creates or drops specific replication system tables, security accounts, and so on, depending on the
options given. Sets the corresponding category bit in the master.sysdatabases system table and creates the
necessary system tables.
To disable publishing, the publication database must be online. If a database snapshot exists for the publication
database, it must be dropped before disabling publishing. A database snapshot is a read-only offline copy of a
database, and is not related to a replication snapshot. For more information, see Database Snapshots (SQL Server).

Permissions
Only members of the sysadmin fixed server role can execute sp_replicationdboption.

See Also
Configure Publishing and Distribution
Create a Publication
Delete a Publication
Disable Publishing and Distribution
sys.sysdatabases (Transact-SQL)
Replication Stored Procedures (Transact-SQL)
sp_replmonitorchangepublicationthreshold (Transact-
SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Changes the monitoring threshold metric for a publication. This stored procedure, which is used to monitor
replication, is executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_replmonitorchangepublicationthreshold [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
[ , [ @publication_type = ] publication_type ]
[ , [ @metric_id = ] metric_id ]
[ , [ @thresholdmetricname = ] 'thresholdmetricname'
[ , [ @value = ] value ]
[ , [ @shouldalert = ] shouldalert ]
[ , [ @mode = ] mode ]

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db = ] 'publisher_db'
Is the name of the published database. publisher_db is sysname, with no default.
[ @publication = ] 'publication'
Is the name of the publication for which the monitoring threshold attributes are being changed. publication is
sysname, with no default.
[ @publication_type = ] publication_type
If the type of publication. publication_type is int, and can be one of these values.

VALUE DESCRIPTION

0 Transactional publication.

1 Snapshot publication.

2 Merge publication.

NULL (default) Replication attempts to determine the publication type.

[ @metric_id = ] metric_id
Is the ID of the publication threshold metric being changed. metric_id is int, with a default value of NULL and can
be one of these values.

VALUE METRIC NAME

1 expiration - monitors for imminent expiration of


subscriptions to transactional publications.

2 latency - monitors for the performance of subscriptions to


transactional publications.

4 mergeexpiration - monitors for imminent expiration of


subscriptions to merge publications.

5 mergeslowrunduration - monitors the duration of merge


synchronizations over low-bandwidth (dial-up) connections.

6 mergefastrunduration - monitors the duration of merge


synchronizations over high-bandwidth local area network
(LAN) connections.

7 mergefastrunspeed - monitors the synchronization rate of


merge synchronizations over high-bandwidth (LAN)
connections.

8 mergeslowrunspeed - monitors the synchronization rate of


merge synchronizations over low-bandwidth (dial-up)
connections.

You must specify either metric_id or thresholdmetricname. If thresholdmetricname is specified, then metric_id
should be NULL.
[ @thresholdmetricname = ] 'thresholdmetricname'
Is the name of the publication threshold metric being changed. thresholdmetricname is sysname, with a default
value of NULL. You must specify either thresholdmetricname or metric_id. If metric_id is specified, then
thresholdmetricname should be NULL.
[ @value = ] value
Is the new value of the publication threshold metric. value is int, with a default value of NULL. If null, then the
metric value is not updated.
[ @shouldalert = ] shouldalert
Is if an alert is generated when a publication threshold metric is reached. shouldalert is bit, with a default of NULL.
A value of 1 means that an alert is generated, and a value of 0 means that an alert is not generated.
[ @mode = ] mode
Is if the publication threshold metric is enabled. mode is tinyint, with a default of 1. A value of 1 means that
monitoring of this metric is enabled, and a value of 2 means that monitoring of this metric is disabled.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replmonitorchangepublicationthreshold is used with all types of replication.
Permissions
Only members of the db_owner or replmonitor fixed database role in the distribution database can execute
sp_replmonitorchangepublicationthreshold.

See Also
Programmatically Monitor Replication
sp_replmonitorhelpmergesession (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns information on past sessions for a given replication Merge Agent, with one row returned for each session
that matches the filtering criterion. This stored procedure, which is used to monitor merge replication, is executed
at the Distributor on the distribution database or at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_replmonitorhelpmergesession [ [ @agent_name = ] 'agent_name' ]
[ , [ @hours = ] hours ]
[ , [ @session_type = ] session_type ]
[ , [ @publisher = ] 'publisher' ]
[ , [ @publisher_db = ] 'publisher_db' ]
[ , [ @publication = ] 'publication' ]

Arguments
[ @agent_name = ] 'agent_name'
Is the name of the agent. agent_name is nvarchar(100) with no default.
[ @hours = ] hours
Is the range of time, in hours, for which historical agent session information is returned. hours is int, which can be
one of the following ranges.

VALUE DESCRIPTION

<0 Returns information on past agent runs, up to a maximum of


100 runs.

0 (default) Returns information on all past agent runs.

>0 Returns information on agent runs that occurred in the last


hours number of hours.

[ @session_type = ] session_type
Filters the result set based on the session end result. session_type is int, and can be one of these values.

VALUE DESCRIPTION

1 (default) Agent sessions with a retry or succeed result.

0 Agent sessions with a failure result.

[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of NULL. This parameter is used when executing
sp_replmonitorhelpmergesession at the Subscriber.
[ @publisher_db = ] 'publisher_db'
Is the name of the publication database. publisher_db is sysname, with a default of NULL. This parameter is used
when executing sp_replmonitorhelpmergesession at the Subscriber.
[ @publication= ] 'publication'
Is the name of the publication. publication is sysname, with a default of NULL. This parameter is used when
executing sp_replmonitorhelpmergesession at the Subscriber.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

Session_id int ID of the agent job session.

Status int Agent run status:

1 = Start

2 = Succeed

3 = In progress

4 = Idle

5 = Retry

6 = Fail

StartTime datetime Time agent job session began.

EndTime datetime Time agent job session was completed.

Duration int Cumulative duration, in seconds, of this


job session.

UploadedCommands int Number of commands uploaded during


the agent session.

DownloadedCommands int Number of commands downloaded


during the agent session.

ErrorMessages int Number of error messages that were


generated during the agent session.

ErrorID int ID of the error that occurred

PercentageDone decimal Estimated percent of the total changes


that have already been delivered in an
active session.

TimeRemaining int Estimated number of seconds left in an


active session.
COLUMN NAME DATA TYPE DESCRIPTION

CurrentPhase int Is the current phase of an active


session, which can be one of the
following.

1 = Upload

2 = Download

LastMessage nvarchar(500) Is the last message logged by Merge


Agent during the session.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replmonitorhelpmergesession is used to monitor merge replication.
When executed on the Subscriber, sp_replmonitorhelpmergesession only returns information on the last five
Merge Agent sessions.

Permissions
Only members of the db_owner or replmonitor fixed database role on the distribution database at the Distributor
or on the subscription database at the Subscriber can execute sp_replmonitorhelpmergesession.

See Also
Programmatically Monitor Replication
sp_replmonitorhelpmergesessiondetail (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns detailed, article-level information about a specific replication Merge Agent session, which is used to
monitor merge replication. The result set includes a detail row for each article that was synchronized during the
session. It also includes a row that represents the session initialization and rows that summarize both the upload
and download phases of the session. This stored procedure is executed at the Distributor on the distribution
database, or at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_replmonitorhelpmergesessiondetail [ @session_id = ] session_id

Arguments
[ @session_id = ] session_id
Specifies an agent session. session_id is int with no default.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

PhaseID int Is the phase of the synchronization


session, which can be one of the
following:

0 = Initialization or summary row

1 = Upload

2 = Download

ArticleName sysname Is the name of the article being


synchronized. ArticleName also
contains summary information for rows
in the result set that do not represent
article details.

PercentComplete decimal Indicates the percent of the total


changes applied in a given article detail
row for currently running or failed
sessions.

RelativeCost decimal Indicates the time spent synchronizing


the article as a percentage of the total
synchronization time for the session.
COLUMN NAME DATA TYPE DESCRIPTION

Duration int Length of the agent session.

Inserts int Number of inserts in a session.

Updates int Number of updates in a session.

Deletes int Number of deletes in a session.

Conflicts int Number of conflicts that occurred in a


session.

ErrorID int ID of a session error.

SeqNo int Order of sessions in the result set.

RowType int Indicates what type of information each


row in the result set represents.

0 = initialization

1 = upload summary

2 = article upload detail

3 = download summary

4 = article download detail

SchemaChanges int Number of schema changes in a


session.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replmonitorhelpmergesessiondetail is used to monitor merge replication.
When executed on the Subscriber, sp_replmonitorhelpmergesessiondetail only returns detailed information
about the last 5 Merge Agent sessions.

Permissions
Only members of the db_owner or replmonitor fixed database role on the distribution database at the Distributor
or on the subscription database at the Subscriber can execute sp_replmonitorhelpmergesessiondetail.

See Also
Programmatically Monitor Replication
sp_replmonitorhelppublication (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns current status information for one or more publications at a Publisher. This stored procedure, which is
used to monitor replication, is executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_replmonitorhelppublication [ @publisher = ] 'publisher'
[ , [ @publisher_db = ] 'publisher_db'
[ , [ @publication = ] 'publication'
[ , [ @publication_type = ] publication_type ]
[ , [ @refreshpolicy = ] refreshpolicy ]

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher the status of which is being monitored. publisher is sysname, with a default value of
NULL. If null, information will be returned for all Publishers that use the Distributor.
[ @publisher_db = ] 'publisher_db'
Is the name of the published database. publisher_db is sysname, with a default value of NULL. If NULL, then
information is returned for all published databases at the Publisher.
[ @publication = ] 'publication'
Is the name of the publication being monitored. publication is sysname, with a default value of NULL.
[ @publication_type = ] publication_type
If the type of publication. publication_type is int, and can be one of these values.

VALUE DESCRIPTION

0 Transactional publication.

1 Snapshot publication.

2 Merge publication.

NULL (default) Replication attempts to determine the publication type.

[ @refreshpolicy= ] refreshpolicy
Internal use only.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

publisher_db sysname Is the name of the Publisher.

publication sysname Is the name of a publication.

publication_type int Is the type of publication, which can be


one of these values.

0 = Transactional publication

1 = Snapshot publication

2 = Merge publication

status int Maximum status of all replication


agents associated with the publication,
which can be one of these values.

1 = Started

2 = Succeeded

3 = In progress

4 = Idle

5 = Retrying

6 = Failed
COLUMN NAME DATA TYPE DESCRIPTION

warning int Maximum threshold warning generated


by a subscription belonging to the
publication, which can be the logical OR
result of one or more of these values.

1 = expiration – a subscription to a
transactional publication has not been
synchronized within the retention
period threshold.

2 = latency - the time taken to replicate


data from a transactional Publisher to
the Subscriber exceeds the threshold, in
seconds.

4 = mergeexpiration - a subscription to
a merge publication has not been
synchronized within the retention
period threshold.

8 = mergefastrunduration - the time


taken to complete synchronization of a
merge subscription exceeds the
threshold, in seconds, over a fast
network connection.

16 = mergeslowrunduration - the time


taken to complete synchronization of a
merge subscription exceeds the
threshold, in seconds, over a slow or
dial-up network connection.

32 = mergefastrunspeed – the delivery


rate for rows during synchronization of
a merge subscription has failed to
maintain the threshold rate, in rows per
second, over a fast network connection.

64 = mergeslowrunspeed – the delivery


rate for rows during synchronization of
a merge subscription has failed to
maintain the threshold rate, in rows per
second, over a slow or dial-up network
connection.

worst_latency int The highest latency, in seconds, for data


changes propagated by the Log Reader
or Distribution Agents for a
transactional publication.

best_latency int The lowest latency, in seconds, for data


changes propagated by the Log Reader
or Distribution Agents for a
transactional publication.

average_latency int The average latency, in seconds, for


data changes propagated by the Log
Reader or Distribution Agents for a
transactional publication.
COLUMN NAME DATA TYPE DESCRIPTION

last_distsync datetime Is the last datetime that the Distribution


Agent ran.

retention int Is the retention period for the


publication.

latencythreshold int Is the latency threshold set for the


transactional publication.

expirationthreshold int Is the expiration threshold set for the


publication if it is a merge publication.

agentnotrunningthreshold int Is the threshold set for the longest time


for an agent not to have run.

subscriptioncount int Is the number of subscriptions to a


publication.

runningdistagentcount int Is the number of distribution agents


running for the publication

snapshot_agentname sysname Name of the Snapshot Agent job for the


publication.

logreader_agentname sysname Name of the Log Reader Agent job for


the transactional publication.

qreader_agentname sysname Name of the Queue Reader Agent job


for a transactional publication that
supports queued updating.

worst_runspeedPerf int Is the longest synchronization time for


the merge publication.

best_runspeedPerf int Is the shortest synchronization time for


the merge publication.

average_runspeedPerf int Is the average synchronization time for


the merge publication.

retention_period_unit int Is the unit used to express retention.

publisher sysname The name of the instance of SQL Server


publishing the publication.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replmonitorhelppublication is used with all types of replication.
Permissions
Only members of the db_owner or replmonitor fixed database role on the distribution database can execute
sp_replmonitorhelppublication.

See Also
Programmatically Monitor Replication
sp_replmonitorhelppublicationthresholds (Transact-
SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns the threshold metrics set for a monitored publication. This stored procedure, which is used to monitor
replication, is executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_replmonitorhelppublicationthresholds [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
[ , [ @publication_type = ] publication_type ]
[ , [ @thresholdmetricname = ] 'thresholdmetricname'

Arguments
[ @publisher= ] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db= ] 'publisher_db'
Is the name of the published database. publisher_db is sysname, with no default.
[ @publication= ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @publication_type= ] publication_type
If the type of publication. publication_type is int, and can be one of these values.

VALUE DESCRIPTION

0 Transactional publication.

1 Snapshot publication.

2 Merge publication.

NULL (default) Replication tries to determine the publication type.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION
COLUMN NAME DATA TYPE DESCRIPTION

metric_id int ID of the replication performance


metric, which can be one of the
following.

1expiration - monitors for imminent


expiration of subscriptions to
transactional publications.

2latency - monitors for the


performance of subscriptions to
transactional publications.

4mergeexpiration - monitors for


imminent expiration of subscriptions to
merge publications.

5mergeslowrunduration - monitors
the duration of merge synchronizations
over low-bandwidth (dial-up)
connections.

6mergefastrunduration - monitors
the duration of merge synchronizations
over high-bandwidth (LAN)
connections.

7mergefastrunspeed - monitors the


synchronization rate of merge
synchronizations over high-bandwidth
(LAN) connections.

8mergeslowrunspeed - monitors the


synchronization rate of merge
synchronizations over low-bandwidth
(dial-up) connections.

title sysname Name of the replication performance


metric.

value int The threshold value of the performance


metric.

shouldalert bit Is if an alert should be generated when


the metric exceeds the defined
threshold for this publication; a value of
1 indicates that an alert should be
raised.

isenabled bit Is if monitoring is enabled for this


replication performance metric for this
publication; a value of 1 indicates that
monitoring is enabled.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replmonitorhelppublicationthresholds is used with all types of replication.

Permissions
Only members of the db_owner or replmonitor fixed database role on the distribution database can execute
sp_replmonitorhelppublicationthresholds.

See Also
Programmatically Monitor Replication
sp_replmonitorhelppublisher (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns current status information for one or more Publishers associated with a Distributor. This stored procedure,
which is used to monitor replication, is executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_replmonitorhelppublisher [ [ @publisher = ] 'publisher' ]
[ , [ @refreshpolicy = ] refreshpolicy ]

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher the status of which is being monitored. publisher is sysname, with a default value of
NULL. If NULL, information will be returned for all Publishers that use the Distributor.
[ @refreshpolicy= ] refreshpolicy
Internal use only.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

publisher sysname Is the name of a Publisher.

distribution_db sysname Is the name of the distribution database


used by a given Publisher.

status int Maximum status of all replication


agents associated with publications at
this Publisher, which can be one of
these values.

1 = Started

2 = Succeeded

3 = In progress

4 = Idle

5 = Retrying

6 = Failed
COLUMN NAME DATA TYPE DESCRIPTION

warning int Maximum threshold warning generated


by a subscription belonging to a
publication at this Publisher, which can
be the logical OR result of one or more
of these values.

1 = expiration – a subscription to a
transactional publication has not been
synchronized within the retention
period threshold.

2 = latency - the time taken to replicate


data from a transactional Publisher to
the Subscriber exceeds the threshold, in
seconds.

4 = mergeexpiration - a subscription to
a merge publication has not been
synchronized within the retention
period threshold.

8 = mergefastrunduration - the time


taken to complete synchronization of a
merge subscription exceeds the
threshold, in seconds, over a fast
network connection.

16 = mergeslowrunduration - the time


taken to complete synchronization of a
merge subscription exceeds the
threshold, in seconds, over a slow or
dial-up network connection.

32 = mergefastrunspeed – the delivery


rate for rows during synchronization of
a merge subscription has failed to
maintain the threshold rate, in rows per
second, over a fast network connection.

64 = mergeslowrunspeed – the delivery


rate for rows during synchronization of
a merge subscription has failed to
maintain the threshold rate, in rows per
second, over a slow or dial-up network
connection.

publicationcount int Is the number of publications belonging


to the Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replmonitorhelppublisher is used with all types of replication.

Permissions
Only members of the sysadmin fixed server role at the Distributor or members of the db_owner or replmonitor
fixed database roles in the distribution database can execute sp_replmonitorhelppublisher.

See Also
Programmatically Monitor Replication
sp_replmonitorhelpsubscription (Transact-SQL)
11/21/2017 • 6 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns current status information for subscriptions belonging to one or more publications at the Publisher and
returns one row for each returned subscription. This stored procedure, which is used to monitor replication, is
executed at the Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_replmonitorhelpsubscription [ @publisher = ] 'publisher'
[ , [ @publisher_db = ] 'publisher_db' ]
[ , [ @publication = ] 'publication' ]
[ , [ @publication_type = ] publication_type ]
[ , [ @mode = ] mode ]
[ , [ @topnum = ] topnum ]
[ , [ @exclude_anonymous = ] exclude_anonymous ]
[ , [ @refreshpolicy = ] refreshpolicy ]

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher the status of which is being monitored. publisher is sysname, with a default value of
NULL. If null, information is returned for all Publishers that use the Distributor.
[ @publisher_db = ] 'publisher_db'
Is the name of the published database. publisher_db is sysname, with a default value of NULL. If NULL, then
information is returned for all published databases at the Publisher.
[ @publication = ] 'publication'
Is the name of the publication being monitored. publication is sysname, with a default value of NULL.
[ @publication_type = ] publication_type
If the type of publication. publication_type is int, and can be one of these values.

VALUE DESCRIPTION

0 Transactional publication.

1 Snapshot publication.

2 Merge publication.

NULL (default) Replication tries to determine the publication type.

[ @mode = ] mode
Is the filtering mode to use when returning subscription monitoring information. mode is int, and can be one of
these values.

VALUE DESCRIPTION

0 (default) Returns all subscriptions.

1 Returns only subscriptions with errors.

2 Returns only subscriptions that have generated threshold


metric warnings.

3 Returns only subscriptions that either have errors or have


generated threshold metric warnings.

4 Returns the top 25 worst performing subscriptions.

5 Returns the top 50 worst performing subscriptions.

6 Returns only subscriptions that are currently being


synchronized.

7 Returns only subscriptions that are not currently being


synchronized.

[ @topnum = ] topnum
Restricts the result set to only the specified number of subscriptions at the top of the returned data. topnum is int,
with no default.
[ @exclude_anonymous = ] exclude_anonymous
Is if anonymous pull subscriptions are excluded from the result set. exclude_anonymous is bit, with a default of 0; a
value of 1 means that anonymous subscriptions are excluded and a value of 0 means that they are included.
[ @refreshpolicy= ] refreshpolicy
Internal use only.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

status int Examines the status of all the replication


agents associated with the publication,
and returns the highest status found in
the following order:

6 = Failed

5 = Retrying

2 = Stopped

4 = Idle

3 = In progress

1 = Started
COLUMN NAME DATA TYPE DESCRIPTION

warning int Maximum threshold warning generated


by a subscription belonging to the
publication, which can be the logical OR
result of one or more of these values.

1 = expiration – a subscription to a
transactional publication has not been
synchronized within the retention
period threshold.

2 = latency - the time taken to replicate


data from a transactional Publisher to
the Subscriber exceeds the threshold, in
seconds.

4 = mergeexpiration - a subscription to
a merge publication has not been
synchronized within the retention
period threshold.

8 = mergefastrunduration - the time


taken to complete synchronization of a
merge subscription exceeds the
threshold, in seconds, over a fast
network connection.

16 = mergeslowrunduration - the time


taken to complete synchronization of a
merge subscription exceeds the
threshold, in seconds, over a slow or
dial-up network connection.

32 = mergefastrunspeed – the delivery


rate for rows during synchronization of
a merge subscription has failed to
maintain the threshold rate, in rows per
second, over a fast network connection.

64 = mergeslowrunspeed – the delivery


rate for rows during synchronization of
a merge subscription has failed to
maintain the threshold rate, in rows per
second, over a slow or dial-up network
connection.

subscriber sysname Is the name of the Subscriber.

subscriber_db sysname Is the name of the database used for


the subscription.

publisher_db sysname Is the name of the publication database.

publication sysname Is the name of a publication.


COLUMN NAME DATA TYPE DESCRIPTION

publication_type int Is the type of publication, which can be


one of these values:

0 = Transactional publication

1 = Snapshot publication

2 = Merge publication

subtype int Is the subscription type, which can be


one of the following values:

0 = Push

1 = Pull

2 = Anonymous

latency int The highest latency, in seconds, for data


changes propagated by the Log Reader
or Distribution Agents for a
transactional publication.

latencythreshold int Is the maximum latency for the


transactional publication above which a
warning is raised.

agentnotrunning int Is the length of time, in hours, during


which the agent has not run.

agentnotrunningthreshold int Is the length of time, in hours, that the


agent has not run before a warning is
raised.

timetoexpiration int Is the length of time, in hours, before


the subscription expires if not
synchronized.

expirationthreshold int Is the time, in hours, before the


subscription expires that a warning is
raised.

last_distsync datetime Is the datetime that the Distribution


Agent last ran.

distribution_agentname sysname Is the name of the Distribution Agent


job for the subscription to a
transactional publication.

mergeagentname sysname Is the name of the Merge Agent job for


the subscription to a merge publication.

mergesubscriptionfriendlyname sysname Is the friendly name given to the


subscription.
COLUMN NAME DATA TYPE DESCRIPTION

mergeagentlocation sysname Is the name of the server on which the


Merge Agent runs.

mergeconnectiontype int Connection used when synchronizing a


subscription to a merge publication,
which can be one of the following
values:

1 = local area network (LAN)

2 = dial-up network connection

3 = Web synchronization.

mergePerformance int Performance of the last synchronization


compared to all synchronizations for the
subscription, which is based on the
delivery rate of the last synchronization
divided by the average of all previous
delivery rates.

mergerunspeed float Is the delivery rate of the last


synchronization for the subscription.

mergerunduration int Is the length of time to complete the


last synchronization of the subscription.
COLUMN NAME DATA TYPE DESCRIPTION

monitorranking int Is the ranking value used to order the


subscriptions in the result set, and can
be one of these values:

For a transactional publication:

60 = Error

56 = Warning: performance critical

52 = Warning: expiring soon or expired

50 = Warning: subscription uninitialized

40 = Retrying failed command

30 = Not running (success)

20 = Running (starting, running, or idle)

For a merge publication:

60 = Error

56 = Warning: performance critical

54 = Warning: long-running merge

52 = Warning: expiring soon

50 = Warning: subscription uninitialized

40 = Retrying failed command

30 = Running (starting, running, or idle)

20 = Not running (success)

distributionagentjobid binary(16) ID of the Distribution Agent job for


subscriptions to a transactional
publication.

mergeagentjobid binary(16) ID of the Merge Agent job for


subscriptions to a merge publication.

distributionagentid int ID of the Distribution Agent job for the


subscription.

distributionagentprofileid int ID of the agent profile used by the


Distribution Agent.

mergeagentid int ID of the Merge Agent job for the


subscription.

mergeagentprofileid int ID of the agent profile used by the


Merge Agent.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replmonitorhelpsubscription is used with all types of replication.
sp_replmonitorhelpsubscription orders the result set based on the severity of the status of the subscription,
which is determined by the value of monitorranking. For example, rows for all subscriptions in an error state are
ordered above rows for subscriptions in a warning state.

Permissions
Only members of the db_owner or replmonitor fixed database role on the distribution database can execute
sp_replmonitorhelpsubscription.

See Also
Programmatically Monitor Replication
sp_replmonitorsubscriptionpendingcmds (Transact-
SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns information on the number of pending commands for a subscription to a transactional publication and a
rough estimate of how much time it takes to process them. This stored procedure returns one row for each
returned subscription. This stored procedure, which is used to monitor replication, is executed at the Distributor on
the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_replmonitorsubscriptionpendingcmds [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
, [ @subscriber = ] 'subscriber'
, [ @subscriber_db = ] 'subscriber_db'
, [ @subscription_type = ] subscription_type

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db = ] 'publisher_db'
Is the name of the published database. publisher_db is sysname, with no default.
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @subscriber = ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with no default.
[ @subscriber_db = ] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with no default.
[ @subscription_type = ] subscription_type
If the type of subscription. publication_type is int, with no default and can be one of these values.

VALUE DESCRIPTION

0 Push subscription

1 Pull subscription

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

pendingcmdcount int The number of commands that are


pending for the subscription.

estimatedprocesstime int Estimate of the number of seconds


required to deliver all of the pending
commands to the Subscriber.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replmonitorsubscriptionpendingcmds is used with transactional replication.

Permissions
Only members of the sysadmin fixed server role at the Distributor or members of the db_owner fixed database
role in the distribution database can execute sp_replmonitorsubscriptionpendingcmds. Members of the
publication access list for a publication that uses the distribution database can execute
sp_replmonitorsubscriptionpendingcmds to return pending commands for that publication.

See Also
Programmatically Monitor Replication
sp_replqueuemonitor (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Lists the queue messages from a Microsoft SQL Server queue or Microsoft Message Queuing for queued updating
subscriptions to a specified publication. If SQL Server queues are used, this stored procedure is executed at the
Subscriber on the subscription database. If Message Queuing is used, this stored procedure is executed at the
Distributor on the distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_replqueuemonitor [ @publisher = ] 'publisher'
[ , [ @publisherdb = ] 'publisher_db' ]
[ , [ @publication = ] 'publication' ]
[ , [ @tranid = ] 'tranid' ]
[ , [ @queuetype = ] 'queuetype' ]

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of NULL. The server must be configured for
publishing. NULL for all Publishers.
[ @publisherdb = ] 'publisher_db' ]
Is the name of the publication database. publisher_db is sysname, with a default of NULL. NULL for all publication
databases.
[ @publication = ] 'publication' ]
Is the name of the publication. publicationis sysname, with a default of NULL. NULL for all publications.
[ @tranid = ] 'tranid' ]
Is the transaction ID. tranidis sysname, with a default of NULL. NULL for all transactions.
[@queuetype= ] 'queuetype' ]
Is the type of queue that stores transactions. queuetype is tinyint with a default of 0, and can be one of these
values.

VALUE DESCRIPTION

0 All types of queues

1 Message Queuing

2 SQL Server queue

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replqueuemonitor is used in snapshot replication or transactional replication with queued updating
subscriptions. The queue messages that do not contain SQL commands or are part of a spanning SQL command
are not displayed.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_replqueuemonitor.

See Also
Updatable Subscriptions for Transactional Replication
System Stored Procedures (Transact-SQL)
sp_replrestart (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Used by transactional replication during backup and restore so that the replicated data at the Distributor is
synchronized with data at the Publisher. This stored procedure is executed at the Publisher on the publication
database.

IMPORTANT
sp_replrestart is an internal replication stored procedure and should only be used when restoring a database published in a
transactional replication topology as directed in the topic Strategies for Backing Up and Restoring Snapshot and
Transactional Replication.

Transact-SQL Syntax Conventions

Syntax
sp_replrestart

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replrestart is used when the highest log sequence number (LSN) value at the Distributor does match the
highest LSN value at the Publisher.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_replrestart.

See Also
Replication Stored Procedures (Transact-SQL)
sp_replsetoriginator (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Used to invoke loopback detection and handling in bidirectional transactional replication. This stored procedure is
executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_replsetoriginator [ @server_name= ] 'server_name'
, [ @database_name= ] 'database_name'

Arguments
[ @server_name=] 'server_name'
Is the name of the server where the transaction is being applied. originating_server is sysname, with no default.
[ @database_name=] 'database_name'
Is the name of the database where the transaction is being applied. originating_db is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_replsetoriginator is executed by the Distribution Agent to record the source of transactions applied by
replication. This information is used to invoke loopback detection for bidirectional transactional subscriptions that
have the loopback property set.

Permissions
Only members of the sysadmin fixed server role at the Publisher, members of the db_owner fixed database role
on the publication database, or users in the publication access list (PAL) can execute sp_replsetoriginator.

See Also
System Stored Procedures (Transact-SQL)
sp_replshowcmds (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns the commands for transactions marked for replication in readable format. sp_replshowcmds can be run
only when client connections (including the current connection) are not reading replicated transactions from the
log. This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_replshowcmds [ @maxtrans = ] maxtrans

Arguments
[ @maxtrans = ] maxtrans
Is the number of transactions about which to return information. maxtrans is int, with a default of 1, which
specifies the maximum number of transactions pending replication for which sp_replshowcmds returns
information.

Result Sets
sp_replshowcmds is a diagnostic procedure that returns information about the publication database from which
it is executed.

COLUMN NAME DATA TYPE DESCRIPTION

xact_seqno binary(10) Sequence number of the command.

originator_id int ID of the command originator, always 0.

publisher_database_id int ID of the Publisher database, always 0.

article_id int ID of the article.

type int Type of command.

command nvarchar(1024) Transact-SQL command.

Remarks
sp_replshowcmds is used in transactional replication.
Using sp_replshowcmds, you can view transactions that currently are not distributed (those transactions
remaining in the transaction log that have not been sent to the Distributor).
Clients that run sp_replshowcmds and sp_replcmds within the same database receive error 18752.
To avoid this error, the first client must disconnect or the role of the client as log reader must be released by
executing sp_replflush. After all clients have disconnected from the log reader, sp_replshowcmds can be run
successfully.

NOTE
sp_replshowcmds should be run only to troubleshoot problems with replication.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_replshowcmds.

See Also
Error Messages
sp_replcmds (Transact-SQL)
sp_repldone (Transact-SQL)
sp_replflush (Transact-SQL)
sp_repltrans (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_repltrans (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Returns a result set of all the transactions in the publication database transaction log that are marked for
replication but have not been marked as distributed. This stored procedure is executed at the Publisher on a
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_repltrans

Result Sets
sp_repltrans returns information about the publication database from which it is executed, allowing you to view
transactions currently not distributed (those transactions remaining in the transaction log that have not been sent
to the Distributor). The result set displays the log sequence numbers of the first and last records for each
transaction. sp_repltrans is similar to sp_replcmds (Transact-SQL) but does not return the commands for the
transactions.

Remarks
sp_repltrans is used in transactional replication.
sp_repltrans is not supported for non- Microsoft SQL Server Publishers.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_repltrans.

See Also
sp_repldone (Transact-SQL)
sp_replflush (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_requestpeerresponse (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
When executed from a node in a peer-to-peer topology, this procedure requests a response from every other
node in the topology. By executing this procedure and reviewing the corresponding responses, you can guarantee
that all previous commands have been delivered to the responding nodes. This stored procedure is executed at
the requesting node on any database.
Transact-SQL Syntax Conventions

Syntax
sp_requestpeerresponse [ @publication = ] 'publication'
[ , [ @description = ] 'description'
[ , [ @request_id = ] request_id OUTPUT ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication in a peer-to-peer topology for which the status is being verified. publication is
sysname, with no default.
[ @description= ] 'description'
User-defined information that can be used to identify individual status requests. description is nvarchar(4000),
with a default of NULL.
[ @request_id = ] request_id
Returns the ID of the new request. request_id is int and is an OUTPUT parameter. This value can be used when
executing sp_helppeerresponses (Transact-SQL) to view all responses to a status request.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_requestpeerresponse is used in peer-to-peer transactional replication.
sp_requestpeerresponse is used to ensure that all commands have been received by all other nodes before
restoring a database published in a peer-to-peer topology. It is also used when replicating data definition
language (DDL) changes made while a node was offline to estimate when these changes arrive at the other nodes.
sp_requestpeerresponse cannot be executed within a user-defined transaction.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_requestpeerresponse.
See Also
sp_deletepeerrequesthistory (Transact-SQL)
sp_helppeerrequests (Transact-SQL)
sp_requestpeertopologyinfo (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Populates the MSpeer_topologyresponse system table with information about a peer-to-peer transactional
replication topology. Execute sp_gettopologyinfo to obtain information from the table in XML format.
Transact-SQL Syntax Conventions

Syntax
sp_requestpeertopologyinfo [ @publication = ] 'publication'
[ ,[ @requestid=] request_id OUTPUT

Arguments
[ @publication= ] 'publication'
Is the name of the publication for which to perform a topology-wide status request. publication is sysname, with
no default.
[ @request_id= ] request_id
Is the ID number that is assigned to the topology status request. request_id is int, with a default of NULL. This ID
can be used by sp_gettopologyinfo.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_requestpeertopologyinfo is used in peer-to-peer transactional replication. Execute sp_requestpeertopologyinfo
before executing sp_gettopologyinfo. These procedures are used by the Configure Peer-to-Peer Topology Wizard,
but they can also be used directly if you require topology information in an XML format. If you prefer tabular
results, query the MSpeer_topologyresponse system table.

Permissions
Requires membership in the sysadmin fixed server role or db_owner fixed database role.

See Also
Peer-to-Peer Transactional Replication
Replication Stored Procedures (Transact-SQL)
sp_resetsnapshotdeliveryprogress (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Resets the snapshot delivery process for a pull subscription so that snapshot delivery can be restarted. Executed at
the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_resetsnapshotdeliveryprogress [ [ @verbose_level = ] verbose_level ]
[ , [ @drop_table = ] 'drop_table' ]

Arguments
[ @verbose_level= ] verbose_level
Specifies the amount of information returned. verbose_levelis int, with a default of 1. A value of 1 means that an
error is returned if the necessary locks cannot be obtained on the MSsnapshotdeliveryprogress table, and 0
means that no error is returned.
[ @drop_table= ] 'drop_table'
Is whether to drop or truncate the table containing information on the progress of the snapshot.drop_table is
nvarchar(5), with a default of FALSE. false means that the table is truncated, and true means the table is dropped.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_resetsnapshotdeliveryprogress removes all rows in the MSsnapshotdeliveryprogress table. This effectively
removes all metadata left behind at the subscription database by any previous progress made in the snapshot
delivery processes.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_resetsnapshotdeliveryprogress.

See Also
Replication Stored Procedures (Transact-SQL)
sp_restoredbreplication (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Removes replication settings if restoring a database to the non-originating server, database, or system that is
otherwise not capable of running replication processes. When restoring a replicated database to a server or
database other than the one where the backup was taken, replication settings cannot be preserved. On the restore,
the server calls sp_restoredbreplication directly to automatically remove replication metadata from the restored
database.
Transact-SQL Syntax Conventions

Syntax
sp_restoredbreplication [ @srv_orig = ] 'original_server_name'
, [ @db_orig = ] 'original_database_name'
[ , [ @keep_replication = ] keep_replication ]
[ , [ @perform_upgrade = ] perform_upgrade ]

Arguments
[ @srv_orig = ] 'original_server_name'
The name of the server where the back up was created. original_server_name is sysname, with no default.
[ @db_orig = ] 'original_database_name'
The name of the database that was backed up. original_database_name is sysname, with no default.
[ @keep_replication = ] keep_replication
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @perform_upgrade= ] perform_upgrade
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_restoredbreplication is used in all types of replication.

Permissions
Only members of the sysadmin or dbcreator fixed server role or the dbo database schema can execute
sp_restoredbreplication.

See Also
Replication Stored Procedures (Transact-SQL)
sp_restoremergeidentityrange (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This stored procedure is used to update identity range assignments. It ensures that automatic identity range
management functions properly after a Publisher has been restored from a backup. This stored procedure is
executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_restoremergeidentityrange [ [ @publication = ] 'publication' ]
[ , [ @article = ] 'article' ]

Arguments
[ @publication = ] 'publication'
Is the name of the publication. publication is sysname, with default value of all. When specified, only identity
ranges for that publication are restored.
[ @article = ] 'article'
Is the name of the article. article is sysname, with a default value of all. When specified, only identity ranges for
that article are restored.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_restoremergeidentityrange is used with merge replication.
sp_restoremergeidentityrange gets maximum identity range allocation information from the Distributor and
updates values in the max_used column of MSmerge_identity_range_allocations (Transact-SQL) for the articles
which use automatic identity range management.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_restoremergeidentityrange.

See Also
sp_addmergearticle (Transact-SQL)
sp_changemergearticle (Transact-SQL)
Replicate Identity Columns
sp_resyncmergesubscription (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Resynchronizes a merge subscription to a known validation state that you specify. This allows you to force
convergence or synchronize the subscription database to a specific point in time, such as the last time there was a
successful validation, or to a specified date. The snapshot is not reapplied when resynchronizing a subscription
using this method. This stored procedure is not used for snapshot replication subscriptions or transactional
replication subscriptions. This stored procedure is executed at the Publisher, on the publication database, or at the
Subscriber, on the subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_resyncmergesubscription [ [ @publisher = ] 'publisher' ]
[ , [ @publisher_db = ] 'publisher_db' ]
, [ @publication = ] 'publication'
[ , [ @subscriber = ] 'subscriber' ]
[ , [ @subscriber_db = ] 'subscriber_db' ]
[ , [ @resync_type = ] resync_type ]
[ , [ @resync_date_str = ] resync_date_string ]

Arguments
[ @publisher = ] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of NULL. A value of NULL is valid if the stored
procedure is run at the Publisher. If the stored procedure is run at the Subscriber, a Publisher must be specified.
[ @publisher_db = ] 'publisher_db'
Is the name of the publication database. publisher_db is sysname, with a default of NULL. A value of NULL is valid
if the stored procedure is run at the Publisher in the publication database. If the stored procedure is run at the
Subscriber, a Publisher must be specified.
[ @publication = ] 'publication'
Is the name of the publication. publicationis sysname, with no default.
[ @subscriber = ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL. A value of NULL is valid if the stored
procedure is run at the Subscriber. If the stored procedure is run at the Publisher, a Subscriber must be specified.
[ @subscriber_db = ] 'subscriber_db'
Is the name of the subscription database. subscription_db is sysname, with a default of NULL. A value of NULL is
valid if the stored procedure is run at the Subscriber in the subscription database. If the stored procedure is run at
the Publisher, a Subscriber must be specified.
[ @resync_type = ] resync_type
Defines when the resynchronization should start at. resync_type is int, and can be one of the following values.
VALUE DESCRIPTION

0 Synchronization starts from after the initial snapshot. This is


the most resource-intensive option, since all changes since the
initial snapshot are reapplied to the Subscriber.

1 Synchronization starts since last successful validation. All new


or incomplete generations originating since the last successful
validation are reapplied to the Subscriber.

2 Synchronization starts from the date given in resync_date_str.


All new or incomplete generations originating after the date
are reapplied to the Subscriber

[ @resync_date_str=] resync_date_string
Defines the date when the resynchronization should start at. resync_date_string is nvarchar(30), with a default of
NULL. This parameter is used when the resync_type is a value of 2. The date given is converted to its equivalent
datetime value.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_resyncmergesubscription is used in merge replication.
A value of 0 for the resync_type parameter, which reapplies all changes since the initial snapshot, may be resource-
intensive, but possibly a lot less than a full reinitialization. For example, if the initial snapshot was delivered one
month ago, this value would cause data from the past month to be reapplied. If the initial snapshot contained 1
gigabyte (GB) of data, but the amount of changes from the past month consisted of 2 megabytes (MB) of changed
data, it would be more efficient to reapply the data than to reapply the full 1 GB snapshot.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_resyncmergesubscription.

See Also
System Stored Procedures (Transact-SQL)
sp_revoke_publication_access (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes the login from a publications access list. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_revoke_publication_access [ @publication = ] 'publication' , [ @login = ] 'login'

Arguments
[ @publication=] 'publication'
Is the name of the publication to access. publication is sysname, with no default.
[ @login=] 'login'
Is the login ID. login is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_revoke_publication_access is used in snapshot, transactional, and merge replication.
sp_revoke_publication_access can be called repeatedly.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_revoke_publication_access.

See Also
sp_grant_publication_access (Transact-SQL)
sp_help_publication_access (Transact-SQL)
Secure the Publisher
System Stored Procedures (Transact-SQL)
sp_schemafilter (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Modifies and displays information on the schema that is excluded when listing Oracle tables eligible for publishing.
Transact-SQL Syntax Conventions

Syntax
sp_schemafilter [ @publisher = ] 'publisher'
[ , [ @schema = ] 'schema' ]
[ , [ @operation = ] 'operation' ]

Arguments
[@publisher = ] 'publisher'
Is the name of the non- Microsoft SQL Server Publisher. publisher is sysname, with no default.
[@schema = ] 'schema'
Is the name of the schema. schema is sysname, with a default value of NULL.
[@operation = ] 'operation'
Is the action to be taken on this schema. operation is nvarchar(4), and can be one of the following values.

VALUE DESCRIPTION

add Adds the specified schema to the list of schema that are not
eligible for publication.

drop Drops the specified schema from the list of schema that are
not eligible for publication.

help Returns the list of schema that are not eligible for publication.

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

schemaname sysname Is the name of the schema not eligible


for publication.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_schemafilter should only be used for heterogeneous publishers.

Permissions
Only members of the sysadmin fixed server role at the Distributor can execute sp_schemafilter.

See Also
Replication Stored Procedures (Transact-SQL)
sp_script_synctran_commands (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Generates a script that contains the sp_addsynctrigger calls to be applied at Subscribers for updatable
subscriptions. There is one sp_addsynctrigger call for each article in the publication. The generated script also
contains the sp_addqueued_artinfo calls that create the MSsubsciption_articles table that is needed to
process queued publications. This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_script_synctran_commands [@publication = ] 'publication'
[ , [@article = ] 'article']

Arguments
[ @publication = ] 'publication'
Is the name of the publication to be scripted. publication is sysname, with no default.
[ @article = ] 'article'
Is the name of the article to be scripted. article is sysname, with a default of all, which specifies all articles are
scripted.

Return Code Values


0 (success) or 1 (failure)

Results Set
sp_script_synctran_commands returns a result set that consists of a single nvarchar(4000) column. The result
set forms the complete scripts necessary to create both the sp_addsynctrigger and sp_addqueued_artinfo
calls to be applied at Subscribers.

Remarks
sp_script_synctran_commands is used in snapshot and transactional replication.
sp_addqueued_artinfo is used for queued updatable subscriptions.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_script_synctran_commands.

See Also
sp_addsynctriggers (Transact-SQL)
sp_addqueued_artinfo (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_scriptdynamicupdproc (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Generates the CREATE PROCEDURE statement that creates a dynamic update stored procedure. The UPDATE
statement within the custom stored procedure is built dynamically based on the MCALL syntax that indicates which
columns to change. Use this stored procedure if the number of indexes on the subscribing table is growing and the
number of columns being changed is small. This stored procedure is run at the Publisher on the publication
database.
Transact-SQL Syntax Conventions

Syntax
sp_scriptdynamicupdproc [ @artid =] artid

Arguments
[ @artid=] artid
Is the article ID. artid is int, with no default.

Result Sets
Returns a result set that consists of a single nvarchar(4000) column. The result set forms the complete CREATE
PROCEDURE statement used to create the custom stored procedure.

Remarks
sp_scriptdynamicupdproc is used in transactional replication. The default MCALL scripting logic includes all
columns within the UPDATE statement and uses a bitmap to determine the columns that have changed. If a column
did not change, the column is set back to itself, which usually causes no problems. If the column is indexed, extra
processing occurs. The dynamic approach includes only the columns that have changed, which provides an optimal
UPDATE string. However, extra processing is incurred at runtime when the dynamic UPDATE statement is built. We
recommend that you test the dynamic and static approaches, and then choose the optimal solution.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_scriptdynamicupdproc.

Examples
This example creates an article (with artid set to 1) on the authors table in the pubs database and specifies that the
UPDATE statement is the custom procedure to execute:

'MCALL sp_mupd_authors'
Generate the custom stored procedures to be executed by the Distribution Agent at the Subscriber by running the
following stored procedure at the Publisher:

EXEC sp_scriptdynamicupdproc @artid = '1'

The statement returns:

CREATE PROCEDURE [sp_mupd_authors]


@c1 varchar(11),@c2 varchar(40),@c3 varchar(20),@c4 char(12),@c5 varchar(40),@c6 varchar(20),
@c7 char(2),@c8 char(5),@c9 bit,@pkc1 varchar(11),@bitmap binary(2)
as

declare @stmt nvarchar(4000), @spacer nvarchar(1)


SELECT @spacer =N''
SELECT @stmt = N'UPDATE [authors] SET '

if substring(@bitmap,1,1) & 2 = 2
begin
select @stmt = @stmt + @spacer + N'[au_lname]' + N'=@2'
select @spacer = N','
end
if substring(@bitmap,1,1) & 4 = 4
begin
select @stmt = @stmt + @spacer + N'[au_fname]' + N'=@3'
select @spacer = N','
end
if substring(@bitmap,1,1) & 8 = 8
begin
select @stmt = @stmt + @spacer + N'[phone]' + N'=@4'
select @spacer = N','
end
if substring(@bitmap,1,1) & 16 = 16
begin
select @stmt = @stmt + @spacer + N'[address]' + N'=@5'
select @spacer = N','
end
if substring(@bitmap,1,1) & 32 = 32
begin
select @stmt = @stmt + @spacer + N'[city]' + N'=@6'
select @spacer = N','
end
if substring(@bitmap,1,1) & 64 = 64
begin
select @stmt = @stmt + @spacer + N'[state]' + N'=@7'
select @spacer = N','
end
if substring(@bitmap,1,1) & 128 = 128
begin
select @stmt = @stmt + @spacer + N'[zip]' + N'=@8'
select @spacer = N','
end
if substring(@bitmap,2,1) & 1 = 1
begin
select @stmt = @stmt + @spacer + N'[contract]' + N'=@9'
select @spacer = N','
end
select @stmt = @stmt + N' where [au_id] = @1'
exec sp_executesql @stmt, N' @1 varchar(11),@2 varchar(40),@3 varchar(20),@4 char(12),@5 varchar(40),
@6 varchar(20),@7 char(2),@8 char(5),@9
bit',@pkc1,@c2,@c3,@c4,@c5,@c6,@c7,@c8,@c9

if @@rowcount = 0
if @@microsoftversion>0x07320000
exec sp_MSreplraiserror 20598
After running this stored procedure, you can use the resulting script to create the stored procedure manually at the
Subscribers.

See Also
System Stored Procedures (Transact-SQL)
sp_scriptpublicationcustomprocs (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Scripts the custom INSERT, UPDATE, and DELETE procedures for all table articles in a publication in which the auto-
generate custom procedure schema option is enabled. sp_scriptpublicationcustomprocs is particularly useful
for setting up subscriptions for which the snapshot is applied manually.
Transact-SQL Syntax Conventions

Syntax
sp_scriptpublicationcustomprocs [ @publication = ] 'publication_name'

Arguments
[ @publication=] 'publication_name'
Is the name of the publication. publication_name is sysname with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
Returns a result set that consists of a single nvarchar(4000) column. The result set forms the complete CREATE
PROCEDURE statement necessary to create the custom stored procedure.

Remarks
Custom procedures are not scripted for articles without the auto-generate custom procedure (0x2) schema option.
The following procedures are used by sp_scriptpublicationcustomprocs to create procedures the Subscriber and
should not be executed directly:
sp_script_reconciliation_delproc
sp_script_reconciliation_insproc
sp_script_reconciliation_vdelproc
sp_script_reconciliation_xdelproc
sp_scriptdelproc
sp_scriptinsproc
sp_scriptmappedupdproc
sp_scriptupdproc
sp_scriptvdelproc
sp_scriptvupdproc
sp_scriptxdelproc
sp_scriptxupdproc

Permissions
Execute permission is granted to public; a procedural security check is performed inside this stored procedure to
restrict access to members of the sysadmin fixed server role and db_owner fixed database role in current
database.

See Also
System Stored Procedures (Transact-SQL)
sp_scriptsubconflicttable (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Generates script for creating a conflict table on the Subscriber for a given queued subscription article. The script
that is generated is executed at the Subscriber on the subscription database. This stored procedure is executed at
the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_scriptsubconflicttable [@publication =] 'publication' , [@article =] 'article'

Arguments
[ @publication=] 'publication'
Is the name of the publication that contains the article. The name must be unique in the database. publication is
sysname, with no default.
[ @article=] 'article'
Is the name of the subscription article. article is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
COLUMN NAME DATA TYPE DESCRIPTION

cmdtext nvarchar(4000) Returns the Transact-SQL script for


creating the conflict table on the
Subscriber for the queued subscription
article. This script is executed on the
Subscriber in the subscription database.

Remarks
sp_scriptsubconflicttable is used for Subscribers that have subscriptions where the initial snapshot is applied
manually. The conflict table is an optional table at the Subscriber.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_scriptsubconflicttable.
See Also
Queued Updating Conflict Detection and Resolution
System Stored Procedures (Transact-SQL)
sp_setdefaultdatatypemapping (Transact-SQL)
11/21/2017 • 3 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Marks an existing data type mapping between Microsoft SQL Server and a non- SQL Server database
management system (DBMS) as the default. This stored procedure is executed at the Distributor on any database.
Transact-SQL Syntax Conventions

Syntax
sp_setdefaultdatatypemapping [ [ @mapping_id = ] mapping_id ]
[ , [ @source_dbms = ] 'source_dbms' ]
[ , [ @source_version = ] 'source_version' ]
[ , [ @source_type = ] 'source_type' ]
[ , [ @source_length_min = ] source_length_min ]
[ , [ @source_length_max = ] source_length_max ]
[ , [ @source_precision_min = ] source_precision_min ]
[ , [ @source_precision_max = ] source_precision_max ]
[ , [ @source_scale_min = ] source_scale_min ]
[ , [ @source_scale_max = ] source_scale_max ]
[ , [ @source_nullable = ] source_nullable ]
[ , [ @destination_dbms = ] 'destination_dbms' ]
[ , [ @destination_version = ] 'destination_version' ]
[ , [ @destination_type = ] 'destination_type' ]
[ , [ @destination_length = ] destination_length ]
[ , [ @destination_precision = ] destination_precision ]
[ , [ @destination_scale = ] destination_scale ]
[ , [ @destination_nullable = ] source_nullable ]

Arguments
[ @mapping_id= ] mapping_id
Identifies an existing data type mapping. mapping_id is int, with default value of NULL. If you specify mapping_id,
then the remaining parameters are not required.
[ @source_dbms= ] 'source_dbms'
Is the name of the DBMS from which the data types are mapped. source_dbms is sysname, and can be one of the
following values.

VALUE DESCRIPTION

MSSQLSERVER The source is a SQL Server database.

ORACLE The source is an Oracle database.

NULL (default)

You must specify this parameter if mapping_id is NULL.


[ @source_version= ] 'source_version'
Is the version number of the source DBMS. source_version is varchar(10), with a default value of NULL.
[ @source_type= ] 'source_type'
Is the data type in the source DBMS. source_type is sysname. You must specify this parameter if mapping_id is
NULL.
[ @source_length_min= ] source_length_min
Is the minimum length of the data type in the source DBMS. source_length_min is bigint, with a default value of
NULL.
[ @source_length_max= ] source_length_max
Is the maximum length of the data type in the source DBMS. source_length_max is bigint, with a default value of
NULL.
[ @source_precision_min= ] source_precision_min
Is the minimum precision of the data type in the source DBMS. source_precision_min is bigint, with a default value
of NULL.
[ @source_precision_max= ] source_precision_max
Is the maximum precision of the data type in the source DBMS. source_precision_max is bigint, with a default
value of NULL.
[ @source_scale_min= ] source_scale_min
Is the minimum scale of the data type in the source DBMS. source_scale_min is int, with a default value of NULL.
[ @source_scale_max= ] source_scale_max
Is the maximum scale of the data type in the source DBMS. source_scale_max is int, with a default value of NULL.
[ @source_nullable= ] source_nullable
Is if the data type in the source DBMS supports a value of NULL. source_nullable is bit, with a default value of
NULL. 1 means that NULL values are supported.
[ @destination_dbms = ] 'destination_dbms'
Is the name of the destination DBMS. destination_dbms is sysname, and can be one of the following values.

VALUE DESCRIPTION

MSSQLSERVER The destination is a SQL Server database.

ORACLE The destination is an Oracle database.

DB2 The destination is an IBM DB2 database.

SYBASE The destination is a Sybase database.

NULL (default)

[ @destination_version= ] 'destination_version'
Is the product version of the destination DBMS. destination_version is varchar(10), with a default value of NULL.
[ @destination_type= ] 'destination_type'
Is the data type listed in the destination DBMS. destination_type is sysname, with a default value of NULL.
[ @destination_length= ] destination_length
Is the length of the data type in the destination DBMS. destination_length is bigint, with a default value of NULL.
[ @destination_precision= ] destination_precision
Is the precision of the data type in the destination DBMS. destination_precision is bigint, with a default value of
NULL.
[ @destination_scale= ] destination_scale
Is the scale of the data type in the destination DBMS. destination_scale is int, with a default value of NULL.
[ @destination_nullable= ] destination_nullable
Is if the data type in the destination DBMS supports a value of NULL. destination_nullable is bit, with a default
value of NULL. 1 means that NULL values are supported.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_setdefaultdatatypemapping is used in all types of replication between SQL Server and a non- SQL Server
DBMS.
The default data type mappings apply to all replication topologies that include the specified DBMS.

Permissions
Only members of the sysadmin fixed server role can execute sp_setdefaultdatatypemapping.

See Also
Specify Data Type Mappings for an Oracle Publisher
sp_getdefaultdatatypemapping (Transact-SQL)
sp_helpdatatypemap (Transact-SQL)
sp_setreplfailovermode (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Allows you to set the failover operation mode for subscriptions enabled for immediate updating with queued
updating as failover. This stored procedure is executed at the Subscriber on the subscription database. For more
information about failover modes, see Updatable Subscriptions for Transactional Replication.
Transact-SQL Syntax Conventions

Syntax
sp_setreplfailovermode [ @publisher= ] 'publisher'
[ , [ @publisher_db = ] 'publisher_db' ]
[ , [ @publication= ] 'publication' ]
[ , [ @failover_mode= ] 'failover_mode' ]
[ , [ @override = ] override ]

Arguments
[ @publisher=] 'publisher'
Is the name of the publication. publication is sysname, with no default. The publication must already exist.
[ @publisher_db =] 'publisher_db'
Is the name of the publication database. publisher_db is sysname, with no default.
[ @publication=] 'publication'
Is the name of the publication. publicationis sysname, with no default.
[@failover_mode=] 'failover_mode'
Is the failover mode for the subscription. failover_mode is nvarchar(10) and can be one of these values.

VALUE DESCRIPTION

immediate or sync Data modifications made at the Subscriber are bulk-copied to


the Publisher as they occur.

queued Data modifications are stored in a Microsoft SQL Server


queue.

NOTE
Microsoft Message Queuing has been deprecated and is no longer supported.

[ @override= ] override
Internal use only.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_setreplfailovermode is used in snapshot replication or transactional replication for which subscriptions are
enabled, either for queued updating with failover to immediate updating, or for immediate updating with failover
to queued updating.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_setreplfailovermode.

See Also
Switch Between Update Modes for an Updatable Transactional Subscription
System Stored Procedures (Transact-SQL)
sp_setsubscriptionxactseqno (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Used during troubleshooting to specify the log sequence number (LSN) of the next transaction to be applied by the
Distribution Agent at the Subscriber, which enables the agent to skip a failed transaction. This stored procedure is
executed at the Subscriber on the subscription database. Not supported for non-SQL Server Subscribers.
Cau t i on

Using this stored procedure incorrectly or specifying an incorrect LSN value can cause the Distribution Agent to
revert changes that were already applied at the Subscriber or skip over all remaining changes.
Transact-SQL Syntax Conventions

Syntax
sp_setsubscriptionxactseqno [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
, [ @publication = ] 'publication'
, [ @xact_seqno = ] xact_seqno

Arguments
[ @publisher= ] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db= ] 'publisher_db'
Is the name of the publication database. publisher_db is sysname, with no default. For a non-SQL Server Publisher,
publisher_db is the name of the distribution database.
[ @publication= ] 'publication'
Is the name of the publication. publication is sysname, with no default. When the Distribution Agent is shared by
more than one publication, you must specify a value of ALL for publication.
[ @xact_seqno= ] xact_seqno
Is the LSN of the next transaction at the Distributor to be applied at the Subscriber. xact_seqno is varbinary(16),
with no default.

Result Set
COLUMN NAME DATA TYPE DESCRIPTION

ORIGINAL XACT_SEQNO varbinary(16) The original LSN of the next transaction


to be applied at the Subscriber.

UPDATED XACT_SEQNO varbinary(16) The updated LSN of the next


transaction to be applied at the
Subscriber.
COLUMN NAME DATA TYPE DESCRIPTION

SUBSCRIPTION STREAM COUNT int The number of subscription streams


used during the last synchronization.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_setsubscriptionxactseqno is used in transactional replication.
sp_setsubscriptionxactseqno cannot be used in a peer-to-peer transactional replication topology.
sp_setsubscriptionxactseqno can be used to skip a specific transaction that is causing an error when applies at
the Subscriber. When there is a failure and after the Distribution Agent stops, call sp_helpsubscriptionerrors
(Transact-SQL) at the Distributor to retrieve the xact_seqno value of the failed transaction, and then call
sp_setsubscriptionxactseqno, passing this value for xact_seqno. This will ensure that only the commands after
this LSN will be processed.
Specify a value of 0 for xact_seqno to deliver all pending commands in the distribution database to the Subscriber.
sp_setsubscriptionxactseqno may fail if the Distribution Agent uses multi-subscription streams.
When this error occurs, you must run the Distribution Agent with a single subscription stream. For more
information, see Replication Distribution Agent.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_setsubscriptionxactseqno.
sp_showpendingchanges (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Returns a result set showing the changes that are waiting to be replicated. This stored procedure is executed at the
Publisher on the publication database and at the Subscriber on the subscription database.
Transact-SQL Syntax Conventions

NOTE
This procedure provides an approximation of the number of changes and the rows that are involved in those changes. For
example, the procedure retrieves information from either the Publisher or Subscriber, but not both at the same time.
Information that is stored at the other node might result in a smaller set of changes to synchronize than the procedure
estimates.

Syntax
sp_showpendingchanges [ [ @destination_server = ] 'destination_server' ]
[ , [ @publication = ] 'publication' ]
[ , [ @article = ] 'article']
[ , [ @show_rows = ] show_rows]

Arguments
[ @destination_server**=** ] 'destination_server'
Is the name of the server where the replicated changes are applied. destination_server is sysname, with default
value of NULL.
[ @publication**=** ] 'publication'
Is the name of the publication. publication is sysname, with a default value of NULL. When publication is specified,
results are limited only to the specified publication.
[ @article = ] 'article'
Is the name of the article. article is sysname, with a default value of NULL. When article is specified, results are
limited only to the specified article.
[ @show_rows = ] show_rows
Specifies whether the result set contains more specific information about pending changes, with a default value of
0. If a value of 1 is specified, the result set contains the columns is_delete and rowguid.

Result Set
COLUMN NAME DATA TYPE DESCRIPTION

destination_server sysname The name of the server to which the


changes are being replicated.
COLUMN NAME DATA TYPE DESCRIPTION

pub_name sysname The name of the publication.

destination_db_name sysname The name of the database to which the


changes are being replicated.

is_dest_subscriber bit Indicates of the changes are being


replicated to a Subscriber. A value of 1
indicates that the changes are being
replicated to a Subscriber. 0 means that
changes are being replicated to a
Publisher.

article_name sysname The name of the article for the table


where changes originated.

pending_deletes int The number of deletes waiting to be


replicated.

pending_ins_and_upd int The number of inserts and updates


waiting to be replicated.

is_delete bit Indicates whether the pending change


is a delete. A value of 1 indicates that
the change is a delete. Requires a value
of 1 for @show_rows.

rowguid uniqueidentifier The GUID that identifies the row that


changed. Requires a value of 1 for
@show_rows.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_showpendingchanges is used in merge replication.
sp_showpendingchanges is used when troubleshooting merge replication.
The result of sp_showpendingchanges does not include rows in generation 0.
When an article specified for article does not belong to the publication specified for publication, a count of 0 is
returned for pending_deletes and pending_ins_and_upd.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_showpendingchanges.

See Also
Replication Stored Procedures (Transact-SQL)
sp_showrowreplicainfo (Transact-SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Displays information about a row in a table that is being used as an article in merge replication. This stored
procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_showrowreplicainfo [ [ @ownername = ] 'ownername' ]
[ , [ @tablename =] 'tablename' ]
, [ @rowguid =] rowguid
[ , [ @show = ] 'show' ]

Arguments
[ @ownername= ] 'ownername'
Is the name of the table owner. ownername is sysname, with a default of NULL. This parameter is useful to
differentiate tables if a database contains multiple tables with the same name, but each table has a different owner.
[ @tablename =] 'tablename'
Is the name of the table that contains the row for which the information is returned. tablename is sysname, with a
default of NULL.
[ @rowguid =] rowguid
Is the unique identifier of the row. rowguid is uniqueidentifier, with no default.
[ @show= ] 'show'
Determines the amount of information to return in the result set. show is nvarchar(20) with a default of BOTH. If
row, only row version information is returned. If columns, only column version information is returned. If both,
both row and column information is returned.

Result Sets for Row Information


COLUMN NAME DATA TYPE DESCRIPTION

server_name sysname Name of the server hosting the


database that made the row version
entry.

db_name sysname Name of the database that made this


entry.

db_nickname binary(6) Nickname of the database that made


this entry.
COLUMN NAME DATA TYPE DESCRIPTION

version int Version of the entry.

current_state nvarchar(9) Returns information on the current


state of the row.

y - Row data represents the current


state of the row.

n - Row data does not represent the


current state of the row.

<n/a> - Not applicable.

<unknown> - Current state cannot be


determined.

rowversion_table nchar(17) Indicates whether the row versions are


stored in the MSmerge_contents table
or the MSmerge_tombstone table.

comment nvarchar(255) Additional information about this row


version entry. Usually, this field is
empty.

Result Sets for Column Information


COLUMN NAME DATA TYPE DESCRIPTION

server_name sysname Name of the server hosting the


database that made the column version
entry.

db_name sysname Name of the database that made this


entry.

db_nickname binary(6) Nickname of the database that made


this entry.

version int Version of the entry.

colname sysname Name of the article column that the


column version entry represents.

comment nvarchar(255) Additional information about this


column version entry. Usually, this field
is empty.

Result Set for both


If the value both is chosen for show, then both the row and column result sets is returned.

Remarks
sp_showrowreplicainfo is used in merge replication.
Permissions
sp_showrowreplicainfo can only be executed by members of the db_owner fixed database role on the
publication database or by members of the publication access list (PAL) on the publication database.

See Also
Detect and Resolve Merge Replication Conflicts
System Stored Procedures (Transact-SQL)
sp_startpublication_snapshot (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Used to start the Snapshot Agent job that generates the initial snapshot for a publication. This stored procedure is
executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_startpublication_snapshot [ @publication = ] 'publication'
[ , [ @publisher = ] 'publisher' ]

Arguments
[ @publication= ] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @publisher= ] 'publisher'
Is the name of a non- SQL Server Publisher. publisher is sysname, with a default value of NULL. You should not
specify this parameter for a SQL Server Publisher.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_startpublication_snapshot is used with all types of replication.
For a non- SQL Server Publisher, this stored procedure is executed at the Distributor on the distribution database.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_startpublication_snapshot.

See Also
Create and Apply the Initial Snapshot
sp_addpublication_snapshot (Transact-SQL)
sp_changepublication_snapshot (Transact-SQL)
sp_subscription_cleanup (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Removes metadata when a subscription is dropped at a Subscriber. For a synchronizing transaction subscription,
it also includes immediate-updating triggers. This stored procedure is executed at the Subscriber on the
subscription database.
Transact-SQL Syntax Conventions

Syntax
sp_subscription_cleanup [ @publisher = ] 'publisher'
, [ @publisher_db = ] 'publisher_db'
[ , [ @publication = ] 'publication']
[ , [ @reserved = ] 'reserved']

Arguments
[ @publisher=] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[ @publisher_db=] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[ @publication=] 'publication'
Is the name of the publication. publication is sysname, with a default of NULL. If NULL, subscriptions using a
shared agent publication in the publishing database will be deleted.
[ @reserved=] 'reserved'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_subscription_cleanup is used in transactional and snapshot replication.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_subscription_cleanup.

See Also
sp_expired_subscription_cleanup (Transact-SQL)
sp_mergesubscription_cleanup (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_table_validation (Transact-SQL)
11/21/2017 • 4 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2014) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Either returns rowcount or checksum information on a table or indexed view, or compares the provided rowcount
or checksum information with the specified table or indexed view. This stored procedure is executed at the
Publisher on the publication database and at the Subscriber on the subscription database. Not supported for
Oracle Publishers.
Transact-SQL Syntax Conventions

Syntax
sp_table_validation [ @table = ] 'table'
[ , [ @expected_rowcount = ] type_of_check_requested OUTPUT]
[ , [ @expected_checksum = ] expected_checksum OUTPUT]
[ , [ @rowcount_only = ] rowcount_only ]
[ , [ @owner = ] 'owner' ]
[ , [ @full_or_fast = ] full_or_fast ]
[ , [ @shutdown_agent = ] shutdown_agent ]
[ , [ @table_name = ] table_name ]
[ , [ @column_list = ] 'column_list' ]

Arguments
[ @table=] 'table'
Is the name of the table. table is sysname, with no default.
[ @expected_rowcount=] expected_rowcountOUTPUT
Specifies whether to return the expected number of rows in the table. expected_rowcount is int, with a default of
NULL. If NULL, the actual rowcount is returned as an output parameter. If a value is provided, that value is checked
against the actual rowcount to identify any differences.
[ @expected_checksum=] expected_checksumOUTPUT
Specifies whether to return the expected checksum for the table. expected_checksum is numeric, with a default of
NULL. If NULL, the actual checksum is returned as an output parameter. If a value is provided, that value is checked
against the actual checksum to identify any differences.
[ @rowcount_only=] type_of_check_requested
Specifies what type of checksum or rowcount to perform. type_of_check_requested is smallint, with a default of 1.
If 0, perform a rowcount and a Microsoft SQL Server 7.0-compatible checksum.
If 1, perform a rowcount check only.
If 2, perform a rowcount and binary checksum.
[ @owner=] 'owner'
Is the name of the owner of the table. owner is sysname, with a default of NULL.
[ @full_or_fast=] full_or_fast
Is the method used to calculate the rowcount. full_or_fast is tinyint, with a default of 2, and can be one of these
values.

VALUE DESCRIPTION

0 Does full count using COUNT(*).

1 Does fast count from sysindexes.rows. Counting rows in


sysindexes is much faster than counting rows in the actual
table. However, because sysindexes is lazily updated, the
rowcount may not be accurate.

2 (default) Does conditional fast counting by first trying the fast method.
If fast method shows differences, reverts to full method. If
expected_rowcount is NULL and the stored procedure is being
used to get the value, a full COUNT(*) is always used.

[ @shutdown_agent=] shutdown_agent
If the Distribution Agent is executing sp_table_validation, specifies whether the Distribution Agent should shut
down immediately upon completion of the validation. shutdown_agent is bit, with a default of 0. If 0, the
replication agent does not shut down. If 1, error 20578 is raised and the replication agent is signaled to shut down.
This parameter is ignored when sp_table_validation is executed directly by a user.
[ @table_name =] table_name
Is the table name of the view used for output messages. table_name is sysname, with a default of @table.
[ @column_list= ] 'column_list'
Is the list of columns that should be used in the checksum function. column_list is nvarchar(4000), with a default
of NULL. Enables validation of merge articles to specify a column list that excludes computed and timestamp
columns.

Return Code Values


If performing a checksum validation and the expected checksum equals the checksum in the table,
sp_table_validation returns a message that the table passed checksum validation. Otherwise, it returns a
message that the table may be out of synchronization and reports the difference between the expected and the
actual number of rows.
If performing a rowcount validation and the expected number of rows equals the number in the table,
sp_table_validation returns a message that the table passed rowcount validation. Otherwise, it returns a
message that the table may be out of synchronization and reports the difference between the expected and the
actual number of rows.

Remarks
sp_table_validation is used in all types of replication. sp_table_validation is not supported for Oracle
Publishers.
Checksum computes a 32-bit cyclic redundancy check (CRC) on the entire row image on the page. It does not
selectively check columns and cannot operate on a view or vertical partition of the table. Also, the checksum skips
the contents of text and image columns (by design).
When doing a checksum, the structure of the table must be identical between the two servers; that is, the tables
must have the same columns existing in the same order, same data types and lengths, and same NULL/NOT NULL
conditions. For example, if the Publisher did a CREATE TABLE, then an ALTER TABLE to add columns, but the script
applied at the Subscriber is a simple CREATE table, the structure is NOT the same. If you are not certain that the
structure of the two tables is identical, look at syscolumns and confirm that the offset in each table is the same.
Floating point values are likely to generate checksum differences if character-mode bcp was used, which is the
case if the publication has non- SQL Server subscribers. These are due to minor and unavoidable differences in
precision when doing conversion to and from character mode.

Permissions
To execute sp_table_validation, you must have SELECT permissions on the table being validated.

See Also
CHECKSUM (Transact-SQL)
@@ROWCOUNT (Transact-SQL)
sp_article_validation (Transact-SQL)
sp_publication_validation (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_unregister_custom_scripting (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
This stored procedure removes a user-defined custom stored procedure or Transact-SQL script file that was
registered by executing sp_register_custom_scripting. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_unregister_custom_scripting [ @type = ] 'type'
[ , [ @publication = ] 'publication' ]
[ , [ @article = ] 'article' ]

Arguments
[ @type = ] 'type'
Is the type of custom stored procedure or script being removed. type is varchar(16), with no default, and can be
one of the following values.

VALUE DESCRIPTION

insert Registered custom stored procedure or script is executed


when an INSERT statement is replicated.

update Registered custom stored procedure or script is executed


when an UPDATE statement is replicated.

delete Registered custom stored procedure or script is executed


when a DELETE statement is replicated.

custom_script Registered custom stored procedure or script is executed at


the end of the data definition language (DDL) trigger.

[ @publication = ] 'publication'
Name of the publication for which the custom stored procedure or script is being removed. publication is
sysname, with a default of NULL.
[ @article = ] 'article'
Name of the article for which the custom stored procedure or script is being removed. article is sysname, with a
default of NULL.

Return Code Values


0 (success) or 1 (failure)
Remarks
sp_unregister_custom_scripting is used in snapshot and transactional replication.

Permissions
Only members of the sysadmin fixed server role, the db_owner fixed database role, or the db_ddladmin fixed
database role can execute sp_unregister_custom_scripting.

See Also
sp_register_custom_scripting (Transact-SQL)
sp_unregistercustomresolver (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Unregisters a previously registered business logic module. Business logic can be in the form of either a COM
component or a Microsoft .NET Framework assembly. This stored procedure is executed on the Distributor where
the custom business logic was registered.
Transact-SQL Syntax Conventions

Syntax
sp_unregistercustomresolver [ @article_resolver = ] 'article_resolver'

Arguments
[ @article_resolver = ] 'article_resolver'
Specifies the name of the custom business logic being unregistered. article_resolver is nvarchar(255), with no
default. If the business logic being removed is a COM component, this parameter is the friendly name of the
component. If the business logic is a .NET Framework assembly, this parameter is the name of the assembly.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_unregistercustomresolver is used in merge replication.
Use sp_enumcustomresolvers at any server in the replication topology to return the list of registered custom
business logic modules or COM resolvers available to the topology.

Permissions
Only members of the sysadmin fixed server role or db_owner fixed database role can execute
sp_unregistercustomresolver.

See Also
sp_lookupcustomresolver (Transact-SQL)
sp_registercustomresolver (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_update_agent_profile (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Updates the profile used by a replication agent. This stored procedure is executed at the Distributor on the
distribution database.
Transact-SQL Syntax Conventions

Syntax
sp_update_agent_profile [@agent_type=] agent_type, [ @agent_id= ] agent_id, [ @profile_id= ] profile_id

Arguments
[@agent_type=] 'agent_type'
Is the type of agent. agent_type is int, with no default, and can be one of these values.

VALUE DESCRIPTION

1 Snapshot Agent.

2 Log Reader Agent.

3 Distribution Agent.

4 Merge Agent.

9 Queue Reader Agent.

[@agent_id=] agent_id
Is the ID of the agent. agent_id is int, with no default.
[@profile_id=] profile_id
Is the ID of the profile that the agent should use. profile_id is int, with no default. To view a list of profiles defined
for each agent, use sp_help_agent_profile (Transact-SQL). For more information about system profiles, see
Replication Agent Profiles.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_update_agent_profile is used in all types of replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_update_agent_profile.

See Also
Replication Agent Profiles
sp_add_agent_profile (Transact-SQL)
sp_change_agent_profile (Transact-SQL)
sp_drop_agent_profile (Transact-SQL)
sp_help_agent_profile (Transact-SQL)
System Stored Procedures (Transact-SQL)
sp_validate_redirected_publisher (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Verifies that the current host for the publishing database is capable of supporting replication. Must be run from a
distribution database. This procedure is called by sp_get_redirected_publisher.
Transact-SQL Syntax Conventions

Syntax
sp_validate_redirected_publisher
[ @original_publisher = ] 'original_publisher',
[ @publisher_db = ] 'database_name',
[ @redirected_publisher = ] 'new_publisher' output

Arguments
[ @original_publisher = ] 'original_publisher'
The name of the instance of SQL Server that originally published the database. original_publisher is sysname,
with no default.
[ @publisher_db = ] 'publisher_db'
The name of the database being published. publisher_db is sysname, with no default.
[ @redirected_publisher = ] 'redirected_publisher'
The target of redirection specified when sp_redirect_publisher was called for the publisher/database pair.
redirected_publisher is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Remarks
If no entry exists for the publisher and the publishing database, sp_validate_redirected_publisher returns null in
the output parameter @redirected_publisher. If an entry exists, it is returned in the output parameter in both
success and failure cases.
If the validation succeeds, sp_validate_redirected_publisher returns a success indication.
If the validation fails, errors are raised describing the failure.

Permissions
Caller must either be a member of the sysadmin fixed server role, the db_owner fixed database role for the
distribution database, or a member of a publication access list for a defined publication associated with the
publisher database.

See Also
Replication Stored Procedures (Transact-SQL)
sp_get_redirected_publisher (Transact-SQL)
sp_redirect_publisher (Transact-SQL)
sp_validate_replica_hosts_as_publishers (Transact-SQL)
sp_validate_replica_hosts_as_publishers (Transact-
SQL)
11/21/2017 • 2 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2012) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
sp_validate_replica_hosts_as_publishers is an extension of sp_validate_redirected_publisher that allows all
secondary replicas to be validated, rather than just the current primary replica.
sp_validate_replicat_hosts_as_publisher validates an entire Always On replication topology.
sp_validate_replica_hosts_as_publishers must be executed directly on the distributor by using a remote
desktop session to avoid a double-hop security error (21892).
Transact-SQL Syntax Conventions

Syntax
sp_validate_replica_hosts_as_publishers
[ @original_publisher = ] 'original_publisher',
[ @publisher_db = ] 'database_name',
[ @redirected_publisher = ] 'new_publisher' output

Arguments
[ @original_publisher = ] 'original_publisher'
The name of the instance of SQL Server that originally published the database. original_publisher is sysname,
with no default.
[ @publisher_db = ] 'publisher_db'
The name of the database being published. publisher_db is sysname, with no default.
[ @redirected_publisher = ] 'redirected_publisher'
The target of redirection when sp_redirect_publisher was called for the original publisher/published database
pair. redirected_publisher is sysname, with no default.

Return Code Values


0 (success) or 1 (failure)

Result Sets
None.

Remarks
If no entry exists for the publisher and the publishing database, sp_validate_redirected_publisher returns null
for the output parameter @redirected_publisher. Otherwise, the associated redirected publisher is returned, both
on success and failure.
If the validation succeeds, sp_validate_redirected_publisher returns a success indication.
If the validation fails, appropriate errors are raised. sp_validate_redirected_publisher makes a best effort to
raise all issues and not just the first encountered.

NOTE
sp_validate_replica_hosts_as_publishers will fail with the following error when validating secondary replica hosts that do
not allow read access, or require read intent to be specified.
Msg 21899, Level 11, State 1, Procedure sp_hadr_verify_subscribers_at_publisher, Line 109
The query at the redirected publisher 'MyReplicaHostName' to determine whether there were sysserver entries for the
subscribers of the original publisher 'MyOriginalPublisher' failed with error '976', error message 'Error 976, Level 14, State 1,
Message: The target database, 'MyPublishedDB', is participating in an availability group and is currently not accessible for
queries. Either data movement is suspended or the availability replica is not enabled for read access. To allow read-only
access to this and other databases in the availability group, enable read access to one or more secondary availability replicas
in the group. For more information, see the ALTER AVAILABILITY GROUP statement in SQL Server Books Online.'.
One or more publisher validation errors were encountered for replica host 'MyReplicaHostName'.

Permissions
Caller must either be a member of the sysadmin fixed server role, the db_owner fixed database role for the
distribution database, or a member of a publication access list for a defined publication associated with the
publisher database.

See Also
Replication Stored Procedures (Transact-SQL)
sp_get_redirected_publisher (Transact-SQL)
sp_redirect_publisher (Transact-SQL)
sp_validate_redirected_publisher (Transact-SQL)
sp_validatemergepublication (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Performs a publication-wide validation for which all subscriptions (push, pull, and anonymous) will be validated
once. This stored procedure is executed at the Publisher on the publication database.
Transact-SQL Syntax Conventions

Syntax
sp_validatemergepublication [@publication=] 'publication'
, [ @level = ] level

Arguments
[@publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @level= ] level
Is the type of validation to perform. level is tinyint, with no default. Level can be one of these values.

LEVEL VALUE DESCRIPTION

1 Rowcount-only validation.

2 Rowcount and checksum validation. For Microsoft SQL Server


2005Subscribers, this is automatically set to 3.

3 This is the recommended value.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_validatemergepublication is used in merge replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_validatemergepublication.

See Also
System Stored Procedures (Transact-SQL)
Validate Replicated Data
sp_validatemergesubscription (Transact-SQL)
sp_validatemergesubscription (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Performs a validation for the specified subscription. This stored procedure is executed at the Publisher on the
publication database.
Transact-SQL Syntax Conventions

Syntax
sp_validatemergesubscription [@publication=] 'publication'
, [ @subscriber = ] 'subscriber'
, [ @subscriber_db = ] 'subscriber_db'
, [ @level = ] level

Arguments
[@publication=] 'publication'
Is the name of the publication. publication is sysname, with no default.
[ @subscriber= ] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with no default.
[ @subscriber_db= ] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with no default.
[ @level= ] level
Is the type of validation to perform. level is tinyint, with no default. Level can be one of these values.

LEVEL VALUE DESCRIPTION

1 Rowcount-only validation.

2 Rowcount and checksum validation.

3 Rowcount and binary checksum validation.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_validatemergesubscription is used in merge replication.

Permissions
Only members of the sysadmin fixed server role or the db_owner fixed database role can execute
sp_validatemergesubscription.

See Also
Replication Stored Procedures (Transact-SQL)
Validate Replicated Data
sp_validatemergepublication (Transact-SQL)
sp_vupgrade_mergeobjects (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Regenerates the article-specific triggers, stored procedures, and views that are used to track and apply data
changes for merge replication. Execute this procedure in the following situations:
If an object required by replication is accidentally dropped.
If you apply an update, such as a hotfix, that requires modification to one or more replication objects.
Execute the procedure on each node after applying the update.
Executing this stored procedure does not require reinitialization of subscriptions. This procedure is not
required if you install a service pack or upgrade to a new version of SQL Server.
Transact-SQL Syntax Conventions

Syntax
sp_vupgrade_mergeobjects [ [@login = ] 'login' ]
[ , [ @password = ] 'password' ]
[ , [ @security_mode = ] security_mode ]

Arguments
[ @login=] 'login'
Is the system administrator login to use when creating new system objects in the distribution database. login is
sysname, with a default of NULL. This parameter is not required if security_mode is set to 1, which is Windows
Authentication.
[ @password=] 'password'
Is the system administrator password to use when creating new system objects in the distribution database.
password is sysname, with a default of '' (empty string). This parameter is not required if security_mode is set to 1,
which is Windows Authentication.
[ @security_mode=] 'security_mode'
Is the login security mode to use when creating new system objects in the distribution database. security_mode is
bit with a default value of 1. If 0, SQL Server Authentication will be used. If 1, Windows Authentication will be used.
When possible, use Windows Authentication.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_vupgrade_mergeobjects is used only for merge replication.

Permissions
Requires membership in the sysadmin fixed server role.

See Also
Replication Stored Procedures (Transact-SQL)
Upgrade Replicated Databases
sp_vupgrade_replication (Transact-SQL)
11/21/2017 • 1 min to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (starting with 2008) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
Activated by setup when upgrading a replication server. Upgrades schema and system data as needed to support
replication at the current product level. Creates new replication system objects in system and user databases. This
stored procedure is executed at the machine where the replication upgrade is to occur.
Transact-SQL Syntax Conventions

Syntax
sp_vupgrade_replication [ [@login=] 'login' ]
[ , [ @password= ] 'password' ]
[ , [ @ver_old= ] 'old_version' ]
[ , [ @force_remove= ] 'force_removal' ]
[ , [ @security_mode= ] security_mode ]

Arguments
[ @login=] 'login'
Is the system administrator login to use when creating new system objects in the Distribution database. login is
sysname, with a default of NULL. This parameter is not required if security_mode is set to 1, which is Windows
Authentication.

NOTE
This parameter is ignored when you are upgrading to SQL Server 2005 and later versions.

[ @password=] 'password'
Is the system administrator password to use when creating new system objects in the Distribution database.
password is sysname, with a default of '' (empty string). This parameter is not required if security_mode is set to 1,
which is Windows Authentication.

NOTE
This parameter is ignored when you are upgrading to SQL SQL Server 2005 and later versions.

[ @ver_old=] 'old_version'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
This stored procedure is deprecated and will be removed in a future release of SQL Server.
[ @force_remove=] 'force_removal'
Identified for informational purposes only. Not supported. Future compatibility is not guaranteed.
[ @security_mode=] 'security_mode'
Is the login security mode to use when creating new system objects in the Distribution database. security_mode is
bit with a default value of 0. If 0, SQL Server Authentication will be used. If 1, Windows Authentication will be used.

NOTE
This parameter is ignored when you are upgrading to SQL Server 2005 and later versions.

Return Code Values


0 (success) or 1 (failure)

Remarks
sp_vupgrade_replication is used when upgrading all types of replication.

Permissions
Only members of the sysadmin fixed server role can execute sp_vupgrade_replication.

See Also
Replication Stored Procedures (Transact-SQL)
Validate Replicated Data

Potrebbero piacerti anche