将多个值插入表中而无需循环

时间:2018-10-24 19:56:55

标签: sql sql-server

目标:我正在尝试编写一个SQL脚本,该脚本将从一个表(.dbo.CardFormat)中查找CardFormatID,然后将这些CardFormatID与其他数据一起插入另一表(.dbo.CardFormat_CardFormatMetaData)

到目前为止,我已经尝试过:我编写了以下SQL脚本,该脚本成功完成了所述目标,但是要使用CURSOR循环。

问题:是否可以使用CURSOR循环来替代/更好地做到这一点?

USE [CardWizard]
GO

DECLARE @tblCursor CURSOR;
DECLARE @CFID INT;

BEGIN

  SET @tblCursor = CURSOR FOR
    SELECT CardFormatID FROM .dbo.CardFormat WHERE isDeleted = 'False'

  OPEN @tblCursor
  FETCH NEXT FROM @tblCursor
    INTO @CFID

  WHILE @@FETCH_STATUS = 0
  BEGIN

    INSERT INTO .dbo.CardFormat_CardFormatMetaData(CardFormatID, CardFormatMetaDataID, MetaDataValue, MinimumLength, MaximumLength)
      VALUES(@CFID, 114, 'True', 0, 5)

    FETCH NEXT FROM @tblCursor
      INTO @CFID

  END;

END;

使用MS SQL Server 2017 Express

Database Name: CardWizard

Table 1 (getting info from): CardWizard.dbo.CardFormat:
CardFormatID    CardFormatName    BIN       isDeleted
1               TestFormat1       123456    False
2               TestFormat2       234567    True
3               TestFormat3       345678    False

Table 2 (inputting info to): CardWizard.dbo.CardFormat_CardFormatMetaData:
CardFormatID    CardFormatMetaDataID    MetaDataValue    MinimumLength   MaximumLength
(no values yet) (no values yet)         (no values yet)  (no values yet) (no values yet)

预期结果:'TestFormat1'和'TestFormat3'(CardFormatID 1和3,因为它们的IsDeleted值为False)与CardFormatMetaDataID,MetaDataValue,MinimumLength和MaximumLength的附加值(这些附加值是静态的)一起添加到CardFormat_CardFormatMetaData表中:分别为114, 'True', 0, 5

CardWizard.dbo.CardFormat_CardFormatMetaData:
    CardFormatID    CardFormatMetaDataID    MetaDataValue    MinimumLength   MaximumLength
    1               114                     'True'           0                5
    3               114                     'True'           0                5

1 个答案:

答案 0 :(得分:6)

--You can just do a bulk INSERT with your SELECT statement, and use the static
--values for the other 4 columns
INSERT INTO .dbo.CardFormat_CardFormatMetaData
(CardFormatID, CardFormatMetaDataID, MetaDataValue, MinimumLength, MaximumLength)
SELECT CardFormatID, 114, 'True', 0, 5 
FROM .dbo.CardFormat 
WHERE isDeleted = 'False'