SQL Server:如何在INSERT存储过程中动态设置FROM值

时间:2013-02-20 00:51:41

标签: sql sql-server tsql

我有一个插入存储过程,我想根据用户发送的参数值动态设置SELECT子句表。我将发布一个我认为应该是这样的示例:< / p>

*编辑,我最初发布了错误的代码示例。我道歉 *

CREATE PROC [spInsertLOG_ReqClone]
  (@NewReqID char(8),
   @ReqID char(8),
   @SiteCode char(3),
   @RequestorID char(6),
   @CloneFromPo bit) 

AS BEGIN
DECLARE @ReqCreatedDate datetime = GetDate() 
SET @NewReqID = dbo.fnLOG_ReqIDGenerator(@SiteCode) --Generates New ReqID

INSERT INTO LOG_ReqHeader (

        ReqID,
        ReqCreatedDate,
        RequestDate,
        RequiredByDate

        )
(SELECT
 @NewReqID,
 @ReqCreatedDate,
 @ReqCreatedDate,
 @RequiredByDate


FROM LOG_ReqHeader h
WHERE h.ReqID = @ReqID )


INSERT INTO LOG_ReqLineItems
 (ReqID,
  QtyOrdered,
  UI,
  PartNumber,
  Nomenclature )

If @CloneFromPO = 0  -- Use line items intially entered in ReqLineITems table
BEGIN
(SELECT 
 @NewReqID,
 l.QtyOrdered,
 l.UI,
 l.PartNumber,
 l.Nomenclature

FROM ReqLineItems l 
WHERE l.ReqID = @ReqID)

END

If @CloneFromPO = 1  -- Use line items after PO was issued from PO table

Begin
(SELECT 
 @NewReqID,
 l.Qty_Ord,
 l.UnitOfIssue,
 l.Part_Number,
 l.Item_Desc

FROM PO_LineItems l 
WHERE l.ReqID = @ReqID)

END
END

3 个答案:

答案 0 :(得分:3)

这是一种方法,但我怀疑动态SQL在计划质量和稳定性方面可能更好:

INSERT dbo.LOG_ReqHeader 
( 
    ReqID,
    ReqCreatedDate,
    RequestDate,
    other columns
)
SELECT
  @NewReqID,
  @ReqCreatedDate,
  CURRENT_TIMESTAMP,
  other columns
FROM
(
  SELECT col1, col2, col3
    FROM dbo.table1
    WHERE @CloneFromPo = 0
    AND ReqID = @ReqID
  UNION ALL
  SELECT col1, col2, col3
    FROM dbo.table2
    WHERE @CloneFromPo = 1
    AND ReqID = @ReqID
) AS x;

答案 1 :(得分:0)

您需要一种方法是使用dynamic SQL来执行此操作。在您匆忙使用动态SQL之前,我建议您阅读这篇文章:http://www.sommarskog.se/dynamic_sql.html

答案 2 :(得分:0)

由于重复,这不是一个非常漂亮的解决方案,但这可能是你想要的:

    CREATE PROC [spInsertLOG_ReqClone]

(@NewReqID char(8),
@ReqID char(8),
@SiteCode char(3),
@RequestorID char(6),
@CloneFromPo bit) 

IF @CloneFromPo = 0 

BEGIN
    INSERT INTO LOG_ReqHeader ( 
            ReqID,
            ReqCreatedDate,
            RequestDate, SOME_OTHER_FIELDS)
    (SELECT
     @NewReqID,
     @ReqCreatedDate,
     @ReqCreatedDate, SOME_OTHER_FIELDS
        FROM Table_1
        WHERE reqID = @ReqID)

END

IF @CloneFromPo = 1

BEGIN
    INSERT INTO LOG_ReqHeader ( 
            ReqID,
            ReqCreatedDate,
            RequestDate, SOME_OTHER_FIELDS)
    (SELECT
     @NewReqID,
     @ReqCreatedDate,
     @ReqCreatedDate, SOME_OTHER_FIELDS
        FROM Table_1
        WHERE reqID = @ReqID)

END