在创建存储过程时使用CURSOR来插入语句

时间:2018-03-12 17:07:22

标签: sql sql-server stored-procedures cursor

我可以问一个关于SQL Server存储过程的问题吗?

基本上我创建了一个名为Customers的表,我想在存储过程中写一个INSERT语句,我已经使用CURSOR完成了。

当我执行我的CREATE存储过程应该没问题,并且没有任何错误消息,并且当我使用EXECUTE语句执行存储过程而没有任何数据输入时(7,Andy,Singapore)没有任何错误消息。< / p>

最后,当我将一些数据输入到EXECUTE存储过程中时,我收到了此错误消息。

  

Msg 8146,Level 16,State 1,Procedure InsertCustomers_Cursor,Line 0 [Batch Start Line 40]
  过程InsertCustomers_Cursor没有提供参数和参数。

代码:

create table customer 
(
    cust_id int primary key,
    name    varchar(100),
    country varchar(50)
);

insert into customer 
values (1, 'John Hammond', 'United States'), 
       (2, 'Mudassar Khan', 'India'), 
       (3, 'Robert Tan', 'Singapore'), 
       (4, 'Dennis Rodman', 'Indonesia'), 
       (5, 'Michelle Chia', 'Indonesia'),
       (6, null, null);

select * 
from customer;

CREATE PROCEDURE InsertCustomers_Cursor
AS
BEGIN
    DECLARE @cust_id    int,
            @name       varchar(100),
            @country    varchar(50)

    DECLARE @Counter INT
    SET @Counter = 1

    DECLARE @AllRecords TABLE 
    (
        cust_id int,
        name    varchar(100),
        country varchar(50)
    )

    DECLARE InsertCustomers CURSOR READ_ONLY
    FOR
        SELECT cust_id, name, country
        FROM customer

    OPEN InsertCustomers

    FETCH NEXT FROM InsertCustomers INTO @cust_id, @name, @country

    WHILE @@FETCH_STATUS = 0
    BEGIN
        INSERT INTO @AllRecords 
        VALUES (@cust_id, @name, @country)

        FETCH NEXT FROM InsertCustomers INTO @cust_id, @name, @country
    END

    CLOSE InsertCustomers
    DEALLOCATE InsertCustomers
END
GO

-- This EXEC statement cannot run the query
EXEC InsertCustomers_Cursor 7, 'Michael Labone', Indonesia

-- This EXEC statement can run the query and the results is to show how many are being affected
EXEC InsertCustomers

1 个答案:

答案 0 :(得分:0)

问题是你的SP不期望任何参数而你正在调用它传递参数

EXEC InsertCustomers_Cursor 7, 'Michael Labone', Indonesia

要使其正常工作,您需要在SP中创建这些参数:

CREATE PROCEDURE InsertCustomers_Cursor
  @cust_id    int,
  @name       varchar(100),
  @country    varchar(50)
AS
BEGIN
  ...

删除此部分:

DECLARE @cust_id    int,
        @name       varchar(100),
        @country    varchar(50)

可以有更优雅的方式来声明这些参数,但对于这个例子,我认为这已经足够了。