如何在 SQL Server 中声明变量并在同一存储过程中使用它
我试图从一个表中的 BrandID 获取值并将其添加到另一个表中。但我无法让它发挥作用。有人知道如何正确做吗?
CREATE PROCEDURE AddBrand
AS
DECLARE
@BrandName nvarchar(50),
@CategoryID int,
@BrandID int
SELECT @BrandID = BrandID FROM tblBrand
WHERE BrandName = @BrandName
INSERT INTO tblBrandinCategory (CategoryID, BrandID)
VALUES (@CategoryID, @BrandID)
RETURN
Im trying to get the value from BrandID in one table and add it to another table. But I can't get it to work. Anybody know how to do it right?
CREATE PROCEDURE AddBrand
AS
DECLARE
@BrandName nvarchar(50),
@CategoryID int,
@BrandID int
SELECT @BrandID = BrandID FROM tblBrand
WHERE BrandName = @BrandName
INSERT INTO tblBrandinCategory (CategoryID, BrandID)
VALUES (@CategoryID, @BrandID)
RETURN
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我可以看到该 SP 存在以下问题,这些问题可能与您的问题相关,也可能无关:
SELECT@BrandName
之后有一个无关的)
code> (最后)@CategoryID
或@BrandName
设置为任何地方的任何内容(它们是局部变量,但您不为它们赋值)在评论中您说过,修复
)
后您会收到错误:这表明您尚未为 SP 声明任何参数,但您是使用参数来调用它的。根据您对
@CategoryID
的回复,我猜您希望它是一个参数而不是局部变量。试试这个:然后您可以这样称呼它:
或这样:
...假设品牌名称是“Gucci”,类别 ID 是 23。
I can see the following issues with that SP, which may or may not relate to your problem:
)
after@BrandName
in yourSELECT
(at the end)@CategoryID
or@BrandName
to anything anywhere (they're local variables, but you don't assign values to them)In a comment you've said that after fixing the
)
you get the error:That's telling you that you haven't declared any parameters for the SP, but you called it with parameters. Based on your reply about
@CategoryID
, I'm guessing you wanted it to be a parameter rather than a local variable. Try this:You would then call this like this:
or this:
...assuming the brand name was 'Gucci' and category ID was 23.
在 sql 2012(也许早在 2005 年)中,你应该这样做:
In sql 2012 (and maybe as far back as 2005), you should do this:
上述方法都不适合我,所以我按照我的方式发布
None of the above methods worked for me so i'm posting the way i did