我在下面有这个存储过程。我可以在MSDN等中找到的IF / ELSE示例在“SET”参数上没有IF / ELSE功能。
BEGIN
UPDATE c_section_status
-- put in if else statement here to update page has changed or not.
SET status_ID = @status_id,
status_date = GETDATE(),
page_has_not_changed = @page_has_not_changed
/*------------------------------------------------------------------*/
-- log data to history table
OUTPUT INSERTED.cppsa_ID,INSERTED.menuitem_ID
,INSERTED.status_ID,
INSERTED.page_has_not_changed,
INSERTED.status_date
,@user,GETDATE(),0
INTO c_section_status_HIST
/*------------------------------------------------------------------*/
WHERE cppsa_id = @cppsa_id
and menuitem_id = @menuitem_id
END
所以我只想在页面发生变化时设置status_date = GETDATE()
。如果@page_has_not_changed
等于1
那么我想保留旧的status_date
而不是更新它。
这可能吗?
答案 0 :(得分:1)
当我尝试更新变量时,我经常在存储过程中执行类似的操作。
if (@page_has_not_changed= 0 )
Begin
--Do Something
End
if (@page_has_not_changed = 1)
Begin
--Do Something Else
End
答案 1 :(得分:1)
您应该使用CASE声明
BEGIN
UPDATE c_section_status
-- put in if else statement here to update page has changed or not.
SET status_ID = @status_id,
status_date = CASE WHEN @page_has_not_changed=1 THEN status_date ELSE GETDATE() END,
page_has_not_changed = @page_has_not_changed
/*------------------------------------------------------------------*/
-- log data to history table
OUTPUT INSERTED.cppsa_ID,INSERTED.menuitem_ID
,INSERTED.status_ID,
INSERTED.page_has_not_changed,
INSERTED.status_date
,@user,GETDATE(),0
INTO c_section_status_HIST
/*------------------------------------------------------------------*/
WHERE cppsa_id = @cppsa_id
and menuitem_id = @menuitem_id
END
请注意,CASE语句有两种形式:
--Simple CASE expression:
CASE input_expression
WHEN when_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
--Searched CASE expression:
CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
答案 2 :(得分:1)
只需在UPDATE语句工作之前添加IF条件:
IF @page_has_not_changed = 0
BEGIN
UPDATE c_section_status
SET status_ID = @status_id,
status_date = GETDATE(),
page_has_not_changed = @page_has_not_changed
/*------------------------------------------------------------------*/
-- log data to history table
OUTPUT INSERTED.cppsa_ID,INSERTED.menuitem_ID
,INSERTED.status_ID,
INSERTED.page_has_not_changed,
INSERTED.status_date
,@user,GETDATE(),0
INTO c_section_status_HIST
/*------------------------------------------------------------------*/
WHERE cppsa_id = @cppsa_id
and menuitem_id = @menuitem_id
END