根据参数

时间:2016-04-25 14:29:19

标签: tsql stored-procedures sql-server-2014

我现在正全面停电,希望有人可以帮助我。在我的应用程序中,用户可以通过单击按钮将数据从一个表复制到另一个表。来源表中的数据的检索方式不同,具体取决于用户点击复制按钮的页面。

我的表格

tabPlanning

+--------------+-------------+--------+--------+--------------+
|  PlanningId  |  RequestId  | Field1 | Field2 |    Field3    |
|--------------|-------------|--------|--------|--------------|
| Primary key  | Foreign key |        |        |              |
+--------------+-------------+--------+--------+--------------+
|      INT     |     INT     |  DATE  | BIGINT | NVARCHAR(20) |
+--------------+-------------+--------+--------+--------------+

tabPlanningCopy

+------------------+-------------+--------+--------+--------------+
|  PlanningCopyId  |  RequestId  | Field1 | Field2 |    Field3    |
|------------------|-------------|--------|--------|--------------|
|   Primary Key    | Foreign Key |        |        |              |
+------------------+-------------+--------+--------+--------------+
|        INT       |     INT     |  DATE  | BIGINT | NVARCHAR(20) |
+------------------+-------------+--------+--------+--------------+

我的存储过程

spCopyPlanning

spCopyPlanning根据参数将数据从tabPlanning复制到tabPlanningCopy

ALTER PROCEDURE dbo.spCopyPlanning
    @PlanningId INT = NULL
    @RequestId INT = NULL
AS
BEGIN
    IF @PlanningId IS NOT NULL
    BEGIN
        IF EXISTS (SELECT * FROM tabPlanning WHERE RequestId = @RequestId)
        BEGIN
            INSERT INTO tabPlanningCopy(RequestId, Field1, Field2, Field3)
            SELECT RequestId,
                Field1,
                Field2,
                Field3
            FROM tabPlanning
            WHERE PlanningId = @PlanningId
        END
    END
    ELSE
    BEGIN
        IF EXISTS (SELECT * FROM tabPlanning WHERE RequestId = @RequestId)
        BEGIN
            INSERT INTO tabPlanningCopy(RequestId, Field1, Field2, Field3)
            SELECT RequestId,
                Field1,
                Field2,
                Field3
            FROM tabPlanning
            WHERE RequestId = @RequestId
        END
    END
END

-- @PlanningId IS NOT NULL -> copy the row with PlanningId = @PlanningId

-- @PlanningId IS NULL -> copy the row with RequestId = @RequestId

现在正在编写程序。但是,我不认为这是获得我想要的最好的方法(我讨厌冗余!)。我非常确定可以通过扩展WHERE声明来实现,但我现在还没有任何线索如何解决这个问题。任何人都可以引导我找到摆脱冗余代码的解决方案吗?

1 个答案:

答案 0 :(得分:1)

它是多余的,因为除了WHhere子句之外的所有内容都是相同的,除非它评估参数是否为null。由于参数是或者不是null,因此在Where中指定两对条件是一件简单的事情。请尝试以下方法:

ALTER PROCEDURE dbo.spCopyPlanning
    @PlanningId INT = NULL
    @RequestId INT = NULL
AS
BEGIN
    IF EXISTS (SELECT * FROM tabPlanning WHERE RequestId = @RequestId)
    BEGIN
        INSERT INTO tabPlanningCopy(RequestId, Field1, Field2, Field3)
        SELECT RequestId,
            Field1,
            Field2,
            Field3
    FROM tabPlanning
    WHERE (@PlanningId is not null
            and PlanningId = @PlanningId)
        or (@PlanningId is null
            and RequestId = @RequestId)
    END
END