如何在 SQL 服务器中为声明的变量设置值

How to set value to declared variable in SQL Server

如何在 SQL 服务器中为声明的变量设置值。

DECLARE  @V_SEQUENCE INT,  @V_SEQUENCENAME NVARCHAR(MAX);
SET @V_SEQUENCENAME = 'dbo.MYSEQ';   
EXEC('SELECT @V_SEQUENCE = NEXT VALUE FOR  ' + @V_SEQUENCENAME)
SELECT @V_SEQUENCE

这里出现错误:

Must declare the scalar variable "@V_SEQUENCE"'

请告诉我如何获得 @V_SEQUENCE 的结果。

您想从执行中传递一个值。我建议您使用 sp_executesql:

DECLARE  @V_SEQUENCE INT, @V_SEQUENCENAME NVARCHAR(MAX), @SQL NVARCHAR(MAX);
SET @V_SEQUENCENAME = 'dbo.MYSEQ'; 
SELECT @SQL = 'SELECT @V_SEQUENCE = NEXT VALUE FOR  ' + @V_SEQUENCENAME;

EXEC sp_executesql @SQL, N'@V_SEQUENCE INT OUTPUT', @V_SEQUENCE = @V_SEQUENCE OUTPUT;

SELECT @V_SEQUENCE;