将 KILL 与声明的变量一起使用

2021-09-10 00:00:00 tsql sql-server

我正在尝试使用带有声明变量的 KILL 语句,但它给了我一个语法错误.无论如何不使用常量并以编程方式更改 SPID?

I'm trying to use a KILL statement with a declared variable but it's giving me a syntax error. Is there anyway to not use a constant and programatically change the SPID?

例如:

DECLARE @SPID smallint
SET @SPID = 100
Kill @SPID

顺便说一句,这只是一个例子.我需要使用游标在循环中运行 kill 以摆脱旧的持久用户连接.(别问了)

BTW this is just an example. I need to run the kill in a loop with a cursor to get rid of old persistant user connections. (Don't ask)

推荐答案

我认为您需要为此使用动态 SQL.在使用动态 SQL 执行任何操作之前,请阅读这个重要页面.

I think you're going to need dynamic SQL for this. Read this essential page before doing anything with dynamic SQL, please.

DECLARE @SPID smallint
DECLARE @SQL nvarchar(1000)

SET @SPID = 100

SET @SQL = 'KILL ' + CAST(@SPID as varchar(4))

EXEC (@SQL)

相关文章