Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BCP in SQL command give NativeError = 2 when no -S parameter on local DB

I have this command in SQL:

DECLARE @cmd NVARCHAR(4000)
DECLARE @pathAndFileName NVARCHAR(MAX)
DECLARE @result INT
SET @pathAndFileName = 'C:\Temp\file.csv'
SET @cmd = 'bcp "SELECT TOP 1 * FROM SomeDB.dbo.SomeTable" queryout "'
  + @pathAndFileName + '" -w -T -t; '       
EXEC @result = xp_cmdshell @cmd 
SELECT @result

and it outputs this:

SQLState = 08001, NativeError = 2 Error = [Microsoft][SQL Server Native Client 11.0]Named Pipes Provider: Could not open a connection to SQL Server [2]. 
SQLState = 08001, NativeError = 2 Error = [Microsoft][SQL Server Native Client 11.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. 
SQLState = S1T00, NativeError = 0 Error = [Microsoft][SQL Server Native Client 11.0]Login timeout expired

@result is 1

It works only if I add -S parameter with server name and database name (like this -S "MYCOMPUTERNAME\DBINSTANCENAME").

But when I try this on remote server this works without -S parameter.

How can I setup my local DB, so I don't need -S anymore?

like image 748
Bomberlt Avatar asked Feb 03 '14 08:02

Bomberlt


People also ask

Can SQL database be local?

Once installed, LocalDB is an instance of SQL Server Express that can create and open SQL Server databases. The system database files for the database are stored in the local AppData path, which is normally hidden.

What is mssql BCP?

The bulk copy program utility (bcp) bulk copies data between an instance of Microsoft SQL Server and a data file in a user-specified format. The bcp utility can be used to import large numbers of new rows into SQL Server tables or to export data out of tables into data files.


1 Answers

If you ommit -S then it will try the default, localhost unnamed instance:

-S server_name[ \instance_name]
Specifies the instance of SQL Server to which to connect. If no server is specified, the bcp utility connects to the default instance of SQL Server on the local computer.

From your example it seems you do have an instance name, so it will not be possible to connect w/o specifying the -S explicitly. Besides, your code will always be more portable and easier to troubleshoot if you take the extra steps of specifying the -S params explicitly. Use SERVERPROPERTY(MachineName) and SERVERPROPERTY(InstanceName), make sure the code is cluster aware.

like image 98
Remus Rusanu Avatar answered Sep 22 '22 11:09

Remus Rusanu