SA0212 : The SETUSER is deprecated. It is recommended to use EXECUTE AS instead |
![]() |
The SETUSER statement in T-SQL code is problematic because it is primarily maintained for backward compatibility and might be removed in future SQL Server releases.

The SETUSER statement was traditionally used to impersonate another user within a SQL Server session. However, reliance on this statement can compromise the stability and future compatibility of applications, as it poses significant risks if it becomes unsupported in newer SQL Server versions.
For example:
1-- Example of deprecated usage 2SETUSER 'other_user'; 3-- Subsequent operations are executed as 'other_user' 4SELECT * FROM SensitiveTable;
Using SETUSER can lead to code that becomes outdated and potentially non-functional as SQL Server evolves. It also introduces security concerns since it allows session user context switching without adequate accountability.
-
The code may fail in future versions of SQL Server where SETUSER is no longer supported.
-
It can create security vulnerabilities by allowing unmonitored access to sensitive data using impersonation.

Replace the deprecated SETUSER statement with EXECUTE AS to ensure future compatibility and enhance security.
Follow these steps to address the issue:
-
Identify each instance of the SETUSER statement in your T-SQL code.
-
Replace the SETUSER ‘other_user’; statement with EXECUTE AS USER = ‘other_user’;.
-
Ensure that the user context is reverted using REVERT; after the necessary operations are completed to maintain security and data integrity.
For example:
1-- Corrected usage of EXECUTE AS 2EXECUTE AS USER = 'other_user'; 3SELECT * FROM SensitiveTable; 4REVERT;

The rule has a Batch scope and is applied only on the SQL script.

Rule has no parameters.

The rule does not need Analysis Context or SQL Connection.


Deprecated Features, Bugs


SQL
1SETUSER 'mary'; 2 3GRANT SELECT ON computer_types TO joe; 4 5SETUSER; |

Message | Line | Column | |
---|---|---|---|
1 | SA0212 : The SETUSER is deprecated. It is recommended to use EXECUTE AS instead. | 1 | 0 |
2 | SA0212 : The SETUSER is deprecated. It is recommended to use EXECUTE AS instead. | 5 | 0 |
