如何在SQL Server中创建数据集并处理每条记录?

时间:2018-09-20 16:44:27

标签: sql sql-server

我有下表:

CREATE TABLE [dbo].[proposalReviewAction]
(
    [proposalReviewActionID] [INT] IDENTITY(1,1) NOT NULL,
    [proposalPackageID] [INT] NULL,
    [approvalTypeID] [INT] NULL,
    [comments] [VARCHAR](2000) NULL,
    [reviewedByID] [INT] NULL,
    [reviewedDate] [DATETIME] NULL
) ON [PRIMARY]

我想返回每个具有approvalTypeID = 100的记录,并在另一个将数据从投标表移动到项目表的过程中使用proposalPackageID

我考虑使用WHILE循环,但是每个人似乎都喜欢处理数据集,但是我找不到在SQL / T-SQL中执行此操作的任何方法。

我找到了一个WHILE循环的示例,并对其进行了修改...

WHILE (SELECT[approvalTypeID] FROM [proposalReviewAction]) = 100
BEGIN  
    DECLARE @ppID AS INT ;

    SELECT [proposalPackageID] AS ppID, [approvalTypeID] AS atID 
    FROM [proposalReviewAction]

    IF (SELECT [approvalTypeID] AS atID FROM [proposalReviewAction]) = 100
        PRINT @ppID
    ELSE
        BREAK
END  

PRINT 'I got to the print statement'; 

...但是出现以下错误:

  

子查询返回了多个值。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。

然后,它打印“ PRINT”语句。

感谢您的帮助...

鲍勃

3 个答案:

答案 0 :(得分:4)

您可以直接将这些记录直接插入您的ProjectTable!喜欢:

INSERT INTO [ProjectTable] (...)
SELECT proposalPackageID 
FROM [proposalReviewAction]
WHERE approvalTypeID  = 100

如果出于其他原因仍然需要循环,则可以使用光标代替WHILE。使用光标可以帮助您按记录记录变量中的查询结果,并分别处理每个记录:

DECLARE @proposalPackageID INT

DECLARE product_cursor CURSOR FOR

    SELECT proposalPackageID 
    FROM dbo.proposalReviewAction 
    WHERE approvalTypeID = 100

OPEN product_cursor  
FETCH NEXT FROM product_cursor INTO @proposalPackageID
WHILE @@FETCH_STATUS = 0
BEGIN

  -- Insert directly into projectTable or call external process  
  INSERT INTO [projectTable] (proposalPackageID ...)
  SELECT @proposalPackageID


  FETCH NEXT FROM product_cursor INTO @proposalPackageID 
END  
CLOSE product_cursor  
DEALLOCATE product_cursor 

希望这会有所帮助

答案 1 :(得分:1)

给出此表:

   CREATE TABLE [dbo].[proposalReviewAction]
    (
        [proposalReviewActionID] [INT] IDENTITY(1,1) NOT NULL,
        [proposalPackageID] [INT] NULL,
        [approvalTypeID] [INT] NULL,
        [comments] [VARCHAR](2000) NULL,
        [reviewedByID] [INT] NULL,
        [reviewedDate] [DATETIME] NULL
    ) ON [PRIMARY]

您可以使用简单的SELECT语句选择approvalTypeID = 100中的所有记录

SELECT * FROM dbo.proposalReviewAction WHERE approvalTypeID = 100;

如果只需要proposalPackageID,则可以使用查询(QUERY)选择它

SELECT proposalPackageID FROM dbo.proposalReviewAction WHERE approvalTypeID = 100;

根据处理方式,您也可以直接从此处插入“项目表”

INSERT INTO [projectTable] (proposalPackageID ...)
SELECT proposalPackageID, ...
FROM dbo.proposalReviewAction WHERE approvalTypeID = 100;

答案 2 :(得分:0)

select column 
from table 
where columns_name 
  in ( select column from table where columns_name = 'value');

注意:如果我们使用子查询,并且在这种情况下返回一个值,则可以使用(=,!=,<>,<,> ....) 或多个值,在这种情况下,我们应该使用(in,any,all,some)