如果存在超过指定次数,则数据库中的SQL Update值

时间:2016-02-09 20:07:09

标签: sql-server

我正在处理下面的存储过程,但遇到问题。我的问题是,如果[breed]列在表中具有的值多于基于变量指定的值,我需要使用表中列出的同一个表中的另一个品种值更新表<指定的次数。例如,' pitbull'在桌子上6次和#boxer'在表中4次。它们都需要在数据库中列出5次,每次都是根据' BreedListed'的指定值。那是= 5.我试图写一个更新查询来更新[品种]值,所以[品种]将被列出5次。感谢您的投入。

create table #TempCanine (AppID INT, Breed varchar(8), age INT) 

--insert statments not included in stored procedure. They are oncase anyone wanted to recreate the sample data.
insert into #TempCanine values(101, 'Pitbull', 2)
insert into #TempCanine values(102, 'Boxer', 4)
insert into #TempCanine values(103, 'Pitbull', 1)
insert into #TempCanine values(104, 'Pitbull', 5)
insert into #TempCanine values(105, 'Boxer', 2)
insert into #TempCanine values(106, 'Pitbull', 2)
insert into #TempCanine values(107, 'Boxer', 8)
insert into #TempCanine values(108, 'Pitbull', 1)
insert into #TempCanine values(109, 'Pitbull', 3)
insert into #TempCanine values(110, 'Boxer', 8)


DECLARE @Counter INT
DECLARE @BreedListed int
DECLARE @GetBreed varchar(50)
SET @BreedListed = 5
SET @Counter = 1


WHILE @COUNTER <= (SELECT COUNT(*) FROM #TempCanine) BEGIN
   SELECT @GetBreed = breed
   FROM #TempCanine
   WHERE ID = @Counter AND COUNT(breed) > @BreedListed

--LOST
  IF @GetBreed <> NULL
  BEGIN
        UPDATE #TempCanine
        SET T.breed = (SELECT breed
        FROM #TempCanine T INNER JOIN #TempCanine C
    ---LOST HERE
    END


    SET @Counter = @Counter + 1
  END

1 个答案:

答案 0 :(得分:1)

这永远不会返回true:

IF @GetBreed <> NULL

写这个的正确方法是

IF @GetBreed IS NOT NULL