SQL 2008 存储过程中的可选 where 子句/参数?

发布于 2024-08-11 04:16:18 字数 264 浏览 2 评论 0原文

我正在编写一些更新表的代码。根据用户想要执行的操作,它会更新一大组记录或较小的记录。描述因素是组ID。

用户可以选择是更新表中的所有记录,还是仅更新具有该 groupID 的记录。我想对两个实例使用相同的存储过程,其中可能有一些逻辑来区分场景。 (我不想编写两个具有 90% 相同代码的存储过程。)

我不是存储过程方面的专家,并且不确定是否可以传入可选参数,或者如何动态生成 where 子句的一部分,具体取决于关于 groupID 是否存在。欢迎任何建议。

谢谢!

I'm writing some code that updates a table. Depending on what the user wants to do, it either updates a large set of records, or a smaller one. The delineating factor is a group ID.

The user can choose whether to update the table for all records, or just those with that groupID. I'd like to use the same stored procedure for both instances, with maybe a little logic in there to differentiate between the scenarios. (I'd prefer not to write two stored procs with 90% identical code.)

I'm no expert at stored procedures and am not sure if I can pass in optional parameters, or how to dynamically generate part of a where clause, depending on whether the groupID is there or not. Any suggestions are welcome.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黎歌 2024-08-18 04:16:18

您可以使用此结构或“OR”结构

... WHERE GroupID = ISNULL(@GroupdID, GroupID)


... WHERE GroupID = @GroupdID OR @GroupdID IS NULL

You can use this or an "OR" contsruct

... WHERE GroupID = ISNULL(@GroupdID, GroupID)


... WHERE GroupID = @GroupdID OR @GroupdID IS NULL
机场等船 2024-08-18 04:16:18
create procedure MyProc (@GroupID int = null)
as
begin
    update MyTable set ....
    where @GroupID is null or GroupID = @GroupID
end
create procedure MyProc (@GroupID int = null)
as
begin
    update MyTable set ....
    where @GroupID is null or GroupID = @GroupID
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文