使用null参数插入存储过程

时间:2013-09-30 11:04:44

标签: sql stored-procedures

我想创建一个带有null参数的insert存储过程,如果传递了该参数的值,那么它必须在数据库中插入或更新

我的存储过程是:

Create proc [dbo].[SP_InsertOrUpdateCourseDetails]
    @CourseID int,
    @Tab1Title nvarchar(250) = null,
    @Tab1Description nvarchar(max) = null,
    @Tab2Title nvarchar(250) = null,
    @Tab2Description nvarchar(max) = null,
    @Tab3Title nvarchar(250) = null,
    @Tab3Description nvarchar(max) = null,
    @Tab4Title nvarchar(250) = null,
    @Tab4Description nvarchar(max) = null,
    @Syllabus nvarchar(max) = null
As
Begin

    If NOT EXISTS (Select * from CourseDetail Where CourseID=@CourseID )
    Begin
        Insert into CourseDetail(CourseID, Tab1Title, Tab1Description, 
                                 Tab2Title, Tab2Description,
                                 Tab3Title, Tab3Description, Tab4Title, Tab4Description,
                                 Syllabus)
        values (@CourseID, @Tab1Title, @Tab1Description, @Tab2Title, @Tab2Description,
                @Tab3Title, @Tab3Description, @Tab4Title, @Tab4Description, @Syllabus)

        IF @@ERROR = 0 AND @@ROWCOUNT =1
        Begin
            Select top 1 CourseID from CourseDetail Order by CourseDetailID Desc
        End
        Else 
        Begin
             Select 0
        End
    End
 Else
 Begin
     Update CourseDetail 
     SET
        Tab1Title = @Tab1Title,
        Tab1Description = @Tab1Description,
        Tab2Title = @Tab2Title,
        Tab2Description = @Tab2Description,
        Tab3Title = @Tab3Title,
        Tab3Description = @Tab3Description,
        Tab4Title = @Tab4Title,
        Tab4Description = @Tab4Description,
        Syllabus = @Syllabus
     Where 
        CourseID = @CourseID

     IF @@ERROR = 0 AND @@ROWCOUNT =1
     Begin
         Select top 1 CourseID from CourseDetail Order by CourseDetailID Desc
     End
     Else 
     Begin
         Select 0
     End
   End
 End

1 个答案:

答案 0 :(得分:2)

您可以使用ISNULL函数传递SP的参数作为第一个参数,如果是插入或实际列值,则更新时使用默认值:

    Insert into CourseDetail(CourseID, Tab1Title, Tab1Description, 
                             Tab2Title, Tab2Description,
                             Tab3Title, Tab3Description, Tab4Title, Tab4Description,
                             Syllabus)
    values (@CourseID, ISNULL(@Tab1Title, 'default value'), ISNULL(@Tab1Description,'default value'), ...


 Update CourseDetail 
 SET
    Tab1Title = ISNULL(@Tab1Title, Tab1Title),
    Tab1Description = ISNULL(@Tab1Description, Tab1Description),
    ....
 Where 
    CourseID = @CourseID

但是在这种情况下,即使你需要

,你也无法明确地设置NULL值