我想知道如何基于是否存在客户ID来执行存储过程,并为指定客户创建客户订单。否则,创建一个具有指定ID的新客户。
我这里有一些代码,但是出现错误,它说“过程或函数'CustOrder1'期望提供参数'@ custid1',但未提供”。 任何帮助都会很好,谢谢。
declare @custid1 char (6), @CustName1 nvarchar(255)
set @custid1 = 001
set @custName1 = 'Pete'
select @custid1 = 'c102', @custName1 = 'Pete'
update CustomerRecord
set CustomerID = @custid1
where CustName = @CustName1
select * from CustomerRecord where CustomerID = @custid1
if @@ROWCOUNT = 0
print 'The id ' + cast(@custid1 as varchar(5)) + ' does not exists'
else
print 'Update successsful'
go
alter procedure CustOrder1
@custid1 CHAR (6), @custName1 VARCHAR (40), @SalesOrderID CHAR (10)
as
begin
if not exists (select * from CustomerRecord
where CustName = @CustName1)
begin
insert into CustomerRecord (CustomerID)
values (@custid1)
end
end
go
exec CustOrder1
答案 0 :(得分:1)
您已使用3个参数定义了过程CustOrder1。
当您尝试在不传递任何参数的情况下执行此过程时,会出现错误。
此外,此过程中未使用参数@SalesOrderID,因此可以将其删除(除非您只发布了一部分)。
它也不会将@ custName1插入到CustomerRecord表中,因此,每次运行此过程时,它将尝试为该@ custid1创建新记录。
要大致回答您的问题,您的路线正确。您将需要类似(伪代码来说明结构)的信息:
CREATE PROCEDURE CustOrder
-- Parameters
AS
BEGIN
IF NOT EXISTS (SELECT * FROM CustomerRecord WHERE CustName = @custName1)
BEGIN
-- Create the customer record.
END
-- Create the order.
END
答案 1 :(得分:0)
您应该尝试这种方式...有关更多信息,您可以访问此link
CREATE PROCEDURE CustOrder
@custName1 VARCHAR(50) = '',
@ReturnValue VARCHAR(100) OUT
AS
BEGIN
IF EXISTS (SELECT 1 FROM CustomerRecord WITH (NOLOCK) WHERE CustName = @custName1)
BEGIN
SET @ReturnValue = -1 -- for customer already exists
END
ELSE
BEGIN
-- write your insert statement
SET @ReturnValue = @@IDENTITY -- for return inserted customer identity column from CustomerRecord
END
END