简体   繁体   English

在T-SQL中创建循环函数

[英]create a loop function in T-SQL

i have a table include three fields tblUser(ID, parentID,count). 我有一个表,其中包括三个字段tblUser(ID,parentID,count)。 parentID references tblUser(ID) parentID引用tblUser(ID)

I want create function with parameter is ID in table. 我想创建参数为表中ID的函数。 The function will select parentID and set count = count + 1 where ID = parentID . 该函数将选择parentID并设置count = count + 1 where ID = parentID

I want to use while loop or for() to repeat the action until ID == parentID 我想使用while loopfor()重复操作, until ID == parentID

Generally you want to avoid using loops in SQL. 通常,您要避免在SQL中使用循环。 It's better to deal with data as a set rather than a row at a time, as loops are far more resource intensive. 最好将数据作为一个集合而不是一次处理,因为循环会占用更多的资源。

Also, in the example you have given you haven't stated why you need to use a loop. 另外,在给出的示例中,您还没有说明为什么需要使用循环。 It seems in this case it would be easier to simply say 在这种情况下,简单地说

set Count = ParentID

Now that I have warned you off using a loop, here's a simple example of a while loop: 现在,我已经警告您不要使用循环,这是while循环的简单示例:

Declare @Count integer = 0
  ,@ParentID integer

Select @ParentID = ParentID From Table 
(your where clause goes here)

While @Count <= @ParentID
BEGIN

  (whatever you want to do in your loop)
  Set @Count = @Count + 1

END

As far as I understand your problem, couldn't you just do it in a single statement? 据我了解您的问题,您难道不能一言以蔽之吗?

update theTable
set count = count + 1
where ID = parentID

As Aidan said, generally you do NOT want to loop in SQL, nor do you generally need to. 正如Aidan所说,通常您不想在SQL中循环,也通常不需要

SQL is a declarative language, you tell it what you want and let the query engine decide how best to do it SQL是一种声明性语言,您可以说出所需的内容,然后让查询引擎决定如何做到最好

CREATE PROCEDURE IncrementCount @parentID int
AS
UPDATE theTable
SET count = count + 1
WHERE ID = parentID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM