SQL Server:过程抛出批处理错误

时间:2019-01-04 21:55:30

标签: sql-server

如果单元格具有NULL值,则写一个条件程序,然后添加变量具有的所有值,但是如果它已经具有值,则保留其原始值/不覆盖它。

这是一个更新过程。

这是我的查询:

CREATE PROCEDURE dbo.[Learning]
    @StartDate NVARCHAR(20) = NULL,
    @EndDate   NVARCHAR(20) = NULL,
    @Data      NVARCHAR(20) = NULL
AS
BEGIN
    IF EXISTS (SELECT TOP(1) T1.CID  
               FROM temp.dbo.TABLE1 AS T1 
               WHERE StartDate = @StartDate)
    BEGIN
        UPDATE temp.dbo.TABLE1
        SET StartDate = ISNULL(@StartDate, StartDate),
            EndDate = ISNULL(@EndDate, EndDate),
            Data = ISNULL(@Data, Data)
        WHERE TABLE1.SSC = 'OP'
    END

表格

CREATE TABLE temp.dbo.Table1
(
     CID INT,
     PID INT,
     SSC VARCHAR(3),
     StartDate VARCHAR(20),
     EndDate VARCHAR(20), 
     Data VARCHAR(20)
)

INSERT INTO temp.dbo.Table1
VALUES
(1001,  1333,   'OP','20011505','19952012','OP2001156519952012'),
(1002,  1245,   'OR','20121005',NULL,'OR20121005'),
(1003,  1116,   'OP','20131215',NULL,'OP20131215'),
(1004,  1234,   'OP','20011505','19952012','OP2001156519952012')    

CREATE TABLE temp.dbo.Table2
(
     CID INT,
     PID INT,
     SSC VARCHAR(3),
     StartDate VARCHAR(20),
     EndDate VARCHAR(20), 
     Data VARCHAR(20)
)

INSERT INTO temp.dbo.Table2
VALUES
(1001,  1333,   'OP','20111015',NULL,'OP20111015'),
(1002,  1245,   'OR','20131005',NULL,'OR20131005'),
(1003,  1116,   'OP','20131415',NULL,'OP2013141520131516'),
(1004,  1235,   'OP','20121015',NULL,'OP20121015')

这是示例数据的屏幕快照,该数据具有空值,将使用此过程对其进行更新。表1和表2连接在一起,所以这两个表都在一起

enter image description here

2 个答案:

答案 0 :(得分:3)

您的ISNULL逻辑倒退。首先,如果@StartDate IS NULL,则EXISTS将返回FALSE,而UPDATE将不会运行,这是正确的。但是,后退部分位于UPDATE中。如果要在该行中StartDate = ISNULL(StartDate,@StartDate) IS NULL,请在此处使用 UPDATE temp.dbo.TABLE1 SET StartDate = ISNULL(StartDate,@StartDate) ,EndDate = ISNULL(EndDate,@EndDate) ,Data = ISNULL(Data,@Data) WHERE TABLE1.SSC = 'OP' 将其设置为变量。

其他列也需要更改。

{{1}}

答案 1 :(得分:2)

您将变量放在错误的位置。

CREATE PROCEDURE dbo.[Learning]

   @StartDate       nvarchar(20) = null,
   @EndDate         nvarchar(20) = null,
   @Data            nvarchar(20) = null

AS
BEGIN
IF EXISTS (SELECT TOP(1) T1.CID  FROM temp.dbo.TABLE1 AS T1 WHERE StartDate = @StartDate)
BEGIN
    UPDATE temp.dbo.TABLE1
    SET StartDate = ISNULL(StartDate,@StartDate)
        ,EndDate = ISNULL(EndDate,@EndDate)
        ,Data = ISNULL(Data,@Data)
    WHERE TABLE1.SSC = 'OP'