需要有关重写使用游标的查询的帮助
我有一个如下所示的查询:
DECLARE Match_Cursor CURSOR
FOR
SELECT ID,UserKey,TypeCode
FROM [DB1].Table1 as t1
OPEN Match_Cursor
FETCH NEXT FROM Match_cursor INTO @ID,@UserKey,@TypeCode;
WHILE (@@FETCH_STATUS <> -1)
BEGIN
INSERT INTO #TempTable
SELECT t2.Name, t2.Address, t2.Country, @UserKey, @TypeCode
FROM [DB1].[DBO].udf_TableFunction(@ID) as t2
where @typeCode = 142 AND t2.Country = 'US'
FETCH NEXT FROM Match_cursor INTO @ID,@UserKey,@TypeCode;
END
SELECT * FROM #TempTable
有没有人建议使用联接重写此查询?假设t1.ID
和t2.ID
之间存在外键关系。
I have a query that looks like this:
DECLARE Match_Cursor CURSOR
FOR
SELECT ID,UserKey,TypeCode
FROM [DB1].Table1 as t1
OPEN Match_Cursor
FETCH NEXT FROM Match_cursor INTO @ID,@UserKey,@TypeCode;
WHILE (@@FETCH_STATUS <> -1)
BEGIN
INSERT INTO #TempTable
SELECT t2.Name, t2.Address, t2.Country, @UserKey, @TypeCode
FROM [DB1].[DBO].udf_TableFunction(@ID) as t2
where @typeCode = 142 AND t2.Country = 'US'
FETCH NEXT FROM Match_cursor INTO @ID,@UserKey,@TypeCode;
END
SELECT * FROM #TempTable
Does anyone have suggestions for rewriting this using joins? Assume there is a foreign key relation ship between t1.ID
and t2.ID
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
cross apply
传递Table1.ID
到udf_TableFunction
。这是一个关于如何执行此操作的伪代码。
(我现在无法访问SSMS,所以无法测试它)
Use
cross apply
to passTable1.ID
toudf_TableFunction
.Here is a pseudo code on how you might go about to do so.
(I don't have access to SSMS right now so couldn't test it)