【问题标题】:Setting variable SQL Procedure设置变量 SQL 过程
【发布时间】:2014-10-05 03:01:03
【问题描述】:

我正在开发一个数据库,其中包含商店的客户、产品、时间表等。我正在处理的问题涉及创建一个程序,将“开/关”列更改为关闭(默认情况下产品可用(1),此程序将其变为 0)我已经编写了该程序:

create proc p_fudgemart_deactivate_product 
(
    @product_id int
)
as
begin
update fudgemart_products
set product_is_active = 0
where product_id = @product_id
end

但是当我们得到一个产品名称时,问题就出现了,并且需要编写一个选择语句来将该产品更改为不可用。我知道这需要使用变量,但我不知道如何将变量设置为该产品的产品 ID。我的想法是这样的:

Declare @prod_name_id int
    set @prod_name_id= (select product_id from fudgemart_products
    where product_name = 'Slot Screwdriver')
    execute p_fudgemart_deactivate_product product_id @prod_name_id

我可以像这样在我的变量声明中使用选择吗?

【问题讨论】:

  • product_name 是唯一的吗?如题,名称为“一字螺丝刀”的唱片会不会不止一张?

标签: sql-server tsql variables stored-procedures


【解决方案1】:

实际上你走在正确的轨道上。试试这样的:

declare @prod_name_id int

select @prod_name_id = product_id
from fudgemart_products
where product_name = 'Slot Screwdriver'

exec p_fudgemart_deactivate_product
    @product_id = @prod_name_id

【讨论】:

  • 非常感谢!!由于 product_name 为程序提供 product_id,我是否需要重复此操作才能对多个项目执行该程序?而不是能够添加一个OR?例如:'其中 product_name = '一字螺丝刀' OR product_name = '锤子''
  • @wmiller11293 在这种情况下你真的需要调用其他程序吗? UPDATE dbo.fudgemart_products SET product_is_active = 0 WHERE product_name IN ('slot screwdriver','hammer');
【解决方案2】:

如果您使用的是 SQL Server 2008 或更高版本,则可以在一个语句中声明和赋值:

DECLARE @prod_name_id int = ( SELECT    product_id
                              FROM      fudgemart_products
                              WHERE     product_name = 'Slot Screwdriver'
                            );
EXECUTE p_fudgemart_deactivate_product @product_id = @prod_name_id;

【讨论】:

    猜你喜欢
    • 2011-06-06
    • 2021-12-02
    • 2022-01-26
    • 1970-01-01
    • 2017-08-05
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    相关资源
    最近更新 更多