Tuesday, March 20, 2012
Revisiting the locking issues with Sql2000
The issue we are seeing is we get a process that blocks a table, and the bulding up of block process that cause timeouts/deadlocks etc. A couple of things we see when this happens is that .net on the web server seems to open up more and more connections(it seems to double or triple the connections as the blocking begins), we start to see deadlocks and we see alot of timeouts in the app due to the blocking.
The blocking aways happen on an insert of an order or a customer. One thing I keep wondering about is how we handle the unique id for our tables. Our DBA had us put in the following:
Begin Trans
select max(id) + 1
insert...
commit trans
I've heard from a few here and in other forums this is the wrong way to go. I'm still get a gut feeling that this could start causing issues like what we are seeing. My problem is I'm not knowledgable enough to make a strong enough case with it.
What I need help is getting enough information to either point to how we manage ID's or at the very least rule them out. I've done searchs in google and some other search engines but there doesnt seem to be any good articles on how best to handle unique ids and show a good case for it. I do know I can use sql identity, or even guid with the newid() function but I need solid proof before my boss will move to one of these methods. Any links you guys can give or even your own write up will really help my case and hopefully help my headache.
Thanks Ahead of timeI hope at least that you have an index on the id column. I do know that the spike in connections is caused by the blocking, so you are right in thinking that solving the blocking problem will solve the connection problem.
How long does the insert take? If it is a row or two to a couple of nice normalized tables, they shouldn't cause so much trouble. If you are inserting into 100 column tables, then you have some redesigning ahead of you.
I am going to guess that the DBA wants you to save off the max(id) + 1 as your ID. This is a fairly common need, but can be accomplished better through stored procedures. Are you supporting SQL 2000 as well as another RDBMS? If so, then you might not be able to get around this, as you have to play to the lowest common denominator. I am not sure if Oracle, DB2 or any of the others have a new_id () - like function.|||Yeah indexing is in place and from what I can tell, done correctly. We update statistics every night and reindex maybe once a week or so now. The inserts is one at a time but we have about 100-150 users at any given time inserting orders not to mention data we pull in from the websites(10 different sites pulling in around 5000-6000 orders a day). The ugly part of the websites is that it is a cursor that does maybe 50 to 60 orders one at a time(we run the webimports once an hr for each site). We just can't seem to narrow it down and its driving us crazy.|||Yeah, IDENTITY would have made your life much easier, and you probably would not have had those blocking issues. You can and probably should add a table hint to the table where MAX id is stored, but...
The problem with this volume and concurrency is that using:
BEGIN TRAN
select @.id=max(id)+1 from tbl (HOLDLOCK)
INSERT...
...
COMMIT TRAN
would ensure consistency of data, but the duration of each transaction would also ensure that you'll continue having timeouts.
...And before certain "someone" jumps in to promote GUID, I'd say I'm all for it, but try to convince your developers and especially users that typing 5AA729BB-466C-40E8-A487-1C375CFB965B is easier than any sequencial number...|||Cursor that is run once per hour? Hmm. This could be a part of the problem. First thing is going to be finding out who is blocking whom. Try this out, and modify it to find out who is doing what:
select spid, cpu, physical_io, memusage, blocked, waittype, lastwaittype, waitresource
from master..sysprocesses
where blocked > 0
union
select spid, cpu, physical_io, memusage, blocked, waittype, lastwaittype, waitresource
from master..sysprocesses
where spid in (select blocked from master..sysprocesses)
You will probably want to add either program_name, hostname, or loginame to the above queries, depending on how you can tell the various processes apart.
If the ID column is indexed, then the select max(id) + 1 should take out just a rowlock on that one row. The cursor, on the other hand, could be doing all sorts of things to the back of your database. Let us know who is doing all the blocking. Then we can figure out what to do about it.|||Actually who is blocking who I can answer. Its actually across the board. If it was one particular process that would cause it we would have hunted that down. Sometimes it locks when the web imports comes in. When that happens, sometimes its the cursor, sometimes its somone out on the floor taking the order over the phone. Sometimes it happens when the web import is not occuring. This is the frustrating part...there really isn't a partern to it...|||Since no one process is to blame, have you narrowed it down to this one table with the ID column?
How long does it take to do the insert? If the insert goes over about 2 seconds (6000 inserts/8 hour shift comes out to one insert per 5 seconds, so taking gusts into account..), then you should be OK. Otherwise, blocking on the select is almost guaranteed.
As a wild-a** idea, you could build off both ends of the table, and have some processes add orders with select min(id) - 1 for their IDs. That may only get you so far, though.
I think the consensus is going to be try to eliminate the select part altogether, and get to an identity or new_id() way of doing things. It sounds like you do not have to worry about cross-platform or migration issues.|||You may be able to put a band-aid of sorts on this system. After thinking it over, this may be the second system I have seen in my career that could benefit from the (nolock) hint. If you use the (nolock) hint on the select max(id) + 1 query, then it will not be blocked by the insert queries. HOWEVER, you will run a slightly higher risk of inserting (or trying to insert) duplicate IDs into the table. I think this is already a minor problem in the design, because two connections could select the same max(id) if they are run close enough together. The increase in risk is that this time period will now expand by a few milliseconds, to wit, the amount of time between when the insert query sets up all of its locks, and when the insert actually happens. I doubt it is a long period of time (or at least I hope it is not), so you may get away with it. Just remember, (nolock) is not to be used lightly. If you do a search on (nolock) in this forum, you will probably find a number of posts saying do not use it. As was pointed out before, using either an identity column, or using new_id() would be a much better fix for this situation. This would only ever be a band-aid buying you a little time to implement a better solution. Good luck.
Friday, March 9, 2012
Reusing connections
Every time my asp.net app needs to open a connection, it tries to establish a new connection with the mssql server. I′ve already set the max pool size property in the connection string. After that, my app raises an "time out"error saying it couldn′t obtain a connection from the pool. The problem is that I have a lot of iddle connections. With the Enterprise Manager I can see the status of the connections. They′re all the same "awaiting command". How can I reuse this connections? I know that the connection string must be the same for all connections and it is. I′ve set it in the web.config file. If I remove the max pool size property from the connection string I get a lot, I mean A LOT of connections with the sql server. Any ideas?
You should be ensuring that all connections get closed using a try/catch/finally block. Also, take a look at the following articles:
Tuning Up ADO.NET Connection Pooling With ASP.NET Applications
ASP.NET and SQL Server Performance Tips
The .NET Connection Pool Lifeguard
HTH
Wednesday, March 7, 2012
Returning Values from a Dynamic SQL
The frontend is a VB.Net program. At the year end, the program creates
new voucher and transaction tables and creates new stored procedures for
them.
I just append the 'new year' at the end and create them
ie, Vouchers2001, Vouchers2002, Vouchers2003
Similarly Transactions2001, Transactions2002.
The data for all the years is in the same database.
Also, I maintain a table called 'Books' which contains the Years for
which data is present in the Database. The Structure of the Books table
is
BookID BookYear
1 2001
2 2002
3 2003
4 2004
My Problem is that i need to know the current balance of any ledger for
any year. The method to calculate the balance for any year is to start
from the Minimum year in the Books table and continue upto the required
year. The SQL is as follows.
DECLARE @.iLedgerID AS INT --will be passed as parameter
DECLARE @.iYear as INT --will be passed as parameter
DECLARE @.CurrentBalance as MONEY
SET @.iLedgerID =1
DECLARE @.MinBook as INTEGER
DECLARE @.String nVarchar(4000)
SELECT @.MinBook = Min(BookYear)
FROM Books
WHILE @.MinBook <= @.iYear
BEGIN
SET @.String = ' DECLARE @.TT Money ' + char(13) +
' SELECT @.TT = ISNULL( SUM( ISNULL(Debit,0) - ISNULL(Credit,0) ),0 )'
+ ' FROM transactions' + CAST(@.MinBook AS CHAR(4)) + ' LEFT OUTER JOIN
dbo.Vouchers' + CAST(@.MinBook AS CHAR(4)) + ' ON dbo.Transactions' +
CAST(@.MinBook AS CHAR(4)) + '.VoucherID' + ' = dbo.Vouchers' +
CAST(@.MinBook AS CHAR(4)) + '.VoucherID ' +
'WHERE (LedgerID = @.iLedgerID)'
EXEC sp_executesql @.String, N'@.iLedgerID Int', @.iLedgerID */
SET @.MinBook = @.MinBook + 1
END
Now this is just a sample code. It may have a few glitches. My question
is
a) Do I have to create a dynamic sql if the name of the database is not
known ahead of time. If No then
b) I need to add the balance of each year to the grand total. How do i
return a value from a dynamic sql.
TIA
*** Sent via Developersdex http://www.developersdex.com ***Oops, I missed out the last line in the string varible. The last line
returns the calculated variable. The SQL docmentation says that Return
can only return integer types. so how do i return a money value. I
cannot insert into a temporary table because the application is
Multi-User and may fail.
WHILE @.MinBook <= @.iYear
BEGIN
SET @.String =' DECLARE @.TT Money ' + char(13) +
' SELECT @.TT = ISNULL( SUM( ISNULL(Debit,0) - ISNULL(Credit,0) ),0 )' +
' FROM transactions' + CAST(@.MinBook AS CHAR(4)) + ' LEFT OUTER JOIN
dbo.Vouchers' + CAST(@.MinBook AS CHAR(4)) + ' ON dbo.Transactions' +
CAST(@.MinBook AS CHAR(4)) + '.VoucherID' +
' = dbo.Vouchers' + CAST(@.MinBook AS CHAR(4)) + '.VoucherID ' + 'WHERE
(LedgerID = @.iLedgerID)' + char(13) +
' Return @.TT'
EXEC sp_executesql @.String, N'@.iLedgerID Int', @.iLedgerID
SET @.MinBook = @.MinBook + 1
END
*** Sent via Developersdex http://www.developersdex.com ***|||Bill Bob (nospam@.devdex.com) writes:
> Oops, I missed out the last line in the string varible. The last line
> returns the calculated variable. The SQL docmentation says that Return
> can only return integer types. so how do i return a money value. I
> cannot insert into a temporary table because the application is
> Multi-User and may fail.
1) You would have a much simpler task, if you made the year a key in the
Vouchers and Transactions table, rather than having one table per year.
2) So you don't have the possibility to do that, but then create views:
CREATE VIEW Vouchers AS
SELECT Year = '2000', * FROM Vouchers2000
UNION ALL
SELECT '2001', * FROM Vouchers2001
UNION ALL
...
3) That you cannot use temp tabls in a multi-user environment is a mis-
understanding. Temp tables are visible for the local connection only.
4) However, ther prefer method for getting scalar data back from
sp_executesql is output parameters. For a quick example, see
http://www.sommarskog.se/dynamic_sql.html#sp_executesql.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||
> a) Do I have to create a dynamic sql if the name of the database is not
> known ahead of time.
Yes
> b) I need to add the balance of each year to the grand total. How do i
> return a value from a dynamic sql.
You can use OUTPUT parameters in sp_executesql
SET @.String = ' SELECT @.TT = ISNULL( SUM( ISNULL(Debit,0) -
ISNULL(Credit,0) ),0 )' +
' FROM transactions' + CAST(@.MinBook AS CHAR(4)) + ' LEFT OUTER JOIN
dbo.Vouchers' + CAST(@.MinBook AS CHAR(4)) + ' ON dbo.Transactions' +
CAST(@.MinBook AS CHAR(4)) + '.VoucherID' +
' = dbo.Vouchers' + CAST(@.MinBook AS CHAR(4)) + '.VoucherID ' + 'WHERE
(LedgerID = @.iLedgerID)' + char(13) +
' Return @.TT'
DECLARE @.TT Money
EXEC sp_executesql @.String, N'@.iLedgerID Int, @.TT Money', @.iLedgerID ,
@.TT OUTPUT|||... should be this
EXEC sp_executesql @.String, N'@.iLedgerID Int, @.TT Money OUTPUT',
@.iLedgerID ,
@.TT OUTPUT|||> 1) You would have a much simpler task, if you made the year > a key in
the Vouchers and Transactions table, rather than > having one table per
year.
My intial problem was something else. So, I had to switch to different
table for different years.
Each Voucher Table contains a VoucherDate and a VoucherTypeID and a
VoucherNo. The VoucherNo must be unique for a vouchertype and within a
financial year (1st April - 31st March).
SQL Server cannot create a unique index with this criteria. Hence, I had
to split the tables.
*** Sent via Developersdex http://www.developersdex.com ***|||Bill Bob (nospam@.devdex.com) writes:
> Each Voucher Table contains a VoucherDate and a VoucherTypeID and a
> VoucherNo. The VoucherNo must be unique for a vouchertype and within a
> financial year (1st April - 31st March).
> SQL Server cannot create a unique index with this criteria. Hence, I had
> to split the tables.
Of course it can! You would add Year as a column in the table, and the
primary key would be (Year, VoucherTypeID, VoucherNo).
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx
Returning the Primary Key
if you are using a stored procedure to insert then
Function()
Delcare con,
Delcare command,adapters etc....
'declare a param
Dim parameter1 As New SqlParameter("@.ID", SqlDbType.Int)
parameter1.Direction = ParameterDirection.Output
'after the executescalar
Dim iID As Integer = yourcommand.Parameters("@.ID").Value.ToString()
Return iID
End Function
Hope this helps?
m_7e7|||Multiple ways to get Identity value from SQL:
System variable @.@.Identity, this is database scope
Function SCOPE_IDENTITY(), Or IDENT_CURRENT('Table name')|||I might have to do it the srored procedure way, however at the moment i'm just using a function that executes the sql variable when it's called e.g
Dim queryString As String = "INSERT INTO [tblKnowledgeBase] ([knowledgeTitle], [knowledgeType], [knowledgeCust"& _
"omerView], [knowledgeProjectID], [knowledgeDesc], [knowledgeAttachName], [knowle"& _
"dgeAttachType], [knowledgeAttachSize], [knowledgeAdditionUserID], [knowledgeAddi"& _
"tionDate], [KnowledgeApproved]) VALUES (@.knowledgeTitle, @.knowledgeType, @.knowle"& _
"dgeCustomerView, @.knowledgeProjectID, @.knowledgeDesc, @.knowledgeAttachName, @.kno"& _
"wledgeAttachType, @.knowledgeAttachSize, @.knowledgeAdditionUserID, @.knowledgeAddi"& _
"tionDate, @.KnowledgeApproved)"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnectionDim rowsAffected As Integer = 0
dbConnection.Open
Try
rowsAffected = dbCommand.ExecuteNonQuery
Finally
dbConnection.Close
End TryReturn rowsAffected
Is there a way I can retrieve it with this method of insertion, If I use stored procedures I will have compatibility problems when creating a microsoft Access/mySQL version.|||Is your ID(Primary Key) a AutoNumber ??|||My advice would be to bite the bullet and use a stored proc.|||Try this query instead.............
Dim queryString As String = "INSERT INTO [tblKnowledgeBase] ([knowledgeTitle], [knowledgeType], [knowledgeCust"& _
"omerView], [knowledgeProjectID], [knowledgeDesc], [knowledgeAttachName], [knowle"& _
"dgeAttachType], [knowledgeAttachSize], [knowledgeAdditionUserID], [knowledgeAddi"& _
"tionDate], [KnowledgeApproved]) VALUES (@.knowledgeTitle, @.knowledgeType, @.knowle"& _
"dgeCustomerView, @.knowledgeProjectID, @.knowledgeDesc, @.knowledgeAttachName, @.kno"& _
"wledgeAttachType, @.knowledgeAttachSize, @.knowledgeAdditionUserID, @.knowledgeAddi"& _
"tionDate, @.KnowledgeApproved)";"SELECT @.@.IDENTITY AS Ident";
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection
Dim rowsAffected As Integer = 0
dbConnection.Open
Try
rowsAffected = dbCommand.Executescalar
Finally
dbConnection.Close
End Try
Return rowsAffected
*********Note*************
Use an executescalar instead of execnonquery and try.....|||Yeah it is an utonumber|||hey you got it???
Saturday, February 25, 2012
Returning SQL servers on a network
I would like some help with what the best way is to return a list of the
Server names on a network using VB .NET.
I found a reference to the dbserverenum function, is this the best thing to
use, I was unable to find any examples? I would be most grateful if someone
could provide some robust example code of the best way to do this.
Many thanks.Hi
I'm sure you can use SQLDMO object to list all servers
Dim i As Integer
Set oSQLServerDMOApp = New SQLDMO.Application
gShowServerEvents = False
Dim namX As NameList
Set namX = oSQLServerDMOApp.ListAvailableSQLServers
For i = 1 To namX.Count
txtServer.AddItem namX.Item(i)
Next
--
or call the following SP from vb.net
--
CREATE PROCEDURE dbo.ListLocalServers
AS
BEGIN
SET NOCOUNT ON
CREATE TABLE #servers(sname VARCHAR(255))
INSERT #servers EXEC master..XP_CMDShell 'OSQL -L'
DELETE #servers WHERE sname='Servers:'
SELECT LTRIM(sname) FROM #servers WHERE sname != 'NULL'
DROP TABLE #servers
END
"11Oppidan" <11Oppidan@.community.nospam> wrote in message
news:efgTgepEFHA.628@.TK2MSFTNGP15.phx.gbl...
> Hi,
> I would like some help with what the best way is to return a list of the
> Server names on a network using VB .NET.
> I found a reference to the dbserverenum function, is this the best thing
to
> use, I was unable to find any examples? I would be most grateful if
someone
> could provide some robust example code of the best way to do this.
> Many thanks.
>|||If you want the instances of sql server, then you can use SQL-DMO API,
specifically the ListAvailableSQLServers Method of the Application object.
http://www.microsoft.com/resources/... />
c3561.mspx
AMB
"11Oppidan" wrote:
> Hi,
> I would like some help with what the best way is to return a list of the
> Server names on a network using VB .NET.
> I found a reference to the dbserverenum function, is this the best thing t
o
> use, I was unable to find any examples? I would be most grateful if someo
ne
> could provide some robust example code of the best way to do this.
> Many thanks.
>
>
Tuesday, February 21, 2012
Returning multiple results from a Cursor into a table
But more specifically, this is what I need to accomplish. I have written a cursor that I know works - when I run it in MS SQL Query Analyzer, I get the results I want, but it's returned in multiple tables. I am maintaining a .NET application with some pretty lousy performance and I'm trying to boost it up. I need to take the cursor's results, stuff them into a DataTable, and then return that table to my web application to render.
In my C# code, I am using a SqlDataAdapter to execute my query. This is what I'd like to do...
/*assume query is my working cursor, InvoiceDBConnection is not null, and dt is an empty, non-null DataTable*/
SqlDataAdapter sda = new SqlDataAdapter(query, InvoiceDBConnection);
sda.Fill(dt);
... but this doesn't work, and it makes sense, I guess...since the cursor returns multiple "tables" (not sure if that's actually how the data is returned).
So is there any way to accomplish what I want to do? Or do I have to do it the crappy way it's done now by running my aggregate query and then using a really time-consuming for loop on my results to make the necessary adjustment?
Any help is greatly appreciated
Have you tried putting the results into a single temp table and just returning that the end of the cursor?
If you post your DDL along with your existing T-SQL then we may be able to shed some more light.
HTH!
|||No, I haven't tried that. I'm pretty new to cursors, so I didn't know I could do that. Here's my cursor so far...
Code Snippet
DECLARE @.@.invoiceID int
DECLARE @.@.additions decimal
DECLARE @.@.subtractions decimal
DECLARE @.@.adjustments decimal
DECLARE @.@.payments decimal
DECLARE invoiceCursor CURSOR SCROLL
FOR
SELECT Invoice_ID FROM Invoice WHERE Customer_ID = 115
OPEN invoiceCursor
FETCH FIRST FROM invoiceCursor INTO @.@.invoiceID
WHILE @.@.FETCH_STATUS <> -1
BEGIN
SELECT @.@.additions = SUM(Amount)
FROM [Adjustment]
WHERE Is_Addition = 1 AND Invoice_ID = @.@.invoiceID;
SELECT @.@.subtractions = SUM(Amount)
FROM [Adjustment]
WHERE Is_Addition = 0 AND Invoice_ID = @.@.invoiceID;
SELECT @.@.adjustments = (CASE WHEN @.@.additions IS NULL THEN 0 ELSE @.@.additions END) - (CASE WHEN @.@.subtractions IS NULL THEN 0 ELSE @.@.subtractions END);
SELECT @.@.payments = CASE WHEN SUM(Payment_Amount) IS NULL THEN 0 ELSE SUM(Payment_Amount) END FROM Payment WHERE Invoice_ID = @.@.invoiceID
SELECT i.*, CASE WHEN i.Paid_In_Full = 1 THEN '<font face=''Arial'' size=''1'' color=''green''>Yes</font>' ELSE '<font face=''Arial'' size=''1'' color=''red''>No</font>' END AS Paid, @.@.payments AS Amount_Paid,
(Invoice_Amount - @.@.payments + @.@.additions) AS Remaining, CASE WHEN DATEDIFF(dd, Terms_Start_Date, GETDATE()) < 0 THEN 0 WHEN i.Paid_In_Full = 1 THEN 0 ELSE DATEDIFF(dd, Terms_Start_Date,
GETDATE()) END AS Terms_Days_Passed
FROM [Invoice] i
WHERE Invoice_ID = @.@.invoiceID
FETCH NEXT FROM invoiceCursor INTO @.@.invoiceID
END
CLOSE invoiceCursor
DEALLOCATE invoiceCursor
So it sounds like I need to declare a table somehow, and stuff the highlighted select statement into that table, and then Return that table?
Do you know the syntax for that offhand, or maybe know of an article I could read to do it? Thanks!
Sure, check out Books Online for table variables and temporary tables:
In pesudo code, you'd do something like:
Code Snippet
DECLARE @.AllYour variables
......
-- create your temp table
CREATE TABLE #InvoiceStuff
(iCol1 INT, iCol2 INT, strHTML VARCHAR(100))
OPEN CURSOR
INSERT INTO #InvoiceStuff
SELECT *
FROM Invoice
WHERE InvoiceID = @.InvoiceID
FETCH NEXT FROM Cursor
CLOSE Cursor
SELECT *
FROM #InvoiceStuff
DROP TABLE #InvoiceStuff
One other thing to mention, i'd suggest using single @.'s for your local variables as those with @.@. are system globals eg @.@.Fetch_Status and @.@.Version.
HTH!!
|||Awesome, thanks a lot. And I didn't know that about the local variables. I'm going to give this a shot.