Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

tsql - Alternate synonym in SQL Server in one transaction

I am new to Transact SQL programming.

I have created a stored procedure that would drop and create an existing synonym so that it will point to another table. The stored procedure takes in 2 parameters:

  • synonymName - an existing synonym
  • nextTable - the table to be point at

This is the code snippet:

...
BEGIN TRAN SwitchTran
   SET @SqlCommand='drop synonym ' + @synonymName
   EXEC sp_executesql @SqlCommand
   SET @SqlCommand='create synonym ' + @synonymName + ' for ' + @nextTable
   EXEC sp_executesql @SqlCommand
COMMIT SwitchTran
...

We have an application that would write data using the synonym regularly.

My question is would I run into a race condition where the synonym is dropped, while the application try to write to the synonym?

If the above is a problem, could someone give me suggestion to the solution.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, you'd have a race condition.

One way to manage this is to have sp_getapplock after BEGIN TRAN in Transaction mode and trap/handle the return status as required. This will literally serialise (in the execution sense, not isolation) callers so only one SPID executes at any one time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...