XP_CMDSHELL bcp error - sql

I am executing the XP_CMDSHELL as below:
Exec XP_CMDSHELL 'bcp "Select OrderID, OrderDate, OrderDesc from DB.dbo.Order" queryout C:\Orderfile.txt -k -t \t -c -Slocalhost -T'
I got the following error:
"Unable to open BCP host datafile."
I looked at the c:\ drive and there is a file Orderfile.txt exist. ANd i have not opened the file or any other program doesn't not the file. But still I am getting this error.
Anyone have any idea why I am getting this error? Thank you in advance.

One of two issues:
XP_CMDSHELL uses the SQL Server service account credentials for filesystem (and other) access. The service account won't have permissions on the root of C: and it doesn't matter if you can see it
SQL Server is on a server somewhere (that is, isn't a local install) and you are trying to access your local C: drive. SQL Server can't see this of course...

there should be full permission on drive.
file is create automatically.
exec master..xp_cmdshell 'BCP "Select * From [test].[dbo].[Customer]" QUERYOUT C:\Backup\customer123.txt -S HP-PC -T -c'

Related

SQL Server Agent unable to run SQLCMD

An SQL Server instance was set up without access to the Internet and failed to install SQLCMD during the initial SQL Server installation process. Upon discovering this SQLCMD was installed through the MsSqlCmdLnUtils.msi installer. Can now run SQLCMD through command line, as user account, but when running SQLCMD as part of xp_cmdshell the error is
'sqlcmd' is not recognized as an internal or external command,operable program or batch file.
I've manually given read/write access to all the SQLCmd files, i.e. .exe, .rll, etc, to the SQL Agent NT account. I can manually run the sqlcmd through command line as user account. Xp_cmdshell can run successfully when given other command line tasks, i.e. moving files, mapping drives, etc. Restarted SQL Server Agent.
SET #sqlCommand =
'sqlcmd -S hqconnectsql1 -d M -Q "SET NOCOUNT ON; select * from temp_travelSurvey" -o"' +
#filePath + #fileName +
'" -W -s"|" -w 1024'
EXEC master..xp_cmdshell #sqlCommand
GO
The above code is what is failing when run as a query through SSMS, left out are the variables that are declared and set prior to the command.
EXEC master..xp_cmdshell 'net use Y: \\HQPCISQL\e$ troperM12 /USER:aaa177\Reportsrv'
go
This code works successfully when run as a query through SSMS, showing that xp_cmdshell is not the issue.
The expected result, which I have been able to have succeed when run through the command prompt, is for a file containing the content of temp_travelSurvey to be created. Current error message is the sqlcmd is not a recognized internal or external command.
on SSMS you can execute your sql directly, you need not to use SQLCMD there. SQLCMD is command line interface to execute SQL from command prompt. I hope this would help you.
Like in above case directly execute sql scripts as below.
select * from temp_travelSurvey

batch file for executing sql query in a production server

is it possible to create a batch file which run from local computer to execute a query in production server, production server can be accessible only through remote connection. ? if not possible please suggest some ways,
Requirement: Need a batch files to get query results from production server?
Try like this,
Step-1:
Enter the below five lines and Save this as execute.bat file
set /P TargetServer=Enter Target DB Server IP:
set /P TargetDb=Enter Target DB Name:
set /P UserName=Enter UserName:
set /P Passwd=Enter Password:
sqlcmd -S %TargetServer% -U %UserName% -P %Passwd% -d %TargetDb% -i MyScript.sql -o MyOutput.txt
Step-2
Provide your sqls in this file and save it as MyScript.sql
select *from tablename
Step-3
Place execute.bat and Myscript.sql files in a folder then double click the execute.bat file. Your output of the MyScript.sql is saved in MyOutput.txt file.
Create a Batch file and Keep it production server itself by scheduling a task Task Scheduler (Windows assumed OS). So that no need of Remote access to Production server every time.
This is my suggestion from what I understood from your question.

Need help to make sqlcmd run as per requirements

I wanted to run SQLCMD.EXE as mentioned here - http://blog.daringa.com/archives/tag/error-hresult-e_fail-has-been-returned-from-a-call-to-a-com-component
I used the line in link with proper path to sqlcmd, user and password I use to login to my SQL server - sqlcmd -S .\MYSQLSERVER2008 -U MyUsername -P MyPassword -i C:\Database\hugescript.sql
Problem - I see a window and some message, but it vanishes so quickly that I cannot even see what it is. How do I see this window and how do I then execute an SQL file via SQLCMD.EXE
Why am I executing a script via SQLCMD and not SQL SERVER (ie SS) MGMT STUDIO ?
SS throws an error when sql files are big, ie about 100mb or more.
You can redirect the output from sqlcmd
sqlcmd -S .\MYSQLSERVER2008 -U MyUsername -P MyPassword
-i C:\Database\hugescript.sql > log.txt 2> error.txt
It will write the output to log.txt file and errors to error.txt file (you can specify the full path if you want). You can then see what's happening.

Cannot execute script: Insufficient memory to continue the execution of the program

I have a 123MB sql file which I need to execute in my local PC. But I am getting
Cannot execute script: Insufficient memory to continue the execution of the program
How to solve this issue?
use the command-line tool SQLCMD which is much leaner on memory. It is as simple as:
SQLCMD -d <database-name> -i filename.sql
You need valid credentials to access your SQL Server instance or even to access a database
Taken from here.
It might help you! Please see below steps.
sqlcmd -S server-name -d database-name -i script.sql
Open cmd.exe as Administrator.
Create Documents directory.
Put your SQL Script file(script.sql) in the documents folder.
Type query with sqlcmd, server-name, database-name and script-file-name as like above highlighted query or below command line screen.
For Windows Authentication use this sql cmd
SQLCMD -S TestSQLServer\SQLEXPRESS -d AdventureWorks2018 -i "d:\document\sql document\script.sql"
Note: If there is any space in the sql file path then use " (Quotation marks) "
For SQL Server Authentication use this sql cmd
SQLCMD -S TestSQLServer\SQLEXPRESS -U sa -P sasa -d AdventureWorks2018 -i "d:\document\sql document\script.sql"
-S TestSQLServer\SQLEXPRESS: Here specify SQL Server Name
-U sa: Username (in case of SQL Server Authentication)
-P sasa: Password (in case of SQL Server Authentication)
-d AdventureWorks2018: Database Name come here
-i "d:\document\sql document\script.sql": File Path of SQLFile
You can also simply increase the Minimum memory per query value in server properties. To edit this setting, right click on server name and select Properties > Memory tab.
I encountered this error trying to execute a 30MB SQL script in SSMS 2012. After increasing the value from 1024MB to 2048MB I was able to run the script.
(This is the same answer I provided here)
My database was larger than 500mb, I then used the following
C:\Windows>sqlcmd -S SERVERNAME -U USERNAME -P PASSWORD -d DATABASE -i C:\FILE.sql
It loaded everything including SP's
*NB: Run the cmd as Administrator
If I understand your problem correctly, you are trying to restore (transact sql) xyz.sql - database + schema. You can try this command which worked for me:
SQLCMD -U sa -i xyz.sql
Try this step,
1)Open PowerShell
2)Write this command:
sqlcmd -S PCNAME\SQLEXPRESS -U user -P password -d databanse_name -i C:\script.sql
3)Press Return
:-)
Below script works perfectly:
sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql -x
Symptoms:
When executing a recovery script with sqlcmd utility, the ‘Sqlcmd: Error: Syntax error at line XYZ near command ‘X’ in file ‘file_name.sql’.’ error is encountered.
Cause:
This is a sqlcmd utility limitation. If the SQL script contains dollar sign ($) in any form, the utility is unable to properly execute the script, since it is substituting all variables automatically by default.
Resolution:
In order to execute script that has a dollar ($) sign in any form, it is necessary to add “-x” parameter to the command line.
e.g.
Original:
sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql
Fixed:
sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql -x
Sometimes, due to the heavy size of the script and data, we encounter this type of error. Server needs sufficient memory to execute and give the result. We can simply increase the memory size, per query.
You just need to go to the sql server properties > Memory tab (left side)> Now set the maximum memory limit you want to add.
Also, there is an option at the top, "Results to text", which consume less memory as compare to option "Results to grid", we can also go for Result to Text for less memory execution.
sqlcmd -S mamxxxxxmu\sqlserverr -U sa -P x1123 -d QLDB -i D:\qldbscript.sql
Open command prompt in run as administrator
enter above command
"mamxxxxxmu" is computer name
"sqlserverr" is server name
"sa" is username of server
"x1123" is password of server
"QLDB" is database name
"D:\qldbscript.sql" is sql script file to execute in database
If you need to connect to LocalDB during development, you can use:
sqlcmd -S "(localdb)\MSSQLLocalDB" -d dbname -i file.sql
As in most answers given here use the command-line tool. In my case the script already has database creation code. If your script contains CREATE DATABASE command, for example
USE [master]
GO
CREATE DATABASE [your-database-name]
Then do not use the -d your-database-name, instead use the following command.
For Windows Authentication use the command
sqlcmd -S ServerName\InstanceName -i "script.sql" -x
For SQL Server Authentication use the command
sqlcmd -S ServerName\InstanceName -U usename -P password -i "script.sql" -x

How to save query result using T-SQL in a csv file?

How to save query result using T-SQL in a csv file in SSMS 2008? Needs to be done programmatically.
You could use System.Diagnostics.Process to run the SQLCMD or OSQL or BCP programs to dump out csv files.
Here is an example I found from google. Play around with the parameters.
EXEC master..xp_cmdshell 'sqlcmd -X -S server -q "SET NOCOUNT ON Select 'department','FundCode','Month' SELECT * FROM pubs.dbo.test" -s , -w 255 -u -o "\\server\output.csv" -h-1'