Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 从合并查询返回一个输出结果_Sql_Sql Server 2008_Sql Server 2012 - Fatal编程技术网

Sql 从合并查询返回一个输出结果

Sql 从合并查询返回一个输出结果,sql,sql-server-2008,sql-server-2012,Sql,Sql Server 2008,Sql Server 2012,我有一个合并查询,如果没有找到记录,它会更新或插入。在我的结果中,当记录不存在并且被插入时,我遇到了一个问题。查询返回“Updated”(为空)和“Inserted”(具有正确的值) 在没有更新时,如何避免返回空的“更新”呢 ALTER PROCEDURE [dbo].[spInsOrUpdApplicant] -- Add the parameters for the stored procedure here @Name nvarchar(50), @Surname

我有一个合并查询,如果没有找到记录,它会更新或插入。在我的结果中,当记录不存在并且被插入时,我遇到了一个问题。查询返回“Updated”(为空)和“Inserted”(具有正确的值)

在没有更新时,如何避免返回空的“更新”呢

ALTER PROCEDURE [dbo].[spInsOrUpdApplicant]
    -- Add the parameters for the stored procedure here
    @Name nvarchar(50),
    @Surname nvarchar(50),
    @Position nvarchar(50),
    @NationalID int,
    @ApplicantID int

AS
BEGIN
    SET NOCOUNT ON;
-- Update the row if it exists.    
    UPDATE tbApplicant
    SET Name = @Name, Surname = @Surname, Position = @Position, NationalID = @NationalID

        OUTPUT INSERTED.ApplicantID AS 'Result'

    WHERE ApplicantID = @ApplicantID;

-- Insert the row if the UPDATE statement failed.   
    IF (@@ROWCOUNT = 0 )
    BEGIN
        INSERT INTO tbApplicant (Name, Surname, Position, NationalID)
        OUTPUT INSERTED.ApplicantID AS 'Result'
        VALUES (@Name, @Surname, @Position, @NationalID)
    END

END;

即使没有更新实际行,“output”似乎也总是激发。您可以在触发器中看到相同的行为。您可能需要考虑以下事项:

ALTER PROCEDURE [dbo].[spInsOrUpdApplicant]
    -- Add the parameters for the stored procedure here
    @Name nvarchar(50),
    @Surname nvarchar(50),
    @Position nvarchar(50),
    @NationalID int,
    @ApplicantID int

AS
BEGIN
    SET NOCOUNT ON;
-- Check if the row exists.    
    IF EXISTS (SELECT 1 FROM tbApplicant WHERE ApplicantID = @ApplicantID) BEGIN
-- update if the row exists.    
        UPDATE tbApplicant
        SET Name = @Name, Surname = @Surname, Position = @Position, NationalID = @NationalID
        OUTPUT INSERTED.ApplicantID AS 'Result'
        WHERE ApplicantID = @ApplicantID;
    END
    ELSE BEGIN
-- Else Insert.   
        INSERT INTO tbApplicant (Name, Surname, Position, NationalID)
        OUTPUT INSERTED.ApplicantID AS 'Result'
        VALUES (@Name, @Surname, @Position, @NationalID)
    END

END;

我做了一些非常相似的事情

在我的存储过程中,我有:

 DECLARE @mergeResults TABLE (mergeAction varchar(10), tableName varchar(50));
 OUTPUT $action, 'Table Name' INTO @mergeResults;
您是否可以在表变量中插入数据,然后根据所看到的内容决定如何移动数据

您提到您有一个合并查询,但您没有使用合并-您使用的更多的是“向上插入”

合并T-SQL: