Sql 如何使用动态计数执行GO语句?
如何为GO语句设置动态计数 我得到以下错误: 发生致命的脚本错误。遇到了不正确的语法 一边走 当我尝试运行以下查询时:Sql 如何使用动态计数执行GO语句?,sql,sql-server,database,tsql,Sql,Sql Server,Database,Tsql,如何为GO语句设置动态计数 我得到以下错误: 发生致命的脚本错误。遇到了不正确的语法 一边走 当我尝试运行以下查询时: Declare @count int Select @count=COUNT(*) From Users Insert Into #DummyUsers Select * from Users where UserName = 'Sachin' GO @Count 但是,当我使用下面带有硬编码计数的查询时,同样可以正常工作 Declare @count int Se
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运行,批处理就会终止,并且您的变量不再存在 试试这个
DECLARE @cntr INT=1
WHILE @cntr <= @count
BEGIN
INSERT INTO #DummyUsers
SELECT *
FROM Users
WHERE UserName = 'Sachin'
SET @cntr+=1
END
您不能使用变量作为count参数,但在您的示例中(可能是人为设计的),您可以直接连接回用户: 其他选择: Dynaimc SQL通过连接字符串并通过SQLCMD.EXE或OSQL.EXE执行来构建SQL 使用带计数器的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
虽然我同意其他人的观点,即可能有更好的方法来实现您正在尝试做的事情,但如果存在一些我们没有看到的限制,您可以考虑使用
您创建的序列持续存在,可以根据需要重置,您可以通过调用函数的下一个值来增加该序列。如果您只想插入重复的行,可以使用CTE或数字表
-- 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;
动态sql将无法工作。Go不是sql server关键字。它是SSMS中的批处理终止符。如果你把GO放在动态sql中,它将不起作用……当然,除非你想构建一个长字符串而不是使用GO。我澄清了,你必须使用一个外部程序来执行包含GO的sql。
-- 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;