Quantcast
Channel: SQL Error Messages – Journey to SQL Authority with Pinal Dave
Viewing all 134 articles
Browse latest View live

SQL SERVER – How to take InMemory – OLTP FileGroup Offline?

$
0
0

InMemory topics are always interesting and a great learning experience. When I wrote the other post, it was more about how InMemory tables are loaded into memory even if they are not queried. The basics, here is to bring the data for In Memory Tables ahead to memory irrespective of their usage.

After this blog post was published, someone wrote me a mail asking if it is possible to take the InMemory Filegroups offline? And will the table’s data taken offline too? This question was obvious but still needed validation and I was curious to understand why this wouldn’t work in normal circumstances. The script to start working on this post has to start from previous post. Please create the database and then before the cleanup step – start to run the below scripts.

At this stage, your query must return some value for the below query:

USE IM_OLTP;
GO
SELECT CONVERT(CHAR(20), OBJECT_NAME(OBJECT_ID)) AS Name,*
FROM sys.dm_db_xtp_table_memory_stats
WHERE OBJECT_ID> 0

For all practical purposes, InMemory tables and filegroups are just like normal files. We should be able to take them offline using the same way we can do other filegroups.

-- Take InMemory FG offline
ALTER DATABASE IM_OLTP MODIFY FILE (NAME = 'IM_OLTP_mod', OFFLINE)
GO

This should complete successfully and when we run the above DMV query to find the memory consumers, this must return no rows.

SELECT CONVERT(CHAR(20), OBJECT_NAME(OBJECT_ID)) AS Name,*
FROM sys.dm_db_xtp_table_memory_stats
WHERE OBJECT_ID> 0

Now that was pretty simple and easy to figure out. I would like to know if you have ever done anything like this in your systems?

Quick Quiz Question:

Now if taking the filegroup offline was easy, what about bringing the filegroup online next?

ALTER DATABASE IM_OLTP MODIFY FILE (NAME = 'IM_OLTP_mod', ONLINE)
GO

Simple isn’t it? No. You will encounter an error:

Msg 155, Level 15, State 1, Line 1
‘ONLINE’ is not a recognized CREATE/ALTER DATABASE option.

So the quiz question is, how can we bring the filegroup online in SQL Server 2014 version? What are the steps. Let me know via comments.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL Tagged: In-Memory

SQL SERVER – How to Suppress SQL Server messages in Application Event Log

$
0
0

Error messages are a great source of help when it comes to troubleshooting. What can I say, this is maybe be the most repeated phrase from me in this blog about error messages. The messages have grown over ages and got better with the SQL Server dev team putting in extra effort in every release. Having said that, I thought of adding something interesting in this blog.

Logging of errors in ERRORLOG is helpful in many situations. It has helped me many time to fix issues. Recently I came across an email where there was a strange behavior reported. Here in the email from my friend.

Hi Pinal,
We are using 3rd party software which uses SQL Server as backend. We also have monitoring software which keeps track of messages in Event log and sends alert to Wintel team.
Recently there was a brute force attach for sa password on that server so there were many login failure attempts like below:

2015-11-05 20:14:47.040 Logon        Error: 18456, Severity: 14, State: 8.

2015-11-05 20:14:47.040 Logon        Login failed for user ‘sa’. Reason: Password did not match that for the login provided. [CLIENT: 10.10.10.20]

There messages were logged many time and IP address listed there is some machine which we don’t know. We were able to stop the connection by firewall.

Here is the problem: Monitoring software didn’t report anything because strangely these messages were NOT logged in application event log at all.

Do you know how that can happen?
Thanks in advance.

Whenever I get such questions, I always asked for ERRORLOG.

SQL SERVER – Where is ERRORLOG? Various Ways to Find its Location

I looked into ERRORLOG file and found something interesting as below.

Registry startup parameters:

-d D:\MSSQL12.SQL2014\MSSQL\DATA\master.mdf
-e D:\MSSQL12.SQL2014\MSSQL\Log\ERRORLOG
-l D:\MSSQL12.SQL2014\MSSQL\DATA\mastlog.ldf
-n

Command Line Startup Parameters:

-s "SQL2014"

We can see a non-default startup parameter called “n”. I searched MSDN documentation and found its usage. “Does not use the Windows application log to record SQL Server events”

So I replied to my friend and later it was identified that 3rd party tool has done that change for that instance.

Mystery solved and I learned something new.  Have you ever used any such non-default startup parameter in production server?

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – Backup to Azure Blob error – The remote server returned an error: (409) Conflict

$
0
0

Cloud is inevitable. With various innovations happenings in this area, SQL Server is not left behind. It is becoming a first class citizen when it comes to moving to cloud. In the past couple of releases, we have been seeing the enhancements of integrating with Azure getting stronger. Last year I wrote a blog about taking backup directly to Azure Storage.

SQL SERVER – Backup to Azure Blob using SQL Server 2014 Management Studio

As part of a demo environments, I configured it long back and recently I stated seeing failures of backup in ERRORLOG and found below error message.

2015-04-03 15:39:12.40 spid165     Error: 18210, Severity: 16, State: 1.
2015-04-03 15:39:12.40 spid165     BackupVirtualDeviceFile::DetermineFileSize: SetPosition(0,EOF) failure on backup device ‘https://sqlauth.blob.core.windows.net/backups/SQLATHTEST_da634d4074d9451591fe99d6e6981f83_20150331160324-07.log’. Operating system error Backup to URL received an exception from the remote endpoint. Exception Message: The remote server returned an error: (409) Conflict.

I searched for the ways to fix this error and landed across MSDN article which asked to enable trace flag 3051 to get additional details.

DBCC TRACEON (3051,-1)

Once I ran the command and ran the back-up again, it failed but there was an additional file generated in the same folder which has ERRORLOG. Here is the content

11/10/2015 3:39:15 PM: ======== BackupToUrl Initiated =========
11/10/2015 3:39:15 PM: Inputs: Backup = False, PageBlob= True, URI = https://sqlauth.blob.core.windows.net/backups/SQLATHTEST_da634d4074d9451591fe99d6e6981f83_20150331160324-07.log, Acct= sqlauth, FORMAT= False, Instance Name = MSSQLSERVER, DBName = SQLAUTHTEST LogPath = D:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Log
11/10/2015 3:39:15 PM: Process Id: 7384
11/10/2015 3:39:15 PM: Time for Initialization = 9.0003 ms
11/10/2015 3:39:15 PM: BackupToUrl Client is getting configuration from SqlServr
11/10/2015 3:39:15 PM: Time for Handshake and VDI config = 10.0001 ms
11/10/2015 3:39:15 PM: Time for Get BlobRef = 0.9949 ms
11/10/2015 3:39:16 PM: An exception occurred during communication with Azure Storage, exception information follows
11/10/2015 3:39:16 PM:  Exception Info: The remote server returned an error: (409) Conflict.
11/10/2015 3:39:16 PM:  Stack:    at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](StorageCommandBase`1 cmd, IRetryPolicy policy, OperationContext operationContext)
at Microsoft.WindowsAzure.Storage.Blob.CloudPageBlob.AcquireLease(Nullable`1 leaseTime, String proposedLeaseId, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)

If we look at stack it talks about lease. 409 conflict – Indicates that the request could not be processed because of conflict in the request, such as an edit conflict in the case of multiple updates.

I downloaded Azure Explore tool from http://www.cerebrata.com/products/azure-explorer/introduction and using the tool I was able to break lease which was open. Below is the option in the UI called ‘Break Lease On Blob’ once you are connected to the Storage account.

lease 01 SQL SERVER   Backup to Azure Blob error   The remote server returned an error: (409) Conflict

Another way was to break the lease using the way documented in MSDN https://msdn.microsoft.com/en-us/library/jj919145.aspx (Deleting Backup Blob Files with Active Leases) and it needs coding which I am not an expert at.

Have you ever tried using backupToURL option with SQL Server? Will you be using these tools for your environments? Do let me know via comments.

Reference : Pinal Dave (http://blog.SQLAuthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – Installation failed with error – Wait on the Database Engine recovery handle failed

$
0
0

You might have seen on Facebook that I have completed the new setup of my machines. Since I use VMs to do my tests. To have a domain, I made a VM as domain controller and another as a member server. Next step was to install SQL Server and by mistake, I have run the setup of SQL on a domain controller. As per Microsoft documentation they don’t recommend installing SQL on the domain controller and there is a warning in SQL Setup.

setup dc 01 SQL SERVER   Installation failed with error   Wait on the Database Engine recovery handle failed

—————————
Rule Check Result
—————————
Rule “Computer domain controller” generated a warning.
Installing SQL Server 2016 CTP2.4 on a domain controller is not recommended.
—————————
OK
—————————
I proceeded further and it failed at the end with below error
Wait on the Database Engine recovery handle failed. Check the SQL Server error log for potential causes.
Here is the complete message in summary.txt file.
Feature:                       SQL Server Replication
Status:                        Failed: see logs for details
Reason for failure:            An error occurred for a dependency of the feature causing the setup process for the feature to fail.
Next Step:                     Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
Component name:                SQL Server Database Engine Services Instance Features
Component error code:          0x851A001A
Error description:             Wait on the Database Engine recovery handle failed. Check the SQL Server error log for potential causes.
I followed the error message as it asked to check ERRORLOG. Here is message in ERRORLOG
Error: 17190, Severity: 16, State: 1.
Initializing the FallBack certificate failed with error code: 1, state: 20, error number: 0.
Unable to initialize SSL encryption because a valid certificate could not be found, and it is not possible to create a self-signed certificate.
Error: 17182, Severity: 16, State: 1.
TDSSNIClient initialization failed with error 0x80092004, status code 0x80. Reason: Unable to initialize SSL support. Cannot find object or property.
Error: 17182, Severity: 16, State: 1.
TDSSNIClient initialization failed with error 0x80092004, status code 0x1. Reason: Initialization failed with an infrastructure error. Check for previous errors. Cannot find object or property.
Error: 17826, Severity: 18, State: 3.
Could not start the network library because of an internal error in the network library. To determine the cause, review the errors immediately preceding this one in the error log.
Error: 17120, Severity: 16, State: 1.
SQL Server could not spawn FRunCommunicationsManager thread. Check the SQL Server error log and the Windows event logs for information about possible related problems.

I searched on the internet and found that this could be issued with a SQL Service account. I selected all default configuration and it was NT Service\MSSQLServer

I uninstalled SQL Server and this time I selected Local System account for SQL Service in setup wizard and voilà it went fine.

Have you ever faced any such error on a regular machine? What was the solution?

Reference : Pinal Dave (http://blog.SQLAuthority.com)


Filed under: MySQL, PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – InMemory Table Creation Error Message: Msg 41337

$
0
0

I had recently gone to my hometown to visit my parents as it was holidays for my daughter because of festival. These are relaxing times and hardly try to get in front of my computer during these 2-3 days of family time. But who said that happens always. In this recent trip, I had one of my cousins visit our place who was incidentally studying his engineering degree. We suddenly got into a conversation and I started talking about InMemory databases and how they can be made resilient. Though this topic becomes a great conversation starter to college students, he was baffled with the fact that we can have InMemory databases that are ACID compliant.

He got to his home and said he would play around with this concept because he had a SQL Server 2016 evaluation version. I said there are many more enhancements to talk but wanted him to do his bit of search and homework before I taught him some really cool tricks. That night he sent me a mail stating he was getting some error while creating an InMemory table and was not sure what to do. I asked him to send me the error to take a first look:

Msg 41337, Level 16, State 100, Line 2
Cannot create memory optimized tables. To create memory optimized tables, the database must have a MEMORY_OPTIMIZED_FILEGROUP that is online and has at least one container.

It was clear from the message the source of the problem. He had created a normal database without the InMemory filegroup.

I sent him the script to get rid of the error message and is shown below:

-- Create the Database
-- Note the filegroup of type MEMORY_OPTIMIZED_DATA
USE MASTER
GO
IF DB_ID('InMem_OLTP') IS NOT NULL
BEGIN
ALTER DATABASE
[InMem_OLTP] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DROP DATABASE
[InMem_OLTP]
END
CREATE DATABASE
[InMem_OLTP]
ON  PRIMARY
( NAME = N'InMem_OLTP_data', FILENAME = N'C:\DATA\InMem_OLTP_data.mdf',size = 50MB)
LOG ON
( NAME = N'InMem_OLTP_log', FILENAME = N'C:\DATA\InMem_OLTP_log.ldf',size = 10MB)
GO
--- Step 2 - Can we create this table?
USE InMem_OLTP
GO
CREATE TABLE [Customer](
[CustomerID] INT NOT NULL
PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT = 10000),
)
WITH (MEMORY_OPTIMIZED = ON,  DURABILITY = SCHEMA_AND_DATA  );
GO

As you can see we will get the exact error as mentioned earlier.

Msg 41337, Level 16, State 100, Line 2
Cannot create memory optimized tables. To create memory optimized tables, the database must have a MEMORY_OPTIMIZED_FILEGROUP that is online and has at least one container.

As mentioned, let us add the InMemory Filegroup so that we can create the tables without a glitch:

-- Step 3 -- Add a Filegroup that is MEMORY_OPTIMIZED.
USE InMem_OLTP
GO
ALTER DATABASE InMem_OLTP
ADD Filegroup [InMem_OLTP_InMemory] CONTAINS MEMORY_OPTIMIZED_DATA
GO
ALTER DATABASE InMem_OLTP
ADD FILE (NAME = InMem_OLTP_InMemory, FILENAME = N'C:\Data\InMem_OLTP_mopt')
TO FILEGROUP [InMem_OLTP_InMemory]

Now if we create the table as mentioned in Step 2 above, there will not be any error. I don’t blame my cousin for this because he was a novice and was not able to understand what a container is when it comes to InMemory tables. Though this was a simple error that most of you would easily be able to solve, it can surely be a great source troubleshooting for people like my cousin.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – Could Not Register Service Principal Name Persists – Notes from the Field #105

$
0
0

ryanadams SQL SERVER   Could Not Register Service Principal Name Persists   Notes from the Field #105[Note from Pinal]: In this episode of the Notes from the Field series database expert Ryan Adams explains a very critical error user receive when registering service principals. Ryan is one guy who spends more time with real world issues with SQL Server than anything else. He has mastered the art of resolving complex errors and document them so easily that one can’t find anywhere else. In this blog post Ryan addresses a very interesting error related to Service Principal Name. Read the experience of  Ryan in her own words.


Have you ever seen the error below in your SQL Server log shortly after startup?  You’ll actually see two of them and you can see the difference between them in the screen shot, but here is the text.

The SQL Server Network Interface library could not register the Service Principal Name (SPN) [ MSSQLSvc/Node1.stars.com:1433 ] for the SQL Server Service.  Windows return code: 0x2098, state: 15.  Failure to register a SPN might cause integrated authentication to use NTLM instead of Kerberos.  This is an informational message.  Further action is only required if Kerberos authentication is required by authentication policies and if the SPN has not been manually registered.

Kerb Error in Log SQL SERVER   Could Not Register Service Principal Name Persists   Notes from the Field #105

So what causes this error and how can you fix it?  The first thing to note is that it is an informational message and not actually an error.  There are two scenarios in which you will see this message.

  1. The first scenario is what you see right out of the box.  SQL Server does not have the rights on a domain service account to register Service Principal Names (SPNs).  The description we see here is very clear in telling us that SQL Server could not register the required SPNs.  It even tells us the exact SPN syntax it attempted to register.  If you want to use Kerberos you have to register the SPNs manually or give the service account the right to perform the change itself.  If you decided to register them manually, then now is a good time to write down the SPNs from the description.
  2. The second scenario is a weird one that throws people off.  If you choose to manually register the SPNs on the service account and restart SQL Server, you’ll still see the same message in the log.  Now why in the world would this message even show up if you already registered the SPNs?  In fact, many folks will see this message and assume they are not using Kerberos, because the message clearly states that it could not register the SPNs.  The assumption is usually that they got the SPN syntax wrong or that the SPNs never got registered.

Just for kicks, let’s jump back over to my test server and take a look at the current connections.  Most folks will add a WHERE clause to the following query to just look at their current connection, but I’m going to caution you about that.  If you’re on the server itself, you won’t get accurate results because you end up using Named Pipes unless it’s disabled.  We are looking to see if there are any Kerberos connections at all so we don’t want to filter the result set.

SELECT * FROM sys.dm_exec_connections
--WHERE session_id = @@SPID

Kerb Connection SQL SERVER   Could Not Register Service Principal Name Persists   Notes from the Field #105

Well that’s an interesting result, huh?  I clearly have Kerberos connections despite the message I keep getting in the SQL Server log.  So why is that?  Well it comes down to the semantics of the message.  The message said it couldn’t register the SPNs and that’s true.  It couldn’t register them because you already did it.  So if you ever see this message, make sure you go look at your connections first (using the above query) to see if it is something you need to address or not.  If you see KERBEROS in the auth_scheme column, then you are all set.

If you want the message to go away completely, there is only one way to do that.  You have to give the account running the SQL Server service the permissions to change its own SPNs.  You can do that by opening the properties of the account and heading to the security tab.  You will find an account in the account list called SELF.  Grant that account “Write to Public Information”, restart the SQL Server service, and the message will disappear.  Now you’ll see a new message stating that SQL Server was able to successfully register the required SPNs.

If you are looking for more information around Kerberos and SQL Server you can visit my blog for more articles.  This is one of the many checks we perform during our WellDBA exams here at Linchpin People.  If you’re interested in taking us a look at your systems and perform a WellDBA exam, we would be happy to work with you.  You can find more information here about the Linchpin WellDBA exams.

If you want to get started with SQL Server with the help of experts, read more over at Fix Your SQL Server.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: Notes from the Field, PostADay, SQL, SQL Authority, SQL Error Messages, SQL Function, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – Unable to Start SQL Server After Patching

$
0
0

This is one of the common question which lands in my mailbox via email.

Hi Pinal,
I have an issue on my UAT environment. I was unable to start the SQL server 2008 R2 instance after applying SP1. We see the following error logged in the SQL Application log

Script level upgrade for database ‘master’ failed because upgrade step ‘sqlagent100_msdb_upgrade.sql’ encountered error 598, state 1, severity 25. This is a serious error condition which might interfere with regular operation and the database will be taken offline. If the error happened during upgrade of the ‘master’ database, it will prevent the entire SQL Server instance from starting. Examine the previous errorlog entries for errors, take the appropriate corrective actions and re-start the database so that the script upgrade steps run to completion.

Can you please help?

I have asked to share SQL Server ERRORLOG and here is what we found.

2015-12-10 12:20:20.20 spid7s      Error: 5123, Severity: 16, State: 1.
2015-12-10 12:20:20.20 spid7s      CREATE FILE encountered operating system error 5(Access is denied.) while attempting to open or create the physical file ‘C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\temp_MS_AgentSigningCertificate_database.mdf’.
2015-12-10 12:20:20.20 spid7s      Error: 5123, Severity: 16, State: 1.
2015-12-10 12:20:20.20 spid7s      CREATE FILE encountered operating system error 5(Access is denied.) while attempting to open or create the physical file ‘C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\temp_MS_AgentSigningCertificate_database.mdf’.
2015-12-10 12:20:20.20 spid7s      Error: 1802, Severity: 16, State: 4.
2015-12-10 12:20:20.20 spid7s      CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
2015-12-10 12:20:20.20 spid7s      Error: 912, Severity: 21, State: 2.
2015-12-10 12:20:20.20 spid7s      Script level upgrade for database ‘master’ failed because upgrade step ‘sqlagent100_msdb_upgrade.sql’ encountered error 598, state 1, severity 25. This is a serious error condition which might interfere with regular operation and the database will be taken offline. If the error happened during upgrade of the ‘master’ database, it will prevent the entire SQL Server instance from starting. Examine the previous errorlog entries for errors, take the appropriate corrective actions and re-start the database so that the script upgrade steps run to completion.

If you don’t know where ERRORLOG is, then refer below blog.

SQL SERVER – Where is ERRORLOG? Various Ways to Find its Location

What is “Script upgrade mode”?

Based on my understanding, when we apply any patch on SQL Server instance, the patching, upgrades the system databases (views, objects) immediately after the restart of the SQL Server Services. The stopping of the services and starting it again is a part of the patching process.  There are certain scripts (most of the times sqlagentxxx_msdb_upgrade.sql) in the patch/SP which is applied only after the SQL Server service restarts. During the Process of applying these scripts if anyone tries to connect to SQL Server instance, then he/she will get the below error message.

Login failed for user ‘LoginName’ :Reason: Server is in script upgrade mode. Only administrator can connect at this time.

I have also explained it in an earlier blog

SQL SERVER – Login Failed For User – Reason Server is in Script Upgrade Mode

So, here is our problem in this case.

CREATE FILE encountered operating system error 5(Access is denied.) while attempting to open or create the physical file ‘C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\temp_MS_AgentSigningCertificate_database.mdf’.

I asked him to check the service account for SQL Server and it was set to the Network Service. When we checked permission on the folder C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSQLSERVER\MSSQL It did not have permissions for the Network Service account. I suggested to change this to Local System account OR provide permission, so that the SQLServer.exe process account (service account) will have permission and will be able to create the temp database and let the script upgrade complete.

Once permission was given the restart was successful.

Have you ever encountered any such issue of upgrade script mode?

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – Error and Fix for Msg 1907 Cannot recreate index The new index definition does not match the constraint being enforced by the existing index

$
0
0

This particular blog post is around usage of Clustered ColumnStore Indexes and how one of my customer in a recent conversation brought this up to my notice. They were on SQL Server 2012 and were upgrading to SQL Server 2014 and were very much interested in the usage of Clustered ColumnStore Index that was introduced with SQL Server. It made a lot of sense for them because now the data is updatable with CCI implementation.

I was with the dev team and I saw an interesting error message and since I was standing there, they just turned to me and asked – “Hey Pinal, I am getting an error in SQL Server and can you help me quickly.” Not expecting this coming my way, I told them with a warm smile – please goto my blog and search for the error message. I am sure there is already the solution that you are looking forward to. I thought I solved their problem and in less than 5 seconds the developer turned around and said – “Buddy, you don’t have any blog on it.” This got me curious because he is feeding an interesting conversation that I can use it in my blog. So I immediately sat down with him and the only activity I did was to read the error message and I was convinced with the solution in hand. The message read:

Msg 1907, Level 16, State 1, Line 5
Cannot recreate index ‘PK_FactResellerSales_SalesOrderNumber_SalesOrderLineNumber’.
The new index definition does not match the constraint being enforced by the existing index.

Let me walk you through the steps of achieving the same and what was the workaround. For this example, I am creating the table with a bunch of constraints.

CREATE DATABASE ColumnStoreDemos
GO
USE ColumnstoreDemos
GO
-- Create a normal table.
IF OBJECT_ID('FactResellerSales_Trim') IS NOT NULL
DROP TABLE FactResellerSales_Trim
GO
CREATE TABLE [dbo].FactResellerSales_Trim (
[ProductKey] [int] NOT NULL
,
[OrderDateKey] [int] NOT NULL
,
[DueDateKey] [int] NOT NULL
,
[ShipDateKey] [int] NOT NULL
,
[ResellerKey] [int] NOT NULL
,
[EmployeeKey] [int] NOT NULL
,
[PromotionKey] [int] NOT NULL
,
[CurrencyKey] [int] NOT NULL
,
[SalesTerritoryKey] [int] NOT NULL
,
[SalesOrderNumber] [nvarchar](20) NOT NULL
,
[SalesOrderLineNumber] [tinyint] NOT NULL
,
CONSTRAINT [PK_FactResellerSales_SalesOrderNumber_SalesOrderLineNumber] PRIMARY KEY CLUSTERED (
[SalesOrderNumber] ASC
,[SalesOrderLineNumber] ASC
)
)
ON [PRIMARY]
GO

You can add any data if required, but now assuming you have an existing table with data already there and you create an Clustered ColumnStore Index like below, you will get the same error:

-- Now Create a Columnstore Index to convert this table into Columnstore
CREATE CLUSTERED columnstore INDEX [PK_FactResellerSales_SalesOrderNumber_SalesOrderLineNumber] ON FactResellerSales_Trim
WITH (DROP_EXISTING = ON)
GO

Msg 1907, Level 16, State 1, Line 7
Cannot recreate index ‘PK_FactResellerSales_SalesOrderNumber_SalesOrderLineNumber’. The new index definition does not match the constraint being enforced by the existing index.

The error above indicates that we have an unsupported constraint. Primary keys or foreign key constraints are not supported on a table with clustered columnstore. Given that, if we want to create a clustered columnstore, we have to drop the constraints. Are we able to create the clustered columnstore index?

ALTER TABLE FactResellerSales_Trim
DROP CONSTRAINT [PK_FactResellerSales_SalesOrderNumber_SalesOrderLineNumber]
GO
CREATE CLUSTERED COLUMNSTORE INDEX [CCI_FactResellerSales] ON FactResellerSales_Trim
GO

We can look at the successful creation of our Clustered ColumnStore Index using the query to DMVs:

SELECT * FROM sys.indexes
WHERE OBJECT_ID = OBJECT_ID('FactResellerSales_Trim')

Though this is a simple and self-explanatory error message. I thought I have not covered the same in this blog and just making sure that next time I tell someone to search – it shows up to help them. Do let me know if you ever get this error while you were migrating to the new version of SQL Server.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL Tagged: ColumnStore Index

SQL SERVER – Unable to drop login – Msg 15170, Level 16, State 1

$
0
0

Encountering error messages and solving them is something I often do. I think each and every error we encounter is validating our understanding in using the software and how we make simple mistakes.

As you might know, I do a lot of public speaking and many demos are done on my laptop. Due to which there are many unused objects in my SQL Server instance. To get my SQL instance to a clean state, I was trying to clean up the object and when I was trying to drop a login, I got below error:

DROP LOGIN [danny]
GO

job owner 01 SQL SERVER   Unable to drop login   Msg 15170, Level 16, State 1

Here is the error in text format:

Msg 15170, Level 16, State 1, Line 1

This login is the owner of 1 job(s). You must delete or reassign these jobs before the login can be dropped.

I first thought the error message is very self-explanatory to start with. The error message is clear that I need to modify the job which is owned by this login. Finding the job was easy for me as I had only few jobs. I was able to double click on each job and look at the owner in the UI.

job owner 02 SQL SERVER   Unable to drop login   Msg 15170, Level 16, State 1

On second thoughts, I felt – what if the server was some production database and had far too many jobs? What would a potential DBA do? So, if you have a server which has lots of job, opening properties of each job would not be a fun. Here is the script which can be used to find such jobs. You need to replace the login name with the appropriate name on your servers.

SELECT NAME
FROM msdb.dbo.sysjobs
WHERE owner_sid IN (
SELECT sid
FROM MASTER.sys.syslogins
WHERE NAME = 'danny'
)

job owner 03 SQL SERVER   Unable to drop login   Msg 15170, Level 16, State 1

To modify the owner either UI can be used or T-SQL. I have used below command to change the owner to sa.

USE [msdb]
GO
EXEC msdb.dbo.sp_update_job @job_name =N'foo', @owner_login_name=N'sa'
GO

After this I was able to drop the login. Have you ever been in this situation before? What did you do? Did you do something manually or wrote a similar script? Do let me know via comments.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – FIX: SQLServerAgent is not currently running so it cannot be notified of this action. (Microsoft SQL Server, Error: 22022)

$
0
0

Getting error and finding the cause is something which I like. And off late over the blogs I have shared a number of such incidents that have helped me figure out stuffs all by myself. Of course, I do my research and more often than not make things complicated because there are a number of resolutions that I find. I also make it a point to check with a few friends from Microsoft to a possible cause because it is easy to get help than walk the tough line of finding it myself.  One fine day I restarted my virtual machine and then I wanted to take a full backup of all databases before formatting the machine. As soon as I hit on execute button, as shown below, I was welcomed with an error message.

Agent Not Running 01 SQL SERVER   FIX: SQLServerAgent is not currently running so it cannot be notified of this action. (Microsoft SQL Server, Error: 22022)

Here is the error which I received.

Agent Not Running 02 SQL SERVER   FIX: SQLServerAgent is not currently running so it cannot be notified of this action. (Microsoft SQL Server, Error: 22022)

Complete text of the error message is below:

TITLE: Execute Maintenance Plan
——————————
Execution failed. See the maintenance plan and SQL Server Agent job history logs for details.
——————————
ADDITIONAL INFORMATION:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
——————————
SQLServerAgent is not currently running so it cannot be notified of this action. (Microsoft SQL Server, Error: 22022)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=12.00.2480&EvtSrc=MSSQLServer&EvtID=22022&LinkId=20476
——————————
BUTTONS:
OK
——————————

Error message is very clear. SQL Server Agent service should be running before we can execute maintenance plan. If we notice the first screen shot, it’s clear that SQL Server Agent was not running. So solution looked very simple, start the SQL Server Agent Service. It was not started by its own because it was set to manual mode.

Agent Not Running 03 SQL SERVER   FIX: SQLServerAgent is not currently running so it cannot be notified of this action. (Microsoft SQL Server, Error: 22022)

To avoid such error in the future, I change the “Start Mode” of the service, to automatic by going to the properties of the service.

Agent Not Running 04 SQL SERVER   FIX: SQLServerAgent is not currently running so it cannot be notified of this action. (Microsoft SQL Server, Error: 22022)

I also found that sometimes you would get this error even if the SQL Server Agent is running. In those cases, you need to check SQLAgent.out file to check if it’s started completely.

Something SQLAgent.out would show ONLY below message

Waiting for SQL Server to recover databases…

If you are running in that issue, please have a look at https://support.microsoft.com/en-us/kb/2640027 to get a fix for the issue.

Have you even fixed such simple issues? The error messages over the ages have become obvious and very helpful too.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Backup and Restore, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – FIX: sp_rename error Msg 15225 – No item by the name of ‘%s’ could be found in the current database

$
0
0

Few days back I have written blog containing script for removing space in column name using sp_rename. In case you missed, I am listing them below for quick reference.

SQL SERVER – Script: Remove Spaces in Column Name in All Tables

SQL SERVER – How to Rename a Column Name or Table Name

While playing with sp_rename, I came across an interesting error message and I looked into the code of sp_rename to understand the issue. Here is the error message which I received.

Msg 15225, Level 11, State 1, Procedure sp_rename, Line 387
No item by the name of ‘TableTwo’ could be found in the current database ‘SQLAuthority’, given that @itemtype was input as ‘(null)’.

For simplification, I have made up below script to explain the error.

CREATE DATABASE SQLAuthority
GO
USE SQLAuthority
GO
CREATE SCHEMA HR
GO
CREATE TABLE dbo.TableOne (ID INT PRIMARY KEY)
GO
CREATE TABLE HR.TableTwo (ID INT, FName VARCHAR(100))
GO
sp_rename 'TableOne', 'TableOne_renamed' -- This works
GO
sp_rename 'TableTwo','TableTwo_renamed' -- This fails

If we look at sp_helptext sp_rename we would see below at line 387 (as shown in error)

-- was the original name valid given this type?
IF (@objtype IN ('object','userdatatype') AND @CountNumNodes > 3)
BEGIN
COMMIT TRANSACTION
RAISERROR
(15225,-1,-1,@objname, @CurrentDb, @objtypeIN)
RETURN 1
END

I looked at beginning of sp_rename the stored procedure and found some documentation there, there were some good rules listed.

  • To rename a table, the @objname (meaning OldName) parm can be passed in totally unqualified or fully qualified.
  • The SA or DBO can rename objects owned by lesser users, without the need for SetUser.
  • The Owner portion of a qualified name can usually be passed in in the omitted form (as in MyDb..MyTab or MyTab). The typical exception is when the SA/DBO is trying to rename a table where the @objname is present twice in sysobjects as a table owned only by two different lesser users; requiring an explicit owner qualifier in @objname.
  • An unspecified Owner qualifier will default to the current user if doing so will either resolve what would otherwise be an ambiguity within @objtype, or will result in exactly one match.
  • If Database is part of the qualified @objname, then it must match the current database. The @newname parm can never be qualified.
  • Here are the valid @objtype values. They correspond to system tables which track each type: ‘column’  ‘database’  ‘index’  ‘object’  ‘userdatatype’  ‘statistics’
  • The @objtype parm is sometimes required. It is always required for databases.  It is required whenever ambiguities would otherwise exist.  Explicit use of @objtype is always encouraged.

Parms can use quoted_identifiers.  For example: Execute sp_rename ‘amy.”his table”‘,'”her table”‘,’object’

So, we are getting error because our table TableTwo is not in the default schema which is dbo. The solution is very simple: we need to qualify the name of the table with the schema name as shown below.

sp_rename 'HR.TableTwo','TableTwo_renamed' -- Now This would work

While reading the ruled listed in stored procedure, I realized that same error can also come if there is a dot in table name. we need to use [] around such tables. Here is an example

USE SQLAuthority
GO
CREATE TABLE [Name.With.dot] ( i INT)
GO
sp_rename 'Name.With.dot', 'New_Name.With.dot' -- would fail
GO
sp_rename '[Name.With.dot]', 'New_Name.With.dot' -- would work
GO

Hope this would help. Do let me know if you have used something like this before in your environments. Feel free to share via comments below.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – SSMA Error: System.Data.OracleClient requires Oracle client software version 8.1.7 or greater

$
0
0

I work majorly on SQL Server but rarely do I get a chance to work on Oracle in general. When some of the error messages reach my inbox, I get intrigued to why some occur. This error message was an outcome of that exploration. When I got this error message, I said I have no clue to why this is happening and I asked if it was anyway related to SQL Server?

The gentleman wrote back stating this was coming from a SQL Server tool and since they were doing a migration using SQL Server Migration Assistant Tool (SSMA). Now that statement got me interested because it was coming from a SQL Server migration.

I went ahead to asked about the environment to get a better hang of things. I asked the Oracle client version they were running. They responded saying, though we are running Oracle Client 9.2.0.8 we are getting an Oracle 8.1.7 or higher error strangely.

Following message is being displayed on the console:

Migrating data…
Analyzing metadata…
Preparing table SYSTBL.CMN_TBL_CUST_…
Preparing data migration package…
Starting data migration agent…
Starting data migration…
Exception during processing: System.Data.OracleClient requires Oracle client software version 8.1.7 or greater.
Data migration complete.

0 table(s) successfully migrated.
0 table(s) partially migrated.
1 table(s) failed to migrate.

After a going through the complete problem statement. I saw that it was working on a local server, but was failing when it was called from remote server.

Reason After Investigation

The Oracle client provider is not there on the remote SQL Server. If working with remote machines, the Oracle Client provider should be present on the remote SQL Server.

I sent a mail to – Install the Oracle Client provider on the remote SQL Server and verify the data migration. As SSMA doesn’t have any limitation to work with remote SQL Server. Also as part of the installation, asked to check if the extension packs were installed on the remote servers.

After this exercise, I felt there was some good learning for me too and worth a share here. I am sure you are much more experienced in working with SSMA but feel free to let me know if I missed anything.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – FIX: Msg 3169, Level 16, State 1 – The database was backed up on a server running version. That version is incompatible with this server.

$
0
0

At this rate, I think I am going to exhaust the whole error set available inside SQL Server. I am glad that I am able to get into unique situations and then resolve them too. And this is more of a diary of the error messages I am getting into. I was playing with my Demo database on SQL Server 2016. Once done, I started restore from the previous copy.  But is failed with below error:

Msg 3169, Level 16, State 1, Line 1
The database was backed up on a server running version 13.00.0801. That version is incompatible with this server, which is running version 12.00.4213. Either restore the database on a server that supports the backup, or use a backup that is compatible with this server.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.

Then I realized that I have taken back-up from 13.00.0801 which is SQL Server 2016 and I was trying to restore on 12.00.4213 which is SQL Server 2014. Error message shows both versions, source and destination.

So, it’s is clear that there is no direct way to downgrade from a higher version to a lower version and it would fail with error message. Why? When an instance of SQL is upgraded, not only do the binaries for the database engine change, the schema level for the databases also changes. So it would not be possible to attach a database with a higher schema level to an instance on a lower version of SQL.

What can be done? One possible approach is to manually export and import the data. You can follow the below steps:

Create empty database

  • In Object Explorer, expand Databases, right-click a database, point to Tasks, and then click Generate Scripts. Follow the steps in the wizard to script the database objects.
  • On the Choose Objects page, select “Script entire database and database objects”.
  • On the Set Scripting Options page, select Save scripts to a specific location.
  • select the Advanced button; under “Types of data to script” select “Schema Only” and under “Script for server version” select “SQL Server 2008” (or appropriate version)
  • Click on Next and finish to complete the process.
  • Now you can use the generated script file and execute this against the SQL server 2008 instance to create the complete database schema without data.

Move the data

To move the data, you have a couple of options but all of these are a bit tricky.

  1. Script out the data exactly the way described in the above steps, just by selecting “Types of data to script” as “Data Only”.

Or

  1. Script out the data for every object individually one by one instead of complete database if you have a large database.

Or

  1. BCP to export the data into files and then again use BCP to import the data back into the tables on to the new server.

In short, moving back-up from higher to lower version is not possible. Only option we have is to move the data using the ways described above. Do you know any more ways?

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – FIX: Msg 7395, Level 16, State 2 – Unable to start a nested transaction for OLE DB provider

$
0
0

While playing with linked server from SQL Server to SQL Server, I faced few errors and fixed them as well. It has become a custom to get errors working with Linked Servers almost every time. I personally thought it is worth blogging because I didn’t find any single blog having the cause and solution explained in detail.

Here is the query which I was running on SMALLSERVER which has linked server to BIGSERVER. It is a four part naming having format for ServerName.DatabaseName.SchemaName.ObjectName.  Basically, query is updating a value for a table called dbo.Employee in database called SQLAuthority on server BIGSERVER.

BEGIN DISTRIBUTED TRANSACTION
UPDATE
BIGSERVER.SQLAuthority.dbo.Employee
SET SALARY = 'Y'
WHERE ID = 5
COMMIT TRANSACTION

It was failing with below error message.

OLE DB provider “SQLNCLI11” for linked server “BIGSERVER” returned message “The transaction manager has disabled its support for remote/network transactions.”.
Msg 7391, Level 16, State 2, Line 2
The operation could not be performed because OLE DB provider “SQLNCLI11” for linked server “BIGSERVER” was unable to begin a distributed transaction.

Here is the important information in error message. “The transaction manager has disabled its support for remote/network transactions” which basically indicates issue with setting of DTC. To fix that, we need to go to Start > Run > dcomcnfg and open below interface (this is Windows 2012 R2 Sevrer)

dtc 01 SQL SERVER   FIX: Msg 7395, Level 16, State 2 – Unable to start a nested transaction for OLE DB provider

You can also launch the same interface from “Control Panel” > “Administrative Tools > Component Services”. Follow the screen shot and open “Properties” and go to security tab and change setting as below.

dtc 02 SQL SERVER   FIX: Msg 7395, Level 16, State 2 – Unable to start a nested transaction for OLE DB provider

Once changed, restart the DTC Service. Now, I got below error.

OLE DB provider “SQLNCLI11” for linked server “BIGSERVER” returned message “Cannot start more transactions on this session.”.
Msg 7395, Level 16, State 2, Line 3
Unable to start a nested transaction for OLE DB provider “SQLNCLI11” for linked server “BIGSERVER”. A nested transaction was required because the XACT_ABORT option was set to OFF.

Above error also tells the action needed – we need to enable the XACT_ABORT in the transaction. Here is the modified version of the query

SET XACT_ABORT ON
GO
BEGIN DISTRIBUTED TRANSACTION
UPDATE
BIGSERVER.SQLAUTHORITY.DBO.EMPLOYEE
SET SALARY = 'Y'
WHERE ID = 5
COMMIT TRANSACTION

And that worked for me and it updated the value on remote server.

You must have also encountered some errors while using linked server? Share the problem and solution via comments section.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – System.IO.FileNotFoundException: Could not load file or assembly

$
0
0

In a recent R&D operation, I was trying to use some SQLCLR assembly as part of the installation process. It was not easy but it got me into a mess that I thought was worth debugging. One of the interesting issues which I faced recently was to deploy a .net assembly which was failing with an error. I thought the third party .msi and the .dlls they shared must have gone wrong. I wanted to understand what was going wrong here to get a better feeler. The Error mentioned as part of the stack was:

Error: System.IO.FileNotFoundException: Could not load file or assembly ‘Microsoft.SqlServer.BatchParserClient, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91’ or one of its dependencies. The system cannot find the file specified.
File name: ‘Microsoft.SqlServer.BatchParserClient, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91’
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection)
at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.Load(String assemblyString)
at Microsoft.SqlServer.Management.Common.ServerConnection.GetStatements(String query, ExecutionTypes executionType, Int32& statementsToReverse)
at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType)

Whenever there are such errors, we need to look at a few things.

  1. What is the error?
  2. What is assembly name?
  3. What is the version of the assembly?

Here is what we have in error message. I have highlighted them as well.

  1. IO.FileNotFoundException: Could not load file or assembly
  2. SqlServer.BatchParserClient
  3. Version=12.0.0.0

The assemblies are stored in C:\Windows\Assembly folder and they are shown as below

assembly 01 SQL SERVER   System.IO.FileNotFoundException: Could not load file or assembly

Two things to be noted in the screenshot. Version and Processor Architecture. The screenshot is NOT from the same machine where we received the error. On the problem machine, we were not seeing the needed assembly.

I have downloaded and installed “Microsoft® SQL Server® 2014 Shared Management Objects” (SMO) from https://www.microsoft.com/en-us/download/details.aspx?id=42295 and after that I was able to get the assembly and the code worked. Microsoft SQL Server Management Objects require – Microsoft SQL Server System CLR Types, that was also available on the same page.

I am sure most of us sometimes don’t get on this path of exploration, but I felt this was a great learning for me to explore. Do let me know if you did debug anything on these lines at your environments via the comments.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – FIX: Msg 4335, Level 16, State 1 – The specified STOPAT time is too early

$
0
0

While trying to prepare for a demo, I ran into some interesting error. When I searched for error on the internet, there were not many clear answers so I thought of sharing on my blog. Actually, my demo was all about point in time restore feature of SQL Server. I was trying something similar given in my earlier blog.

SQL SERVER – A Quick Script for Point in Time Recovery – Back Up and Restore

Here is the error which I received

Msg 4335, Level 16, State 1, Line 3
The specified STOPAT time is too early. All or part of the database is already rolled forward beyond that point.
Msg 3013, Level 16, State 1, Line 3
RESTORE LOG is terminating abnormally.
The error was not very clear so I checked my script and found the mistake. I was giving incorrect time in STOPAT. To understand it better, I have written a small script.

/*Clean up*/
USE [master]
GO
ALTER DATABASE [SQLAuthority] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
DROP DATABASE [SQLAuthority]
GO

/*create database*/
CREATE DATABASE [SQLAuthority]
GO
USE [SQLAuthority]
GO
CREATE TABLE FIRST(I INT)
GO
BACKUP DATABASE [SQLAuthority] TO  DISK = N'E:\Backup\SQLAuth_1.bak' WITH FORMAT, INIT,  NAME = N'SQLAuthority-Full Database Backup 1', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO
SELECT GETDATE() 'Approx Time of first full backup'
GO
CREATE TABLE SECOND(I INT)
GO
WAITFOR delay '00:00:10'
GO
BACKUP DATABASE [SQLAuthority] TO  DISK = N'E:\Backup\SQLAuth_2.bak' WITH FORMAT, INIT,  NAME = N'SQLAuthority-Full Database Backup 2', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO
SELECT GETDATE() 'Approx Time of second full backup'
GO
CREATE TABLE THIRD(I INT)
GO
WAITFOR delay '00:00:10'
GO
BACKUP LOG [SQLAuthority] TO  DISK = N'E:\Backup\SQLAuth_3.bak' WITH FORMAT, INIT,  NAME = N'SQLAuthority-Log Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO
SELECT GETDATE() 'Approx Time of log backup'
GO

Here are backups taken via about the script.

  1. Full back up – 1: SQLAuth_1.bak
  2. Full back up – 2: SQLAuth_2.bak
  3. Transaction Log back up: SQLAuth_3.bak

The error would come if I restore SQLAuth_3.bak on top of SQLAuth_2.bak BUT specify time before the SQLAuth_2.bak. I have modified the script to make sure you can understand the cause.

Here is the output of my SQL instance.

restore err 01 SQL SERVER   FIX: Msg 4335, Level 16, State 1   The specified STOPAT time is too early

If I run below command, I would get the same error which I explained earlier.

USE [master]
GO
IF (DB_ID('SQLAuthority') IS NOT NULL)
BEGIN
ALTER DATABASE
[SQLAuthority] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
DROP DATABASE
[SQLAuthority]
END
GO
USE [master]
RESTORE DATABASE [SQLAuthority] FROM  DISK = N'E:\Backup\SQLAuth_2.bak' WITH  FILE = 1,  NORECOVERY,  NOUNLOAD,  STATS = 5
RESTORE LOG [SQLAuthority] FROM  DISK = N'E:\Backup\SQLAuth_3.bak' WITH  FILE = 1,  NOUNLOAD,  STATS = 5, STOPAT = '2016-01-17 22:05:50.593' --This time has to be modified
GO

In the above example, STOPAT is done at the time when the first full backup was taken. You have to replace the time as per your script execution and give any time before second output.

I am sure such small scripts make concepts very clear. Have you ever encountered any interesting restore error? Please share via comments.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding

$
0
0

Some errors when encountered take most of us for a spin. In this category the error related to “Timeout” surely falls. If you are a web developer and receive the same there are a hundred combinations why this can possibly happen. The web results can sometimes lead us in completely opposite direction because we have not analyzed the root cause for this. I sincerely urge everyone when working with generic errors, look for specific symptoms and then use the trick of eliminating one after the other before a final solution can be arrived.

This is one of the most common error which you would hear from web developers. Here is a typical error raised shown on website.

timeout 01 SQL SERVER   Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding

[SqlException (0x80131904): Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1948826
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4844747
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
System.Data.SqlClient.SqlDataReader.get_MetaData() +83
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +297
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +954
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
System.Data.Common.DbCommand.ExecuteReader() +12
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +332

It’s very clear message that the timeout duration specified for the operation is completed but actual work didn’t finish. The error can come because of two kind of timeouts:

  1. Query Timeout: The default value for web application or .NET application is generally 30 seconds. If any request is in progress and it couldn’t complete within the timeout period, we would again see an error.
  1. Connection Timeout: The default value of connection timeout is generally 15 seconds. Within this time if connection can’t be made, we would see the error.

Next obvious question is – what should we do if we see such error?

Query timeout: The reasons a command/query runs longer than expected is commonly due to blocking or the need for query/index tuning or both.  A quick way to check for blocking to to run sp_who2 while the query is running.  The BlkBy column will show the SPID of the blocking connection if the query is blocked.  For slow running query, you may want to check the execution plan to verify that the statement is touching the rows which are needed.  For example, if your intent is to Select a single row but you see a scan operator, that is a strong indication that you need to perform index or query tuning or need to update statistics.

Here is the over-simplified repro of query timeout done via SQL Server Management Studio (SSMS). The default value of query timeout in SSMS in 0 (which is infinite) Tools > Options in menu would open below window where the value can be set, if needed.

timeout 02 SQL SERVER   Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding

For demo purpose, I have changed it to 10 seconds. In one query window we would run below command

USE tempdb
GO
CREATE TABLE foo (i INT)
BEGIN TRAN
INSERT INTO
foo VALUES (1)
GO

In second query window, we can run below command

SELECT * FROM tempdb..foo

and we can see below after 10 seconds.

timeout 02 1 SQL SERVER   Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding

It is important to note the error number. It is not an SQL Server error but error by client. The query waited for 10 seconds because we caused blocking. If we don’t set timeout value in SSMS, they query would run forever because default timeout is zero.

Connection timeout: This I can’t reproduce by management studio query easily. On a slow network, you can easily reproduce it by reducing the connection timeout to a lower value. In SSMS. You need to click on Options on login page as shown below:

timeout 03 SQL SERVER   Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding

and change the value in Connection Properties tab.

timeout 04 SQL SERVER   Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding

On the same screen we can also set query timeout (shown as execution time-out)

If you are seeing same errors in your web application, then you need to check configuration file (normally known as web.config file). The same parameters (query and connection timeout) can be set in connection string of the application as well.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – Add failover cluster node fails with “number of cluster nodes supported for edition”

$
0
0

A lot of my blog readers contact me via comments and I try my best to reply to all of them. Sometimes issue is so interesting that I ask them to contact via email. This blog is result of such an interaction.

Asif (name anonymized) was trying to Add third node to SQL Server failover cluster instance (FCI). He was able to add second node without a problem. But when he was trying to add the third node, there seemed to be an error. FCI related errors and troubleshooting are sometimes complex and I try to keep such interactions on face-to-face troubleshooting only. Here I possibly felt there was something fundamentally wrong in the understanding. He also told that this is enterprise edition media. So, I asked him to share the screenshot and setup logs:

AddNode 01 SQL SERVER   Add failover cluster node fails with number of cluster nodes supported for edition

Here is the snip from the setup logs.

(14) 2016-01-10 15:44:24 Slp: Executing rules engine…
(14) 2016-01-10 15:44:24 Slp: Start rule execution, total number of rules loaded: 18
(14) 2016-01-10 15:44:24 Slp: Initializing rule      : Number of cluster nodes supported for edition
(14) 2016-01-10 15:44:24 Slp: Rule is will be executed  : True
(14) 2016-01-10 15:44:24 Slp: Init rule target object: Microsoft.SqlServer.Configuration.SetupExtension.NumberOfNodesFacet
(14) 2016-01-10 15:44:24 Slp: Rule ‘Cluster_NumberOfNodes’ edition Standard allows 2 cluster nodes.
(14) 2016-01-10 15:44:24 Slp: Rule ‘Cluster_NumberOfNodes’ detected 2 cluster nodes.
(14) 2016-01-10 15:44:24 Slp: Evaluating rule        : Cluster_NumberOfNodes
(14) 2016-01-10 15:44:24 Slp: Rule running on machine: SQLNode03
(14) 2016-01-10 15:44:24 Slp: Rule evaluation done   : Failed
(14) 2016-01-10 15:44:24 Slp: Rule evaluation message: This SQL Server edition does not support the installed number of cluster nodes. To continue, remove nodes and then complete cluster installation.
(14) 2016-01-10 15:44:24 Slp: Send result to channel : RulesEngineNotificationChannel

I saw something familiar, where it said “Standard” – now that looked basic validation has failed. I have asked to run below query in SQL Server Management Studio

SELECT SERVERPROPERTY('Edition')

OR share the ERRORLOG

SQL SERVER – Where is ERRORLOG? Various Ways to Find its Location

Here is what we saw in ERRORLOG

2016-01-18 14:55:48.430 Server       Microsoft SQL Server 2014 – 12.0.2548.0 (X64)
Jun  8 2015 11:08:03
Copyright (c) Microsoft Corporation
Standard Edition (64-bit) on Windows NT 6.3 <X64> (Build 10240: )

As I was guessing earlier, it is a Standard edition which allows only 2 nodes in FCI. So, I asked him to contact to the application team and get media for enterprise edition. He upgraded Standard to Enterprise and then he was able to add node.

If we closely look at setup logs, its clearly mentioned there. Have you ever encountered any such simple errors in SQL Setup and logs have helped you?

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL Tagged: Cluster

SQL SERVER – Fixing Annoying Network Binding Order Error – Notes from the Field #112

$
0
0

ryanadams SQL SERVER   Fixing Annoying Network Binding Order Error   Notes from the Field #112[Note from Pinal]: In this episode of the Notes from the Field series database expert Ryan Adams explains a very critical error user receive when binding network error. Ryan is one guy who spends more time with real world issues with SQL Server than anything else. He has mastered the art of resolving complex errors and document them so easily that one can’t find anywhere else. In this blog post Ryan addresses a very interesting error related to binding network error. Read the experience of  Ryan in her own words.


One of the more common errors I see when setting up a Windows cluster (usually in preparation for a SQL Server Failover Cluster Instance or a SQL Server Availability Group) is regarding an incorrect network binding order.  You will see this presented as a warning in the Cluster Validation Report.  There are actually two different errors that I have seen with the first being very common and the second being more rare.

Error 1

Rule “Network binding order” generated a warning.

The domain network is not the first bound network.  This will cause domain operations to run slowly and can cause timeouts that result in failures.  Use the Windows network advanced configuration to change the binding order.

What this error means is that the network card used to connect to your domain network is not at the top of the network binding order.  The fix for this is usually pretty easy because we just need to go into Control Panel…Network and Internet…Network Connections and make the change.  Once we get there we need to identify which NIC card is connected to the domain network and that can be seen in the “Network Category” column shown in the screen shot below.  You’ll notice that I have labeled my connections Public and Private and they both show “Domain Network”.  If you are configuring a multi-subnet cluster you will see the exact same thing, but if your cluster is on a single subnet the Private network connection will show “Public Network”.  So in a single subnet it’s the one labeled “Domain Network” that you are targeting and in a multi-subnet cluster it’s your Public connection you are targeting.

112 1 SQL SERVER   Fixing Annoying Network Binding Order Error   Notes from the Field #112

In order to change the network binding order we need to go into the advanced settings.  Starting in Windows 2008 this option is hidden.  If you don’t see it hit ALT on your keyboard and the Advanced option pointed out in the previous screen shot will appear.  We need to select that and then go to Advanced Settings.  You will now be presented with the Advanced Settings box shown below.  In the screen shot you will see that my Public network is the second in the binding order and we need to move it to the top by selecting it and hitting the up arrow.  Click OK and go run Cluster validation again to see if it is resolved.

112 2 SQL SERVER   Fixing Annoying Network Binding Order Error   Notes from the Field #112

There is a chance that either your domain network was already at the top of the binding order, or you ran Cluster Validation again and it failed with the same error.  If that is the case then you either have a ghost network card (can be caused by NIC changes or driver changes) or the Microsoft Failover Cluster Virtual Adapter is bound before the domain network.  These adapters are not show in the GUI, but can be found in the registry and other places like the ipconfig /all command.

Unfortunately the network binding order in the registry uses GUIDs instead of friendly names, so we’ll have to do some translating to find and move the domain network to the top.  The first thing we will do is go figure out what the GUID of the domain network NIC is by running the following command from a command prompt.

WMIC Nicconfig Get Description, SettingID

You’ll remember that I renamed my NIC cards to be called Public and Private, but that’s the friendly name and not what will be returned from WMIC.  WMIC returns what is in the “Device Name” column from the very first screen shot above.  In my case it is called “Intel(R) PRO/1000 MT Desktop Adapter”.  You can see this pointed out in the screen shot below where we can see the output of WMIC in the command window.  Note that the GUID starts with A7.

112 3 SQL SERVER   Fixing Annoying Network Binding Order Error   Notes from the Field #112

Now we just need to open Regedit and head to HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Linkage\Bind.  That’s right, we’re getting down and dirty now so make sure you know what you are doing and above all else backup your registry before you make any changes.  Mistakes in the registry can be costly and destroy a system so proceed with caution because from here on out the responsibility lies solely with you…not me.  In the screen shot above you can see that my Public Domain Network is next to the last in the list and we need it to be at the top.  As an aside, I have also pointed out where the Microsoft Failover Cluster Virtual Adapter is located since I see this listed above the Public network from time to time.

The fix here is to cut the GUID for the Public Domain Network that starts with A7 and paste it at the top of the list.  Now we can go run Cluster Validation and life should be good unless you get the second error we’ll talk about now.

Error 2

Note that the error message is the same error you got above.  However, it’s a completely different issue.  So let’s say you verified the above and that the domain network is the first in the list, but the error persists.  Go Look in the following file and search for “IsDomainInCorrectBindOrder” to find the warning in the log file.

C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\Log\"Newest Log File Folder By Date"\Detail.txt

Here is a sample of the section you are looking for.

Init rule target object: Microsoft.SqlServer.Configuration.SetupExtension.NetworkBindingFacet
NetworkBindingFacet: Looking up network binding order.
NetworkBindingFacet: Network: ‘Production Team’ Device: ‘\Device\{0BF4D354-E6E9-480C-91CF-DC598282C4C1}’ Domain: ‘LITWARE.COM’ Adapter Id: ‘{0BF4D354-E6E9-480C-91CF-DC598282C4C1}’
NetworkBindingFacet: Network: ‘Local Area Connection’ Device: ‘\Device\{4DB91193-72F1-4713-A938-EB73F27CFEC8}’ Domain: ” Adapter Id: ‘{4DB91193-72F1-4713-A938-EB73F27CFEC8}’
NetworkBindingFacet: Network: ‘Heart Beat’ Device: ‘\Device\{5AC63784-8088-40F7-93C8-37F9CD03D445}’ Domain: ” Adapter Id: ‘{5AC63784-8088-40F7-93C8-37F9CD03D445}’
NetworkBindingFacet: Network: ‘BackUp Network’ Device: ‘\Device\{52AEDCB0-9E8E-4243-9D5D-ED86E602DF23}’ Domain: ” Adapter Id: ‘{52AEDCB0-9E8E-4243-9D5D-ED86E602DF23}’
IsDomainInCorrectBindOrder: The top network interface ‘Production Team’ is bound to domain ‘LITWARE.COM’ and the current domain is ‘CONTOSO.COM’.
Evaluating rule : IsDomainNetworkTopOfBindings
Rule running on machine: Server1
Rule evaluation done : Warning
Rule evaluation message: The domain network is not the first bound network. This will cause domain operations to run slowly and can cause timeouts that result in failures. Use the Windows network advanced configuration to change the binding order.
Send result to channel: RulesEngineNotificationChannel

The issue here is that the server is joined to the LITWARE.COM domain, but the current domain is that of the currently logged in user which happens to be CONTOSO.COM.  Another way to say this is that the server is joined to the LITWARE.COM domain, but you logged with a user account from the CONTOSO.COM domain to create the cluster.  From a domain perspective these are completely different domains that have been trusted and it’s possible that they are in different forests too, but again they are trusted.  Technically this configuration is correct as the public/domain joined network is indeed at the top of the list.  You have two choices here.  You can safely ignore this warning or you can log out and back in with a user in the LITWARE.COM domain.

If you are looking for more information around Clustering, AlwaysOn Failover Clusters, or AlwaysOn Availability Groups you can visit my blog at http://www.ryanjadams.com/category/sql-server/alwayson-ag/ for more articles.  Setting up clusters to support SQL Server is complicated, but can yield great benefits if done correctly.  If you’re setting up a new cluster or interested in having us take a look at your current systems we would be happy to work with you.  You can find more information on the services we provide and contact us on our website http://www.linchpinpeople.com/.

If you want to get started with SQL Server with the help of experts, read more over at Fix Your SQL Server.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: Notes from the Field, PostADay, SQL, SQL Authority, SQL Error Messages, SQL Function, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

SQL SERVER – 2016 Error Reasons: Msg 10778, Level 16 Foreign key relationships between memory optimized tables and non-memory optimized tables are not supported

$
0
0

When I was writing the blog SQL SERVER 2016 – InMemory OLTP support for Foreign Key, it felt like a great addition to SQL Server. I felt there must be something that I might be missing as the obvious. I was not wrong in that feeling too. One of my blog readers pinged to say they were getting a strange error that Foreign Key was not supported. This is how I figured out what was going wrong.

Pinal: Hi buddy.

Reader: Thanks for the ping.

Pinal: Not an issue. It is my pleasure.

Reader: As you know, based on your last week blog. I was experimenting something.

Pinal: Go on, anything related to this blog is something I am all ears.

Reader: I am getting an error.

Pinal: Which Blog are we talking?

Reader: It is the OLTP support for Foreign keys.

Pinal: Oh that one. That was a simple blog. What is the error?

Reader: It say it is not supported.

Pinal: Are you sure you are on a SQL Server 2016 version when you are trying that? It wouldn’t work on a SQL Server 2014 edition.

Reader: I am on the latest SQL Server 2016 version. But I was experimenting and got this error.

Pinal: What sort of experiment? What error are we talking?

Reader: The error states: “Foreign key relationships between memory optimized tables and non-memory optimized tables are not supported.”

Pinal: No wonder. It is quite possible. Now I get it. You didn’t run the script as-is but changed one of them to Disk based tables.

The reader had changed the blog SQL SERVER 2016 – InMemory OLTP support for Foreign Key, and edited the portion of creation of table. It was as below:

CREATE TABLE Products
(
ProductID INT CONSTRAINT pk_products_pid PRIMARY KEY,
ProductName VARCHAR(25)
);
GO
CREATE TABLE ProductSales
(
SalesID INT CONSTRAINT pk_productSales_sid PRIMARY KEY NONCLUSTERED HASH (SalesID) WITH (BUCKET_COUNT = 10000),
ProductID INT CONSTRAINT fk_productSales_pid FOREIGN KEY REFERENCES Products(ProductID),
SalesPerson VARCHAR(25)
)
WITH ( MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA);
GO

As you can see the Products table was made as normal Disk based table while the transactions table was made as InMemory OLTP table. I am sure this is the strategy for most of the users wherein they will be creating normal tables for their masters and using the InMemory capability for the transactions. At the moment we will receive the error:

Msg 10778, Level 16, State 0, Line 3
Foreign key relationships between memory optimized tables and non-memory optimized tables are not supported.
Msg 1750, Level 16, State 0, Line 3
Could not create constraint or index. See previous errors.

I am sure the SQL Server product team is looking into this and maybe in subsequent versions there will be a provision for the same. But how important are these capabilities in your opinion? Do you want relationship management from InMemory and Disk based tables? Do let me know via the comments.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL
Viewing all 134 articles
Browse latest View live