在sql查询循环请帮忙 [英] loops in sql query please help

查看:75
本文介绍了在sql查询循环请帮忙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望根据条件在sql server中获取N条记录



我正在尝试根据条件维护记录跟踪。







我有一张存放一些信息的桌子..



以及当用户输入消息时存储FromId和ToId的更多表格并点击



发送按钮然后消息将存储在消息表中,FromId将其检索为已发送



消息ToId将其作为收件箱消息检索...



现在我的要求是在我的ID表中添加一个Reply列,用于存储以前的MessageId。



现在我需要根据以下内容检索整个会话链使用循环。





喜欢while(如果存在(从tbl_id选择回复)



{

做一些事情;

}



如果遇到null,循环应该会破坏

i want to get N number of records in sql server based on a condition

I'm trying to maintain a track of records based on a condition ..



I'm having a table which is storing some messages ..

and on more table which stores FromId and ToId when a user type message and Click on

Send Button then the message will be stored in message table, FromId Retrieves it as Sent

Message where as ToId Retrieves it as Inbox Message...

now my Requirement is to add a Reply column to my ID table which stores previous MessageId.

now i need to Retrieve the entire conversation based on the chain using a loop.


like while (if exists (select Reply from tbl_id )

{
do some thing;
}

if it encounters null the loop should break

推荐答案

虽然 SQL 问题中没有循环(例如,您可以在<$ c中使用它们) $ c> PL / SQL )您显然可以检索满足给定条件的一组记录,这就是 SQL 查询的目的。
While there aren't loops in a SQL quesry (you may use them, for instance, in PL/SQL) you may obviously retrieve a set of records satisfying a given condition, that is the very purpose of the SQL queries.


也许它会给你一个想法。也许我对我的假设完全错误.N行意味着我的东西(取决于SQL Server):



SELECT ..... LIMIT N



SELECT TOP N ....
Maybe it gives you an idea. Maybe I'm completely wrong with my assumption. N rows implies me something like (depending on what SQL Server):

SELECT ..... LIMIT N

SELECT TOP N ....


假设你想要检索特定消息之前所有消息的反向链接,假设reply_id可以为空,我的想法如下:



Let say you want to retrieve a backward chaining of all messages preceding a particular message, assuming the reply_id is nullable, my idea is as follows:

declare @id varchar(255)
set @id = "some message id"
While (@id is not null)
begin

   select @id = reply_id from tbl_id where message_id = @id
   if @id is not null /* do something. */
end


这篇关于在sql查询循环请帮忙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆