Viz*_*hna 0 sql-server stored-procedures functions errors query-performance
我有这张表,有 3 条记录。3条记录是创建脚本。我需要执行创建脚本,如果发生208错误,那么我需要保留记录并将状态设置为1。然后在其他记录完成后再次执行它。如果没有错误或者有除 208 之外的任何其他错误,我需要从表中删除它。但是当我执行它时,它会无限循环。我该如何解决?
问题是第二个视图参考了第一个视图。所以我需要先创建第二个,然后创建第一个。这就是我创建这个 SP 的原因。任何其他想法也表示赞赏。我是编码新手,所以请原谅我犯的任何错误。
Create PROCEDURE [dbo].[UP_CREATE_SCRIPT]
AS
BEGIN
declare @qry1 nvarchar(max)
DECLARE @i INT =1
DECLARE @qry2 NVARCHAR(100)
IF EXISTS (select 1 from [SmartMigrateDB_New].dbo.temp3 where id>0 and type<>'sq')
BEGIN
truncate table error_log
while (select count(1) from [SmartMigrateDB_New].dbo.temp3 where status=1)>=0
BEGIN
WHILE @i <= (SELECT MAX(ID) FROM [SmartMigrateDB_New].dbo.temp3)
BEGIN
BEGIN TRY
set @qry1 = ( select code from [SmartMigrateDB_New].dbo.temp3 where id = @i )
print @qry1
EXEC sp_ExecuteSQL @qry1
update [SmartMigrateDB_New].dbo.temp3 set status=0 where id = @i
END TRY
BEGIN CATCH
if ERROR_NUMBER()=208
update [SmartMigrateDB_New].dbo.temp3 set status=1 where id = @i
if ERROR_NUMBER()<>208
update [SmartMigrateDB_New].dbo.temp3 set status=0 where id = @i
insert into error_log(name,error_no,msg)
SELECT
ERROR_PROCEDURE() as name,
ERROR_NUMBER() AS error_no,
ERROR_MESSAGE() AS msg
END CATCH
SET @qry2=(SELECT NAME FROM [SmartMigrateDB_New].dbo.temp3 where id = @i )
delete from [SmartMigrateDB_New].dbo.temp3 where id=@i and status=0
print @qry2 +' Created'
set @i = @i + 1
END
END
END
ELSE print 'no objects'
END
Run Code Online (Sandbox Code Playgroud)
当您循环使用非连续值的标识符时,您需要以不同的方式处理递增。这是一个简单的例子:
DECLARE
@t table (id int PRIMARY KEY);
INSERT
@t
(
id
)
SELECT
ABS(ao.object_id)
FROM sys.all_objects AS ao;
DECLARE
@min bigint,
@max bigint;
SELECT
@min = MIN(t.id),
@max = MAX(t.id)
FROM @t AS t;
WHILE @min < @max
BEGIN
RAISERROR('Current value: %I64d', 0, 1, @min) WITH NOWAIT;
SELECT TOP (1)
@min = t.id
FROM @t AS t
WHERE t.id > @min
ORDER BY t.id;
END;
Run Code Online (Sandbox Code Playgroud)
这将找到大于当前标识符的下一个标识符,而不会增加到它们之间不存在的值。
归档时间: |
|
查看次数: |
533 次 |
最近记录: |