what is the proper way to write this sql for insert?

时间:2018-06-04 16:54:46

标签: sql sql-server tsql stored-procedures

I have an ADGroup table in my DB which has columns Id, Guid. The Guid column represents the Guid attribute of external Active Directory groups.

I have an ADGroupADGroup table in my DB which has columns ParentADGroupId, ChildADGroupId. These columns represent parent/child instances of the ADGroup.Id column in the ADGroup table.

I have a sproc which uses a Table-Valued Parameter. The TVP has columns ParentADGroupGuid and ChildADGroupGuid, both with a UNIQUEIDENTIFIER data type. These columns represent parent/child Group Guid relationships in AD.

I've inserted ADGroup data into my DB and now I need to insert ADGroupADGroup data with the sproc below. What would be the proper way to write the select statement for insert in the "/* select statement here */" section below?:

CREATE PROCEDURE InsertADGroupGroups

    -- Add the parameters for the stored procedure here
    @ADGroupADGroupParameter ADGroupADGroupParameter READONLY
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    INSERT INTO ADGroupADGroup
    (
        ParentADGroupId,
        ChildADGroupId
    )
    /* select statement here */

END

UPDATE

Here's some sample SQL that would get the proper ADGroup.Id to insert for the ParentADGroupGuid in the TVP:

-- get ADGroup.Id for the AD Group Guid in the tvp
SELECT adg.Id 
FROM ADGroup adg
JOIN ADGroupADGroupParameter tvp ON tvp.ParentADGroupGuid = adg.Guid

So now I need to figure out a streamlined way to update this query to also include the ADGroup.Id for the ChildADGroupGuid in the TVP

2 个答案:

答案 0 :(得分:0)

You can treat a table valued parameter just like a regular table so a basic select statement will work.

select ParentADGroupId,
    ChildADGroupId
from @ADGroupADGroupParameter

答案 1 :(得分:0)

我认为以下SQL可能会起到作用:

INSERT INTO ADGroupADGroup
(
    ParentADGroupId,
    ChildADGroupId
)
SELECT adg1.Id, adg2.Id
FROM ADGroup adg1
JOIN @ADGroupADGroupParameter tvp ON tvp.ParentADGroupGuid = adg1.Guid
JOIN ADGroup adg2 ON tvp.ChildADGroupGuid = adg2.Guid

立即测试......