我有这个商店程序,我假设用户想要更新一些字段而不是全部,我应该在更新部分添加什么
CREATE PROCEDURE [dbo].[helpChainAllCRUD]
@action char(1),
@lineId char(2),
@lineShift smallint = NULL,
@sequence smallint = NULL,
@Role VARCHAR(32) = NULL,
@radioChannel VARCHAR(16)= NULL,
@officePhone VARCHAR(16)= NULL,
@cellPhone VARCHAR(16)= NULL
as
IF(@action = 'I')
BEGIN TRY
BEGIN TRAN
INSERT INTO [dbo].[tbl_helpChain] (lineId,lineShift,sequence,Role,radioChannel,officePhone,cellPhone)
VALUES (@lineId ,@lineShift,@sequence,@Role,@radioChannel,@officePhone,@cellPhone)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT >0
ROLLBACK
END CATCH
IF(@action = 'U')
BEGIN TRY
BEGIN TRAN
UPDATE [dbo].[tbl_helpChain] SET lineShift=@lineShift,sequence=@sequence,Role=@Role,radioChannel=@radioChannel,officePhone=@officePhone,cellPhone=@cellPhone WHERE lineId=@lineId
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT >0
ROLLBACK
END CATCH
IF(@action = 'D')
BEGIN TRY
BEGIN TRAN
Delete from [dbo].[tbl_helpChain] WHERE lineId=@lineId
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT >0
ROLLBACK
END CATCH
IF(@action = 'S')
Begin
select lineId,lineShift,sequence,Role,radioChannel,officePhone,cellPhone from [dbo].[tbl_helpChain]
end
GO
答案 0 :(得分:1)
如果ie null表示不更新,则只需编写
即可SET lineShift = COALESCE(@lineShift,lineShift), ...
或者您采用另一个特殊值和案例表达
SET lineShift = CASE WHEN @lineShift = -1 then lineShift else @lineShift end,
或者为每个列提供额外的布尔参数,以便在case-expression
中使用答案 1 :(得分:1)
我确信有更好的解决方案,但快速简便的解决方案可能是使用非常丑陋的动态SQL
DECLARE @QueryText nvarchar(max) = 'UPDATE [dbo].[tbl_helpChain] SET '
IF @radioChannel<> NULL
@QueryText = @QueryText + 'RadioChannel=@radioChannel'
EXECUTE SP_EXECUTESQL @QueryText
答案 2 :(得分:0)
更新helpChain
SET
fullName = ISNULL(@ fullName,fullName),
lineShift = ISNULL(@ lineShift,lineShift),
sequence = ISNULL(@ sequence,sequence),
Role = ISNULL(@ Role,Role),
radioChannel = ISNULL(@ radioChannel,radioChannel),
officePhone = ISNULL(@ officePhone,officePhone),
cellPhone = ISNULL(@ cellPhone,cellPhone) WHERE lineId = @lineId