【问题标题】:select statement inside sp containing value SQL server 2008包含值 SQL Server 2008 的 sp 内的 select 语句
【发布时间】:2013-12-23 12:11:05
【问题描述】:

我有一个简单的问题,我认为解决方案在我的眼皮底下,但仍然无法弄清楚。

我有一个存储过程,期望用户输入 2 次:

@userid int,
@subtotal int

我的存储过程还需要一个可以从以下查询中获取的表中的值:

SELECT discountid FROM historical WHERE userid = @userid

所以,我只需要将我从这个查询中获得的值(它是一个 int)保存到我将在整个存储过程中使用的变量中,这样我就可以调用它并在以后使用它。

问题是我不知道如何声明一个变量来保存此查询中的值以便以后使用。

我搜索并找到了类似的内容:

@userid int,
@subtotal int,
@discountid int = (SELECT discountid from historical where userid = @userid)

还有……

@userid int,
@subtotal int,
SELECT @discountid = discountid from historical
where userid = @userid;

...但它们似乎都不起作用。我目前正在使用 SQL Server 2008。希望有人可以帮助我一点,对不起我的英语,因为我不是母语人士,提前谢谢!

【问题讨论】:

    标签: sql-server variables select stored-procedures


    【解决方案1】:

    首先你必须DECLARE这个变量然后赋值给它。还要确保您的查询仅返回一行,否则一旦您无法将 N 行分配给一个 INT 变量,您就会收到错误消息。因此,为了防止这种情况,我在 select 语句中添加了 TOP 1

    CREATE PROCEDURE YOUR NAME
    @userid int,
    @subtotal int
    
    AS
    
    Declare @discountid int;
    SELECT TOP 1 @discountid = discountid from historicalwhere userid = @userid;
    .....
    

    【讨论】:

    • 是的!!!我相信这就是我一直在寻找的。我在 sp 的第一部分声明了我的变量,从而使用户插入他自己的这个变量的值,这是我不想要的。我必须在“AS”之后包含它,这是我的错误。让我重新检查一下是否一切正常,稍后我会回到这里。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 2013-06-14
    • 1970-01-01
    • 2010-11-10
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多