Sql query checking condition before insert row
I have a table called dbo.Tbl_ActivityInformations
and the data look like
Activityid activitymaxcount Activityusedcount
1 10 9
2 10 7
3 15 15
And another table called Tbl_AttendeeInformations
and the data look like
AttendedID AssID ActivityID
13 123456 1,2
14 123457 1,3
In the Tbl_AttendeeInformations
table data will be inserted as new row from page and in the ActivityInformations
table Activityusedcount
column incremented by one for appropriate activityID
.
Now I want to check before inserting a row into AttendeeInformations
that Activityusedcount < activitymaxcount
using ActivityID
. If the condition is satisfied then only it will allow to insert otherwise it should rollback. I have function named SplitString
to split ActivityID
in Tb开发者_如何学编程l_AttendeeInformations
.
This is the code for 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
Please do help.
Pseudocode to show an idea:
INSERT INTO AttendeeInformations
SELECT act.*
FROM ActivityInformations act
INNER JOIN AttendeeInformations at ON act.ActivityID = at.ActivityID
WHERE act.Activityusedcount < act.activitymaxcount
精彩评论