1

trying to get this stored procedure to work.

ALTER PROCEDURE [team1].[add_testimonial]
-- Add the parameters for the stored procedure here
@currentTestimonialDate char(10),@currentTestimonialContent varchar(512),@currentTestimonialOriginator varchar(20)
AS
BEGIN
DECLARE
@keyValue int

SET NOCOUNT ON;
--Get the Highest Key Value
SELECT @keyValue=max(TestimonialKey)
FROM Testimonial
--Update the Key by 1
SET @keyValue=@keyValue+1
--Store into table
INSERT INTO Testimonial VALUES (@keyValue, @currentTestimonialDate, @currentTestimonialContent, @currentTestimonialOriginator)

END

yet it just returns

Running [team1].[add_testimonial] ( @currentTestimonialDate = 11/11/10, @currentTestimonialContent = this is a test, @currentTestimonialOriginator = theman ).

No rows affected.
(0 row(s) returned)
@RETURN_VALUE = 0
Finished running [team1].[add_testimonial].

and nothing is added to the database, what might be the problem?

4

2 回答 2

1

可能有两个地方有问题:

一个。表中没有数据,因此,max(TestimonialKey)返回null,下面是处理它的适当方法。

--Get the Highest Key Value
SELECT @keyValue= ISNULL(MAX(TestimonialKey), 0)
FROM Testimonial
--Update the Key by 1
SET @keyValue=@keyValue+1

湾。检查列的数据类型currentTestimonialDate是否为charDateTime类型,如果该字段是表中的日期时间类型,则在插入表之前转换@currentTestimonialDateDateTime

此外,检查不允许为空的列数,并将数据传递给它们。

如果您没有为所有列传递数据,请尝试指定列名称,如下所示:

--Store into table
INSERT INTO Testimonial(keyValue, currentTestimonialDate, 
                       currentTestimonialContent, currentTestimonialOriginator) 
              VALUES (@keyValue, @currentTestimonialDate, 
                     @currentTestimonialContent, @currentTestimonialOriginator)

编辑:

在得到 marc_s 的评论后:

make keyValueas INT IDENTITY,如果多个用户同时调用它不会有问题,DBMS会处理它,所以过程中的最终查询可能如下:

ALTER PROCEDURE [team1].[add_testimonial]
-- Add the parameters for the stored procedure here
@currentTestimonialDate char(10),
@currentTestimonialContent  varchar(512),@currentTestimonialOriginator varchar(20)
AS
BEGIN

  SET NOCOUNT ON;
  --Store into table
  INSERT INTO Testimonial VALUES (@currentTestimonialDate, 
        @currentTestimonialContent, @currentTestimonialOriginator)

END
于 2011-11-28T03:28:32.937 回答
0

我可以发现的两个问题:

SELECT @keyValue=max(TestimonialKey)

应该

SELECT @keyValue=ISNULL(max(TestimonialKey), 0)

考虑数据库中没有记录的情况

其次,我相信使用NOCOUNT ON,您不会将插入的行数返回给调用者。所以,在你的INSERT陈述之前,添加

SET NOCOUNT OFF
于 2011-11-28T02:59:33.887 回答