如何执行带动态计数的GO语句?

How to execute the GO statement with dynamic count?

如何为 GO 语句设置动态计数?

我收到以下错误:

A fatal scripting error occurred.Incorrect syntax was encountered while parsing Go.

当我尝试 运行 以下查询时:

Declare @count int
Select @count=COUNT(*) From Users 

Insert Into #DummyUsers 
Select * from Users where UserName = 'Sachin' 

GO @Count

但是当我使用以下带有硬编码计数的查询时,同样可以正常工作。

Declare @count int
Select @count=COUNT(*) From Users 

Insert Into #DummyUsers 
Select * from Users where UserName = 'Sachin' 

GO 5

如果您对此有任何想法,非常感谢您的建议。

你不能。一旦 SSMS 遇到 GO,批处理就会终止,您的变量将不再存在。

试试这个。

DECLARE @cntr INT=1

WHILE @cntr <= @count
  BEGIN
      INSERT INTO #DummyUsers
      SELECT *
      FROM   Users
      WHERE  UserName = 'Sachin'

      SET @cntr+=1
  END 

您不能为 GOcount 参数使用变量,但在您的示例中(这可能是人为设计的)您可以直接加入 Users :

Insert Into #DummyUsers 
Select U.* from Users U
INNER JOIN Users U2
    ON U.UserName = 'Sachin' 

其他选项:

  • Dynaimc SQL(通过连接字符串构建 SQL)并通过 SQLCMD.EXEOSQL.EXE
  • 执行
  • 使用带有计数器的WHILE循环

我会循环它

Declare @count int
Select @count=COUNT(*) From Users 

WHILE(@count > 0)
BEGIN
    Insert Into #DummyUsers 
    Select * 
    FROM Users 
    WHERE UserName = 'Sachin' 

    SET @count = @count - 1;
END

虽然我同意其他人的观点,即可能有更好的方法来实现您想要做的事情,但如果我们没有看到某些限制,您可以考虑使用 sequence

您创建的序列会保留并可以根据需要重置,您可以 "increment" 通过调用 NEXT VALUE FOR 函数

如果您只想插入重复的行,您可以使用 CTE 或数字 table。

-- Sample data.
declare @Users as Table ( UserId Int Identity, Name VarChar(16) );
insert into @Users ( Name ) values
  ( 'Bob' ), ( 'Carol' ), ( 'Ted' ), ( 'Alice' );
select * from @Users;

-- Load another table with repetitions of a single user.
declare @TempUsers as Table ( UserId Int, Name VarChar(16) );
declare @Repetitions as Int = ( select Count(*) from @Users );
with TempUsers as (
  select UserId, Name, 1 as Repetitions
    from @Users
    where Name = 'Ted'
  union all
  select UserId, Name, Repetitions + 1
    from TempUsers
    where Repetitions < @Repetitions
  )
insert into @TempUsers ( UserId, Name )
  select UserId, Name
    from TempUsers;
select * from @TempUsers;