2012-02-02 67 views
0

我在Intranet上有一个页面,它将请求提交给perl CGI脚本。该脚本依次调用SQL Server数据库上的存储过程来检查是否存在具有某些特性的对象。如果确实如此,storproc将返回乐器的ID,如果不是,则会创建一个新乐器并返回该乐器的ID。存储过程创建一个事务,并在插入语句中使用with (TABLOCKX)。为了用户友好,当所述用户同时提交一堆请求时,网页将请求异步地提交给perl脚本。我认为当提交几个请求都需要一个新的工具时,第一个打到storproc的请求将运行,锁定表,创建新工具,释放锁,然后对storproc的后续调用将会知道新仪器并使用它。我在实践中看到的是,会有一些请求创建新的工具,其余的将使用最新的工具。我尝试在客户端使用setTimeout来分隔请求,但这似乎没有什么区别。任何想法,我可能做错了什么?从存储过程中插入SQL Server独特行不起作用

这里是存储过程的代码:

CREATE PROCEDURE [dbo].[CreateFutures] 
@code varchar(5), 
@month int, 
@year int, 
@currency varchar(3) 
AS 
BEGIN 
SET NOCOUNT ON; 
BEGIN TRANSACTION 

declare @ticker varchar(7) 
declare @yearCode char(1) 
declare @res as Table (id int) 
declare @n as int 

set @yearCode = convert(char(1), @year % 10) 

set @ticker = (
    select @code + futures + @yearCode 
    from FuturesMonthCodes 
    where month = @month 
) 

insert into @res 
select top 1 instrument 
from InstrumentFutures // This is a view that joins InstrumentText and InstrumentNumber data 
where ticker = @ticker 
and code = @code 
and month = @month 
and year = @year 
and currency = @currency 
order by instrument 

set @n = (select COUNT(id) from @res) 

if @n = 0 
    begin 
     print 'Creating Future' 
     declare @id int 
     declare @stamp datetime 
     set @stamp = CURRENT_TIMESTAMP 
     insert into Instrument with (TABLOCKX) (insertTime) values (@stamp) 
     set @id = (select SCOPE_IDENTITY()); 

     insert into InstrumentText  (instrumentId, name, value) values (@id, 'type', 'futures') 
     insert into InstrumentText  (instrumentId, name, value) values (@id, 'ticker', @ticker) 
     insert into InstrumentText  (instrumentId, name, value) values (@id, 'code', @code) 
     insert into InstrumentText  (instrumentId, name, value) values (@id, 'currency',@currency) 
     insert into InstrumentNumber (instrumentId, name, value) values (@id, 'month', @month) 
     insert into InstrumentNumber (instrumentId, name, value) values (@id, 'year', @year) 

     insert into @res (id) values (@id) 
    end 
commit transaction 

if @n = 0 --instrument created 
    select top 1 id, 1 from @res order by id 
else --returning existing instrument 
    select top 1 id, 0 from @res order by id 
END 
+2

要开始,发布插入过程的代码。 – 2012-02-02 23:46:12

回答

1

它比perl的多个SQL问题。

假设3个脚本尝试在同一时间运行此存储过程。

第一次执行并锁定表。其他人等待表解锁,但当锁定结束时他们不重新读取数据,因此他们使用旧数据。

如果您的存储过程进行了选择,您必须在锁定消失后重新运行它。

Regards,

相关问题