插入行之前的SQL查询检查条件

时间:2011-07-27 13:38:13

标签: sql sql-server tsql

我有一个名为dbo.Tbl_ActivityInformations的表,数据看起来像

Activityid  activitymaxcount   Activityusedcount
   1               10                 9
   2               10                 7
   3               15                15

另一个名为Tbl_AttendeeInformations的表格,数据看起来像

AttendedID    AssID     ActivityID
    13        123456      1,2
    14        123457      1,3

Tbl_AttendeeInformations表中,数据将作为页面中的新行插入,ActivityInformationsActivityusedcount列中的数据将加1,以显示相应的activityID

现在我想在使用AttendeeInformationsActivityusedcount < activitymaxcount ActivityID插入行之前进行检查。如果满足条件,则只允许插入,否则应该回滚。我有一个名为SplitString的函数可以在ActivityID中拆分Tbl_AttendeeInformations

这是SplitString

的代码
create  FUNCTION dbo.SplitString(@FormattedString varchar(8000),@Delimitter char(1))      
returns @retResults TABLE(Value varchar(8000),Rownumber int)      
as      
BEGIN      
        DECLARE        @SearchString as varchar(8000)      
        DECLARE        @AssignString as varchar(8000)      
        DECLARE @Index int                      
        DECLARE @Count int      

        set @SearchString = @FormattedString      
        set @AssignString= ''      
        set @Count = 0      

        while(len(@SearchString) > 0 )      
        begin                      
                SET @Index =   CHARINDEX(@Delimitter,@SearchString, 0)                      
                set @Count = @Count + 1      
                if  @Index = 0      
                begin      
                        INSERT INTO @retResults      
                                values( @SearchString,@Count)      
                        set @SearchString = ''      
                        continue      
                end                      
                set @AssignString = SUBSTRING(@SearchString,1, @Index - 1 )      
                INSERT INTO @retResults values      
                        (@AssignString,@Count)      

                SET @SearchString = (select SUBSTRING(@SearchString, @Index + 1, LEN(@SearchString) -  @Index ))      


        end      
        return      
END     

请帮忙。

1 个答案:

答案 0 :(得分:0)

伪代码显示一个想法:

INSERT INTO AttendeeInformations
SELECT act.*
FROM ActivityInformations act 
INNER JOIN AttendeeInformations at ON act.ActivityID = at.ActivityID
WHERE act.Activityusedcount < act.activitymaxcount