2013-04-29 131 views
0

我正在使用sql server数据库。我有我的分贝与1 to many协会的2个表。首先是父母表和第二个是表。 表有一列ChildCount无论何时添加或删除此父项的子项,它都将进行更新。如何编写简单的sql程序?

因此,为此我决定编写一个存储过程和一个DML触发器,它将对子表上的INSERT和DELETE操作执行。我是全新的数据库。我试过没为:

首先,我想创建一个程序(我将在触发执行)

CREATE PROCEDURE [dbo].[ChildCount] 
    @parentId int 
AS 
    //here first i have to extract the total child for the given parentId and 
    //than in the next update statement i will update the count. 

    UPDATE Parent 
    SET ChildCount = //above total child value 
    WHERE Id = parentId 
RETURN 0 

在这里,我不知道如何提取总孩子和保存它在一个变量中,而不是在更新语句中使用该变量?

请指导我在这个CREATE PROCEDURE后,建议我在做什么这是正确的,好的和有效的方法或有其他更好的方法来做到这一点?

+1

嘿,为什么要投票?我告诉我,我是全新的数据库 – user1740381 2013-04-29 03:38:59

+0

你打算从触发器以外的地方执行这段代码吗?如果没有,你可能只需将代码放入触发器即可。 – DeanOC 2013-04-29 03:43:04

+0

没有列是“ChildCount”,总共有孩子我的意思是说单个父项目的所有孩子 – user1740381 2013-04-29 03:46:40

回答

3

尝试这样

CREATE PROCEDURE [dbo].[ChildCount] 
     @parentId int 
    AS 

    Begin 
    Declare @i as int; 

    Select @i=count(child) from childtable where [email protected] 

     UPDATE Parent 
     SET ChildCount [email protected] 
     WHERE Id = @parentId 
    End 
+0

谢谢你的回答,你能告诉我是我的做法是有效的,或者我可以用其他更好的方法做到这一点? – user1740381 2013-04-29 03:49:19

+1

更好的方法来编写触发器...用于在子表中插入和删除相应的父ID ...它将自动递增或递减在父表中插入或删除不在子表中时的子表的计数... .. – 2013-04-29 03:51:27

0

如果你想用一个触发器来做到这一点可能是这样的:

create trigger dbo.tr_Child on dbo.Child for insert, update, delete 
as 

update dbo.Parent 
set ChildCount = (select count(*) from dbo.Child where Child.ParentID = T.ParentID) 
from 
    (
    select ParentID from inserted union 
    select ParentID from deleted 
) as T 
where Parent.ParentID = T.ParentID; 

SQL Fiddle

0

您也可以考虑使用计算列,而不是的触发器。只需创建一个UDF,它将返回给定父级的子级数并从中创建一个计算列。

下面是它可能看起来像

CREATE FUNCTION dbo.GetChildCount(@ParentID int) 
RETURNS int 
BEGIN 
    RETURN (SELECT COUNT(*) FROM Child WHERE ParentID = @ParentID) 
END 


ALTER TABLE Parent 
    ChildCount as dbo.GetChildCount(ParentID) 

Here是更多详细信息的链接。