SQL Server - 如何在 2 个可能的 SELECT 语句之间切换

发布于 2024-08-30 01:25:40 字数 566 浏览 5 评论 0原文

我想在我的 mssql 存储过程中使用一个参数来在小结果和详细结果之间切换(出于可维护性、性能和网络负载的原因)。

如果参数设置为 1,我将获取所有列,否则仅获取一两个最重要的列。 它的工作方式非常有限,如下所示:

ALTER PROCEDURE [dbo].[GetAllUsers]
 @detail BIT
AS
 IF @detail = 1 SELECT UserName, Title, UserID FROM Users
 ELSE SELECT Username FROM Users

但我想使用组合的 WHEN 子句。 以下是我尝试过的,但这不起作用。

ALTER PROCEDURE [dbo].[GetAllUsers]
 @detail BIT
AS
 CASE @detail
    WHEN 1 THEN SELECT UserName, Title, UserID
    ELSE SELECT UserName END
    FROM Users
    WHERE UserID < 5

有什么办法可以实现这样的目标吗?

I would like to use a parameter in my mssql stored procedures to switch between a small and a detailed result (for maintainability, performance and network load reasons).

If parameter is set to 1 i get all columns, else only the one or two most important.
In a very limited way it works like this:

ALTER PROCEDURE [dbo].[GetAllUsers]
 @detail BIT
AS
 IF @detail = 1 SELECT UserName, Title, UserID FROM Users
 ELSE SELECT Username FROM Users

But I want to use a combined WHEN clause.
The following is what i tried, but this doesnt work.

ALTER PROCEDURE [dbo].[GetAllUsers]
 @detail BIT
AS
 CASE @detail
    WHEN 1 THEN SELECT UserName, Title, UserID
    ELSE SELECT UserName END
    FROM Users
    WHERE UserID < 5

Is there any way to achieve somehting like that?

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

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

发布评论

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

评论(3

2024-09-06 01:25:40

我认为让存储过程根据输入变量返回不同的记录类型是糟糕的 API 设计。我认为您应该创建两个存储过程,GetAllUsersGetAllUsersWithDetails

I think it is terrible API design to have a stored procedure return different record types based on an input variable. I think you should create two stored procedure, GetAllUsers and GetAllUsersWithDetails.

百变从容 2024-09-06 01:25:40

就我个人而言,我会使用两个不同的存储过程。没有理由仅仅为了强制事物适合一个存储过程而创建复杂的实现。

Personally, I would use two different stored procedures. There is no reason to create a complex implementation simply to force things to fit inside one stored procedure.

自由如风 2024-09-06 01:25:40

虽然我同意klausbyskov两个程序是更好的设计,无论如何我都会尝试回答你的问题 - 恐怕简短的答案是

确实可以根据变量的值执行两个不同的选择语句(这是您在第一个代码示例中所拥有的),但不可能更改投影< /em> 以这种方式在单个选择语句中。

While I agree witht klausbyskov that two procedures are a better design, I will try to answer your question anyway - and I am afraid that the short answer is no.

It is indeed possible to execute two different select statements (which is what you have in your first code sample) depending on the value of a variable, but it is not possible to alter the projection inside a single select statement this way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文