插入经典asp之后无法获得scope_identity

时间:2011-05-19 18:45:39

标签: asp-classic vbscript ado

我必须为经典的asp做一个快速而又脏的sql会话存储,所以我有以下存储过程来执行插入工作。当我从sql management studio或通过asp代码运行它时,它插入正常,但它没有返回scope_identity。奇怪的是,当我从代码中执行该过程时,我得到“当对象关闭时不允许操作”,它在检查rs.eof的行上出现错误消息。

create procedure InsertSessionValue

    @keyname varchar(50),
    @value varchar(max)

as

    declare @ID int
    delete from storedsessionsimple where datesaved < dateadd(d, -1, getdate())

    insert into dbo.StoredSessionSimple (SessionKey, SessionValue, DateSaved) values (@keyname, @value, getdate())

    set @ID = SCOPE_IDENTITY()

    return @ID

,asp代码是......

set cnLocal = GetConnection()
    cnLocal.open()

    set rs = cnLocal.execute("exec InsertSessionValue '" & SessionKey & "','" & SessionValue & "'")
    if not rs.eof then
        id = rs(0)
    end if
    rs.close: set rs = nothing
    end if
    cnLocal.close: set cnLocal = nothing

3 个答案:

答案 0 :(得分:0)

在存储过程中使用RETURN通常用于返回状态或错误代码。如果您想将数据作为记录集从存储过程中返回,请使用SELECT代替RETURN

更新:听起来它仍然没有发现您的存储过程现在正在返回记录集。根据ADO命令的MSDN文档:

  

如果命令不是为了返回结果(例如,SQL UPDATE查询),只要指定了选项adExecuteNoRecords,提供程序就返回Nothing;否则Execute返回一个关闭的Recordset。

答案 1 :(得分:0)

如果要在记录集中返回SCOPE_IDENTITY,则存储过程需要进行一些更改。它当前实现的方式IDENTITY作为RETURN_VALUE参数返回,您必须使用ADO Command对象检索该参数。返回值将是Command.Parameters集合中的第一个参数。有关示例,请参阅以下article

如果要在记录集中返回结果,请尝试更改行

set @ID = SCOPE_IDENTITY()

SELECT SCOPE_IDENTITY() AS NEW_ID

并删除return语句。

答案 2 :(得分:0)

只需使用

set nocount on ; 

您的Sql使用&#34;;&#34;

插入查询
set nocount off ;

并使用下面的方法

Set rsInsert = conn.execute(SQLQuery)


if not rsInsert.EOF then
   response.write(rsInsert(0))
end if

工作正常。我测试了。