尝试创建将构建多个条目的存储过程

时间:2016-11-16 18:00:34

标签: sql sql-server stored-procedures

我们使用的产品实质上是通过SQL表为对象设置权限。我试图创建一个存储过程,实质上将一个用户的权限设置为另一个用户。这是我到目前为止所做的:

CREATE PROCEDURE SETPRODUCTS
    @sourceCC BIGINT,
    @targetCC BIGINT
BEGIN
    DECLARE @SQL varchar(5000)

    DECLARE @Sequence_Id varchar(50)
    SET @sequence_id = 0

    BEGIN TRANSACTION

    DELETE FROM TCC WHERE CC_Id = @targetCC

    DECLARE cursorCurrent CURSOR FOR
        SELECT MAX(TCC_Id) + 1 
        FROM TCC WITH (tablockx holdlock)

    OPEN cursorCurrent
    FETCH NEXT FROM cursorCurrent INTO @sequence_id

    IF (@sequence_id IS NULL) 
       SET @sequence_id = 1

    INSERT INTO TCC (TCC_Id, T_Id, CCC_Id) 
    VALUES (@sequence_id,
        (SELECT T_Id FROM TCC WHERE CC_Id = @sourceCC), @targetCC)

    CLOSE cursorCurrent
    DEALLOCATE cursorCurrent

    COMMIT TRANSACTION
END

我得到的错误是我的子查询有多个值,这是真的。我想从该子查询中获取每个条目,并使用它将新行插入到我的数据库中。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

试试此版本的插入内容:

INSERT INTO TCC (TCC_Id, T_Id, CCC_Id)
   SELECT @sequence_id, @targetCC, T_Id FROM TCC WHERE CC_Id = @sourceCC

答案 1 :(得分:0)

改变您的程序如下

Alter PROCEDURE SETPRODUCTS
@sourceCC BIGINT,
@targetCC BIGINT
 BEGIN
 DECLARE @SQL varchar(5000)

DECLARE @Sequence_Id varchar(50)
SET @sequence_id = 0

BEGIN TRANSACTION

DELETE FROM TCC WHERE CC_Id = @targetCC

DECLARE cursorCurrent CURSOR FOR
    SELECT MAX(TCC_Id) + 1 
    FROM TCC WITH (tablockx holdlock)

OPEN cursorCurrent
FETCH NEXT FROM cursorCurrent INTO @sequence_id
Declare @total int
IF (@sequence_id IS NULL) 
   SET @sequence_id = 1

     SELECT T_Id,ROW_NUMBER() over (order by TCC_id) as rowno into #temp   
     FROM TCC WHERE CC_Id = @sourceCC
   select @total=COUNT(*) from #temp
   while(@rowno <> @total)
   begin
       Declare @t_id int
       set @t_id=(select top 1 T_id from #temp where rowno=@rowno)

       INSERT INTO TCC (TCC_Id, T_Id, CCC_Id) 
        VALUES (@sequence_id,@t_id,@targetCC)

       set @rowno=@rowno+1
   End
DROP TABLE #temp
CLOSE cursorCurrent
   DEALLOCATE cursorCurrent
   COMMIT TRANSACTION
  END