0

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

* 编辑,我最初发布了不正确的代码示例。我的道歉 *

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
4

3 回答 3

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;
于 2013-02-20T01:00:42.560 回答
0

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

于 2013-02-20T00:54:14.620 回答
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
于 2013-02-20T00:57:59.800 回答