如何使用 tsql 终止会话

Bur*_*Can 3 t-sql database sql-server casting

你好,我有演员问题。即使结果来自查询作为字符串我得到消息 102,级别 15,状态 1,第 21 行 '@session_id' 附近的语法不正确。然后我尝试使用 cast 方法,但没有奏效。

declare @counter        int;
declare @session_id     int;

set @counter=0;
select 
    @counter= count(*),
    @session_id=cast(req.session_id as int) from sys.dm_exec_requests req where req.command='DbccSpaceReclaim'group by req.session_id
if(@counter>0)
begin
kill  @session_id 
end
Run Code Online (Sandbox Code Playgroud)

Mez*_*Mez 5

尝试以下操作,我正在使用 sp_executesql。有关详细信息,请参阅http://technet.microsoft.com/en-us/library/ms188001.aspx

声明@counter int;
声明@session_id int;

设置@counter=0;
选择 
    @计数器=计数(*),
    @session_id=cast(req.session_id as int) from sys.dm_exec_requests req where req.command='DbccSpaceReclaim'group by req.session_id
如果(@计数器> 0)
开始

声明@sql nvarchar(1000)
选择@sql = 'kill' + cast(@session_id as varchar(50))
 exec sp_executesql @sql
结尾