我有一个简单的SQL Server表,用于与两个数字列的多对多关联
我们计划删除多对多,并在Account
指向PFM_USER
时创建一个外键,并根据需要复制Account
条记录(及其子代)。
在计划删除此表时,我编写了以下内容并在Squirrel中运行它,期望BREAK导致循环结束。目的只是为了确保我要开发的逻辑能够正确地运行。
DECLARE @LastUserId INT
DECLARE @CurrentUserId INT
DECLARE @CurrentAccountId INT
DECLARE @Counter int
SET @LastUserId = 0
SET @Counter = 0
DECLARE UsersAndAccounts CURSOR LOCAL FOR
SELECT * FROM PFM_USER_ACCOUNT ORDER BY ACCOUNT_ID asc, PFM_USER_ID asc
OPEN UsersAndAccounts
FETCH NEXT FROM UsersAndAccounts into @CurrentUserId, @CurrentAccountId
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Counter += 1
IF @Counter > 10
BREAK
PRINT N'Examining Count ' + CAST(@Counter AS varchar ) + ' for USER '
+ CAST(@CurrentUserId AS varchar ) + ' and Account '
+ CAST(@CurrentAccountId AS varchar )
-- A lot of logic, inserting new Accont records, copied from the existing one, goes here
-- Many intended details omitted.
FETCH NEXT FROM UsersAndAccounts into @CurrentUserId, @CurrentAccountId
END
CLOSE UsersAndAccounts
DEALLOCATE UsersAndAccounts
我期望输出像(...表示我没有捕获的数字 - 值无关紧要):
Examining Count 1 for USER ... and Account ...
Examining Count 2 for USER ... and Account ...
Examining Count 3 for USER ... and Account ...
Examining Count 4 for USER ... and Account ...
Examining Count 5 for USER ... and Account ...
Examining Count 6 for USER ... and Account ...
Examining Count 7 for USER ... and Account ...
Examining Count 8 for USER 82 and Account 620
Examining Count 9 for USER 85 and Account 629
Examining Count 10 for USER 85 and Account 631
相反,我得到的输出看起来好像有两个@Counter变量和一个内部循环,就好像它一样(因为我对Java更熟悉)
for( int count1 = 0; count1 < 10; count1++) {
for( int count2 = count1; count2 < 10; count2) {
System.out.println("Examining count " + count2 + " [plus other stuff]");
}
}
Squirrel控制台也报告警告我没有找到任何有用的信息。说明事情的输出的最后一点是:
Warning: Examining Count 8 for USER 82 and Account 620
SQLState: S0001
ErrorCode: 0Warning: Examining Count 9 for USER 85 and Account 629
SQLState: S0001
ErrorCode: 0Warning: Examining Count 10 for USER 85 and Account 631
SQLState: S0001
ErrorCode: 0
Warning: Examining Count 9 for USER 85 and Account 629
SQLState: S0001
ErrorCode: 0Warning: Examining Count 10 for USER 85 and Account 631
SQLState: S0001
ErrorCode: 0
Warning: Examining Count 10 for USER 85 and Account 631
SQLState: S0001
ErrorCode: 0
我尝试在循环内删除了测试/ BREAK并更改了WHILE以进行测试,结果相似。
选择前10名并完全忽略@Counter也是如此
请解释我做错了什么,或者我怎么误解了这里发生的事情
谢谢, 乔治麦金尼
答案 0 :(得分:1)
请尝试以下方法:
select
'Examining Count ' + ROW_NUMBER()
+ '; USER ' + CAST(@CurrentUserId AS varchar )
+ ' and Account ' + CAST(@CurrentAccountId AS varchar )
from PFM_USER_ACCOUNT
ORDER BY
ACCOUNT_ID asc
,PFM_USER_ID asc