Error: There is not enough space on the disk

I was running a query in SQL Server Management Studio (SSMS), nothing too complicated, and got this error, unexpectedly:

An error occurred while executing batch. Error message is: There is not enough space on the disk.

There’s plenty of space on the server, so what’s the problem? The problem is that we’re running a query in SSMS, and SSMS caches resultsets to your %TEMP% directory. And there’s no way to configure that, other than changing where %TEMP% actually *is*.

Just to demonstrate the problem, navigate to %TEMP% – it’s buried somewhere in the user profile AppData directory, so it’s quicker just to open a new explorer window and type %TEMP% into the navigation bar:

Look! SSMS!

However, no sign of any files containing anything useful. Open a command window at this location – quick way is to just put “cmd” into the Navbar and hit return:

That opens up a command window in the right location. Look for hidden files:

There’s the culprit (OK, it’s only 14KB here, bu tit’s a small query just to prove a point…)

To really prove the point, on this particular server, I can do it just by running this:

USE [msdb];

FROM [dbo].[backupset] AS [bs1],
     [dbo].[backupset] AS [bs2],
     [dbo].[backupset] AS [bs3];

…but that would risk crashing the server. So I won’t do that.

What do we learn from this, though? The main points (for me):

  • Don’t run SSMS on servers
  • Make sure there’s plenty of disk space
Posted in SQLServerPedia Syndication | Tagged , | Leave a comment

OBJECT_ID()’s second parameter

I received a supplier-supplied maintenance / check / troubleshooting script that did a whole heap of looking-to see-if-a-default-value-exists-and-if-it-doesn’t-then=create-it type stuff.

As you would expect, it’s a load of

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'<<DefaultName>>') AND type = 'D')




They could have saved themselves a bit of typing (or, let’s be honest, copying-and-pasting) by replacing all those IF NOT EXISTS with

IF OBJECT_ID(N'<<DefaultName>>', N'D') IS NULL




Yes. OBJECT_ID can take a second parameter, which is the type of object to look for.

It might be worth noting that, although the type value in sys.objects is of type char(2), the type parameter in OBJECT_ID is implicitly converted to nvarchar if it’s not declared as such. Is this some far-sighted future-proofing? Check the documentation for sys.objects to see the possible values for the type field.

Posted in SQLServerPedia Syndication | Tagged | Leave a comment

SQL Server Availability Groups and SQL Server Reporting Services – A Brief Rant Triggered By Someone Failing Something Over Without Understanding The Full Implications, Or, Pay Attention To Your DBA Because He Knows This Stuff And That’s What You Pay Him For

Is the headline longer than the body? Not now I’ve included the fix for this situation as well as the initial rant. Maybe next time.

Yes, you may have an availability group – well done – and you may have installed SSRS on both servers. But you’ve only set up the reporting application to point to one of those? And you’ve given the link https://<<Listener_Name>>/reports out to the users? Head/desk. I told you at the time that SSRS doesn’t play nicely with AGs. [Nearly misposted as SSRS doesn’t play nicely with SSRS, which, while valid, isn’t the point here…]

Here’s what you need to do to fix this / make sure it doesn’t happen:

  1. Install the reports on the active server
  2. Failover
  3. Install the reports on the now-active server
  4. On each server, change the report data source to use the listener as the source, not (localserver)
  5. On each server, set up the security group(s) and permissions your users require

[Disclaimer – this worked for this situation. It might not work for yours. Support here is worth what you paid for it. Don’t Drink and DBA.]

Only then will you be able to get away with distributing the AG Listener as the SSRS URL. I said this much at the time… Yes, I know things were a bit…difficult back then, but still. Oh well.

Where’s my LART? Or my coffee? Either will do

Posted in SQLServerPedia Syndication | Tagged , , | 3 Comments

SQL Server Error 18456 Severity: 14 State: 73

A question asked on one of the forums today wasn’t easily answerable by Googling. Summary of the question “I have error 18456 State 73 – why?

Google seemed remarkably quiet on the subject of that particular state code. Even Aaron Bertrand’s list of causes of state codes for SQL Server error 18456 missed this one.

However, some searching did find a link to what appears to be some in-depth VMWare VSAN training documentation that includes that error in some logging information, which made me wonder if it was related to the error 18456 state 38 that followed. The log excerpt in question:

2017-08-17 23:16:47.690 spid52 Setting database option SINGLE_USER to ON for database for 'tpcc'.
2017-08-17 23:18:28.490 Logon Error: 18456, Severity: 14, State: 73.
2017-08-17 23:18:28.490 Logon Login failed for user 'SQL2016-SA-03\Administrator'.  Reason: Failed to open the database 'tpcc' configured in the session recovery object while recovering the connection. [CLIENT: ]
2017-08-17 23:18:31.330 Logon Error: 18456, Severity: 14, State: 38.
2017-08-17 23:18:31.330 Logon Login failed for user 'SQL2016-SA-03\Administrator'.  Reason: Failed to open the explicitly specified database 'tpcc'. [CLIENT: ]

The full text of the error in the SQL Server event log is “Failed to open the database ” configured in the session recovery object while recovering the connection”. That, combined with the error state 38 – Failed to open the explicitly specified database – led me to think that a connection had been dropped and the database dropped or made otherwise unavailable before the user tried to reopen the query session.

A test

Fire up SSMS, and create a database:


In another query window, run the following:

USE Test73;

Make a note of that SPID, and feed it into the following SQL that you run in the first window:

KILL 55;

Now go back to the second query window, and hit F5 to refresh / rerun the batch.


The error text:

TITLE: Microsoft SQL Server Management Studio

The connection is broken and recovery is not possible. The client driver attempted to recover the connection one or more times and all attempts failed. Increase the value of ConnectRetryCount to increase the number of recovery attempts. (Microsoft SQL Server, Error: 0)

For help, click:


Cannot open database “Test73” requested by the login. The login failed.
Login failed for user ‘SomeDomain\RUSHTONT’. (Microsoft SQL Server, Error: 4060)

For help, click:

To confirm this series of errors, check the SQL Server Error Log in SSMS, and you’ll see:

Suspicion proved!

Now all we have to do is test to see if there are other possibilities for this issue, but I need to step away from the keyboard…

Posted in SQLServerPedia Syndication | Tagged , , | 1 Comment

Longrunning Query – xp_cmdshell?

Flicking through the ol’ Solarwinds activity monitor, I spotted this one day:

Longrunning WTF 01 - SolarWinds Top SQL Statements

That four day purple thing on the right? Not good.

(The remaining images are from a reconstruction, partly to protect the not-so-innocent, and partly because the first job was (as always) fix the finance department’s server…)

Running Adam Machanic’s (b|t) excellent sp_WhoIsActive gave us the following:

Longrunning WTF 02 - sp_WhoIsActive output

Except, in reality, the first column was over 3 days, and the wait_info & CPU fields were waaaay higher. And the login_name field gave me the name of the perpetrator.

I wanted to know what he was up to, but the sql_text field only gives “xp_cmdshell”, not anything useful that might help to identify what went wrong.

So we have to go to Taskmanager on the server. On the “Process Details” page, you can select which detail columns you want to see. We want to see the Command Line, as that’ll tell us if it’s some manually-launched batch job that’s failed or something else going wrong.

Longrunning WTF 03 - TaskManager Process Page Columns

Click on OK, and find the process (in this case, the only process) named “cmd.exe” that’s been launched by the SQL Server service.

Longrunning WTF 04 - Task Manager Process Line

Oh my. Launching “calc.exe”? Why?

But this shows just what can go wrong if you don’t think about what you’re doing when launching xp_cmdshell – it can (and does) give you the ability to launch anything – and the problem with that is that you can’t control applications with a User Interface when they’re launched from a service account on a server – all you can do is hope you find what you’ve done, and that you can kill it.

…which I could, in this case. Fortunately, the only harm in this case was a red face (not mine, for a change).

Posted in SQLServerPedia Syndication | Tagged , , , , , | 1 Comment

A Problem with Boolean Logic

Your requirement: to find the things where either A or B is true and C is true. Your first draft might be this:


(field, table, function, logic all anonymised to protect the perpetrator)

What’s the problem? Operator Precedence, that’s the problem.

Operator Precedence?

The order in which calculations are done – not just reading from left to right, but remembering that things like multiplication and division happen before addition and subtraction. My son tells me that kids nowadays are being taught something called “BIDMAS” – which stands for “Brackets, Indices, Division, Multiplication, Addition, Subtraction”. Or it can be BODMAS – Brackets, Operations, Division… (Operation is a fancy new way of describing indices – ie xy)

Unsurprisingly, there are similar rules for Boolean operators. (Boolean Operators LogicaL Order of CalculationS? BOLLOCS? So close…) And these all mix in together, with AND being at the same level as multiplication, and OR being at the same as addition. Microsoft has kindly provided a list of the operator precedence rules it uses in SQL Server.

So What? I hear you cry

Well, we had a malfunctioning server. Running sp_WhoIsActive against the server showed 400-odd queries blocked by five instances of a malformed bit of code like the statement at the top of this post.

We, like many places, have a variety of third-party applications that allow users to write their own queries at a high level, and then the applications fill in the blanks, and add all the close brackets and things, to make the query actually parse… What these apps don’t do, of course, is fix the broken logic for you. Anyway, our Joe Punter had been asked to run a query to find customer results (or something) where condition A or condition B were true, and condition C was also true. And he had come up with the A OR B AND C logic above, and was puzzled when he fired off the report that it didn’t come back instantly, so he fired it off again. And again. And a couple more times for good luck.

Reproducing the Problem For Fun & Blogging Purposes

We are using the AdventureWorks Database, as that’s easy to get hold of. (NB: MS has moved all this stuff to github – you may need to update your bookmarks accordingly.)

This query below is a cut-down hack that illustrates the problem. In the data sense, it’s garbage, but it illustrates the problem albeit with several orders of magnitude less data.

       Sales.SalesOrderDetail AS sod,
       Sales.SalesOrderHeader AS soh
       soh.OnlineOrderFlag = 1
    OR soh.BillToAddressID = soh.ShipToAddressID
   AND soh.SalesOrderID = sod.SalesOrderID;

The query plan generated is…unpleasant


As you can see, the query plan is dominated by that Nested Loop operator. Let’s have a look what’s going on there:



Let’s rewrite the query properly (ie add a bracket or two):

       Sales.SalesOrderDetail AS sod,
       Sales.SalesOrderHeader AS soh
       (soh.OnlineOrderFlag = 1 OR soh.BillToAddressID = soh.ShipToAddressID)
   AND soh.SalesOrderID = sod.SalesOrderID;

And the query plan:

Spot the difference.

Yes, the query returns different answers – that’s kinda the point inasmuch as the original query would not have returned what the user wanted… But we can now see a more appropriate join operator, and one that’s not taking all the query time.

The moral of the story? Get your logic right, and your server won’t fall around your ears.

Posted in SQLServerPedia Syndication | Tagged , , , , | 2 Comments

T-SQL Tuesday – Bad Habits – Fixed by SQLPrompt

TSQL2sDay150x150T-SQL Tuesday again. And it’s been a few months since I last blogged, let alone for this blog-party, but, hey, I’m here now. This time, Aaron Bertrand (blog|@aaronbertrand) has given two options – and, given the amount time I’ve been spending lately talking about, seeing and performing in operas, I thought I would talk about T-SQL. And, yeah it’s another redgate-related SQLPrompt Post. <disclaimer/disclosure>They don’t pay me, they’ve not asked me to write this, but they do provide me with software, and I would buy this tool myself if I wasn’t on the FoRG programme…

Bad Habits

Aaron has been busy collecting a list of many many bad T-SQL / SQL Server habits, and some of them are scary.

The one I’m writing about – Using AS instead of = for Column Aliases – is the subject of a holy war, despite being mostly seen as stylistic.

Some of you DBA weirdos insist on writing code like

SELECT x = col1...

rather than the proper, ANSI-standard form of

SELECT col1 AS x...

Even though using “AS” conforms with the ANSI standard, Aaron is against it. He’s wrong, and I guess there are plenty of other deviants out there, but there are plenty of us right-minded people who prefer the proper version.

If you’re working in a big team, though, you can run into real problems where there’s a mix of styles in use.

SQLPrompt’s “Code Smells”

Redgate’s SQLPrompt has new functionality to identify what it calls “code smells” – bits of non-standard functionality, or deprecated usages. It highlights these smelly lines of code with a green wavy line, like you see under dodgy grammar in Word.

If you put your cursor into the green wavy line, the smelly bit is highlighted and a new blue icon appears in the left hand gutter. Click on that, or press CTRL, and up comes a window that describes the problem, and gives you a link to redgate’s documentation about it. OK, it’s a bit sparse, but that’s not the point of this post.

De-stinking code

If you’ve got a lot of code to review, and want to fix this easily, fortunately you can apply this fix automatically using SQLPrompt as part of its reformat sweep.

You’ll need to check the “Apply column alias style” box, and then pick the right style (above), but that’s all you need to do. (OK, if you’re a deviant like the guy I work with, you can set it to use one of the other WRONG formats, but don’t do that because it’s WRONG…)

A quick CTRL+K, CTRL+Y later, and you get properly formatted code:

And as for my strange friend, if he wants to see it in the wrong format, he can set up his own preferences. Or he could, if he had a licence for SQLPrompt, which he doesn’t… Yet…

Posted in T-SQL Tuesday | Tagged , , , | Leave a comment