SQL SERVER – Connecting to Server Using Windows Authentication by SQLCMD

Recently I got a call from an old friend I used to call “DJ”. Here is the exact conversation we had:

DJ: Pinal, your SQL Server does not like me.
Pinal: Possible, no one likes you!
DJ: I am serious…
Pinal: I am too…
DJ: No really – be serious.
Pinal: Well, you started it, tell me your problem.
DJ: This new SQLCMD thingy does not work. Everytime I am using my username and password it does not log me in.
Pinal: Have you tried with SSMS?
DJ: No, but it works fine. I just logged in my machine using it.
Pinal: Oh, are you trying to login using your Windows Authentication Username and Password?
DJ: Does it matter? I am the admin on my box.
Pinal: It does matter. Tell me your script.
DJ: sqlcmd -S .\sqlent1 -U username -P password. And then I’d been given “error 18456 – login failed for user.”
Pinal: Try sqlcmd -S .\sqlent1 -E
(After a while)
DJ: It works! So you still know SQL Server, what’d you say?
Pinal: I say  you still do not know SQL Server (evil laugh)
DJ: (extends the evil laugh)

Well, it was simple. He was trying to connect to SQL Server which was installed on his local box, where he was the admin. In this case, he can use a simpler script. This is a very specific situation and it was not the production server’s fault. Here is a copy of the scenario on my personal laptop.

Watch SQL in Sixty Seconds video to Resolve Connection Error:

Watch the video on the same subject:

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

SQL SERVER – Fix : Error : 17892 Logon failed for login due to trigger execution. Changed database context to ‘master’.

I had previously written two articles about an intriguing observation of triggers online.

SQL SERVER – Interesting Observation of Logon Trigger On All Servers

SQL SERVER – Interesting Observation of Logon Trigger On All Servers – Solution

If you are wondering what made me write yet another article on logon trigger then let me tell you the story behind it. One of my readers encountered a situation where he dropped the database created in the above two articles and he was unable to logon to the system after that.

Let us recreate the scenario first and attempt to solve the problem.

/* Create Audit Database */
CREATE DATABASE AuditDb
GO
USE AuditDb
GO
/* Create Audit Table */
CREATE TABLE ServerLogonHistory
(SystemUser VARCHAR(512),
DBUser VARCHAR(512),
SPID INT,
LogonTime DATETIME)
GO
/* Create Logon Trigger */
CREATE TRIGGER Tr_ServerLogon
ON ALL SERVER FOR LOGON
AS
BEGIN
INSERT INTO
AuditDb.dbo.ServerLogonHistory
SELECT SYSTEM_USER,USER,@@SPID,GETDATE()
END
GO
/* Dropping Database AuditDB */
/* Please note login to Server again will
Produce Errors */
USE master
GO
DROP DATABASE AuditDB
GO

After the database is dropped and we try to login again the following error will be displayed.

Logon failed for login ‘SQL\Pinal’ due to trigger execution.
Changed database context to ‘master’.
Changed language setting to us_english. (Microsoft SQL Server, Error: 17892)

This error could have been evaded if the Trigger was dropped prior to dropping database.

USE master
GO
DROP TRIGGER Tr_ServerLogon ON ALL SERVER
GO

Now, it will not be possible to logon to the database using SQL Server Management Studio. The only way to fix this problem is using DAC. Read more details about DAC  Using a Dedicated Administrator Connection to Kill Currently Running Query. Now let us take a look at the example in our case where I am using windows authentication to logon to the system.

Connect SQL Server using sqlcmd and -A option, which will establish DAC. Running the following command on command prompt will allow you to login once again in the database. I am specifying argument -d master which will directly enable me to logon to master database when DAC is connected.

C:\Users\Pinal>sqlcmd -S LocalHost -d master -A
1> DROP TRIGGER Tr_ServerLogon ON ALL SERVER
2> GO

I hope my explanation on logon triggers, DAC, and sqlcmd is clear to everyone. Let me have your thoughts about my present article.

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

SQL SERVER – Find All Servers From Local Network – Using sqlcmd – Detect Installed SQL Server on Network

I recently had requirement to create list of all the SQL Server on local network. I remembered that I had written similar script a year ago SQL SERVER – Script to Find SQL Server on Network. When I looked at it, I realize that I had written it for SQL Server 2000 and used “isql” utility, which is deprecated now. I quickly wrote down updated script using “sqlcmd”. Command “osql” still works in SQL Server 2008.

Go to command prompt and type in “osql -L” or “sqlcmd -L”.

Note one change between osql and sqlcmd is that osql has additional server “(local)” listed in the servers list which is in fact same as “SQL” in my case. While “sqlcmd” gives accurate result.

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

SQL SERVER – sqlcmd – Using a Dedicated Administrator Connection to Kill Currently Running Query

People are judged from their questions and not their answers. I received wonderful question the other day.

How sqlcmd can be used along with currently running query script posted on your blog?

Please read following two posts before continuing this article as they cover background of this article.

SQL SERVER – Interesting Observation – Using sqlcmd From SSMS Query Editor

SQL SERVER – Find Currently Running Query – T-SQL

If due to a long running query or any resource hogging query SQL Server is not responding sqlcmd can be used to connect to the server from another computer and kill the offending query. SQL Server provides a special diagnostic connection which allows administrators to access SQL Server when standard connection is not possible. Except very extreme situations dedicated administrator connection (DAC) is always successful.

Let us see how we can use DAC using sqlcmd.

Connect SQL Server using sqlcmd and -A option which will establish DAC.

C:\>sqlcmd -S localhost -U sa -P dev -d master -A

For our test purpose run following query which overload server and probably make it unresponsive. If your configure is not strong I strongly suggest not to run following query.

Following query is just for test purpose and not part of solution.

USE AdventureWorks
GO
SELECT *
FROM Person.Address
CROSS JOIN Person.Address a1
CROSS JOIN Person.Address a2
CROSS JOIN Person.Address a3
CROSS JOIN Person.Address a4
CROSS JOIN Person.Address a5
CROSS JOIN Person.Address a6
CROSS JOIN Person.Address a7
CROSS JOIN Person.Address a8
CROSS JOIN Person.Address a9
GO

Once successfully connected it will provide prompt 1> enter following T-SQL query which will give SessionID of currently running query along with its elapsed time.

SELECT
req.session_id,
req.status,
req.total_elapsed_time
FROM sys.dm_exec_requests req
WHERE status = 'running'
AND req.total_elapsed_time > 1

Our previously running query gave session id 52 in on my server. The session id may be different for each SQL Server. Once the session id is figured out it can be killed using KILL [SessionID] command. Always make sure to type command GO after each complete query.

KILL 52

Once above query has run it will kill our example long running query and give following error.

Msg 233, Level 20, State 0, Line 0

A transport-level error has occurred when receiving results from the server. (provider: Shared Memory Provider, error: 0 – No process is on the other end of the pipe.)

sqlcmd is really useful utility of SQL Server and it comes in handy when server is not responsive. I strongly suggest to bookmark this article as it can come to rescue when nothing works and SQL Server is unresponsive.

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

SQL SERVER – Interesting Observation – Using sqlcmd From SSMS Query Editor

A day before I wrote article SQL SERVER – sqlcmd vs osql – Basic Comparison. Today while I was displaying how sqlcmd can be used instead of osql to one of my companies team leader, I found another neat feature of SSMS Query Editor. sqlcmd can be used from Query Editor but it has to be enabled first.

Following image display how sqlcmd can be enabled in Query Editor. Go to SSMS Menu >> Query >> (click on ) SQLCMD Mode.

Now on Query Editor will support sqlcmd mode. Let us see following example where script contains operating system commands as well SQL commands.

SELECT @@Version ServerVersion
!! Dir "C:\Documents and Settings"
!! Date /T
SELECT GETDATE() CurrentTime

Once above command has ran following output is displayed in Result Window.

Interesting Observation:
What really is interesting is that out of complete batch all the operating system commands runs first and those are followed by SQL commands. The order of SQL and operating system does not matter in resultset.

I want to throw my above observation to all of you and want to get your feedback about that. Have you faced this situation or scenario? What is the solution some we want to execute SQL and OS commands in order?

Watch the video on the same subject:

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

SQL SERVER – sqlcmd vs osql – Basic Comparison

Today we will go over very simple but to the point comparison of two SQL Server utilities or SQL Server tools.

This comes often to users which one to use sqlcmd or osql, when in need of running SQL Server queries from command prompt. Answer to this is very simple use “sqlcmd”.

sqlcmd has all the feature which osql has to offer, additionally sqlcmd has many added feature than osql. isql was introduced in earlier versions of SQL Server. osql was introduced in SQL Server 2000 version. sqlcmd is newly added in SQL Server 2005 and offers additionally functionality which SQL Server 2005 offers.

osql


sqlcmd


It is worth noting that when osql command is run on system where SQL Server 2005 is installed it gives following message in the beginning, which itself suggests to use sqlcmd.

Note: osql does not support all features of SQL Server 2005.
Use sqlcmd instead. See SQL Server Books Online for details.

If there are scenario where the script is using very basic functions of SQL Server and either sqlcmd and osql can execute them what user should do? In this case, I would suggest that use sqlcmd because sqlcmd is feature rich and why not use something which is latest.

Let me give one example, in one of the recent script which I came across required to run OS commands along with SQL commands. If osql was only used then whole script has to divide in two parts. osql would run SQL commands and XP_CMDSHELL would run OS commands. However, using sqlcmd both can be achieved easily.

If you are using sqlcmd and you need to run system command “dir” just write “!! dir” and it will run system command right away.

There are many more advantage of using sqlcmd which we will see in follow up posts.

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

SQL SERVER – 2005 – Introduction and Explanation to sqlcmd

I decided to write this article to respond to request of one of usergroup, which requested that they would like to learn sqlcmd 101.

SQL Server 2005 has introduced new utility sqlcmd to run ad hoc Transact-SQL statements and scripts from command prompt. T-SQL commands are entered in command prompt window and result is displayed in the same window, unless result set are sent to output files. sqlcmd can execute single T-SQL statement as well as batch file. sqlcmd utility can connect to earlier versions of SQL Server as well. The sqlcmd utility uses the OLE DB provider to execute T-SQL commands, whereas SQL ServerManagement studio uses .NET sqlclient to execute sqlcmd script, this can lead to different results in certain cases. (If you have example of this please let me know, I will post it here)

sqlcmd is enhenced version of the isql and osql and it provides way more functionality than other two options. In other words sqlcmd is better replacement of isql (which will be deprecated eventually) and osql (not included in SQL Server 2005 RTM). sqlcmd can work two modes – i) BATCH and ii) interactive modes.

Let us go over simple example of sqlcmd.

1) Step 1 : Go to Start >> Run >> Type “cmd” and press enter.

2) Step 2 : Type in command “sqlcmd” and press enter

3) Step 3 : Type following “USE AdventureWorks” command to switch database context to Adventureworks. Type “GO” after the batch to change the code. It will display the success message as “Changed database context to AdventureWorks”.

4) Step 4 : Now run any same query. Refer following image to see the query and its result.

5) Step 5 : Similar result we will get if the same query is ran in Query Editor in SSMS.

6) Type “exit” at any point if you do not want to continue working with sqlcmd.

The use of sqlcmd syntax is very easy however it this command can perform many powerful tasks. We will see that in future articles.

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

SQL SERVER – Fix : Error : Msg 7311, Level 16, State 2, Line 1 Cannot obtain the schema rowset DBSCHEMA_TABLES_INFO for OLE DB provider SQLNCLI for linked server LinkedServerName

You may receive an error message when you try to run distributed queries from a 64-bit SQL Server 2005 client to a linked 32-bit SQL Server 2000 server or to a linked SQL Server 7.0 server.

Error:
The stored procedure required to complete this operation could not be found on the server. Please contact your system administrator.
Msg 7311, Level 16, State 2, Line 1
Cannot obtain the schema rowset “DBSCHEMA_TABLES_INFO” for OLE DB provider “SQLNCLI” for linked server “<LinkedServerName>”. The provider supports the interface, but returns a failure code when it is used.

Fix/WorkAround/Solution:

Use Windows Authentication mode
For a default instance
osql -E -S <LinkedServerName> -i <Location>\instcat.sql

For a named instance
osql -E -S <LinkedServerName>\<InstanceName> -i <Location>\instcat.sql

Use SQL Server Authentication mode
For a default instance
osql -U <AdminLogin> -P <AdminPassword> -S <LinkedServerName> -i <Location>\instcat.sql

For a named instance
osql -U <AdminLogin> -P <AdminPassword> -S <LinkedServerName>\<InstanceName> -i <Location>\instcat.sql

By default, this folder is C:\Program Files\Microsoft SQL Server\MSSQL\Install.

Example:
osql -U sa -P MyPassWord -S Database.IpAddress.com -i “C:\Program Files\Microsoft SQL Server\MSSQL\Install\instcat.sql”

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