BCP out Error in SQL2000: SQLState = 37000, NativeError = 4060 - sql-server

I have created a proc that grabs all the user tables in a local DB on my machine. I want to be able to create a flat file of all my tables using BCP and SQL. Its a dummy database in SQL 2000 connecting through windows authentication. I have set my enviroment path variable in WinXP SP2. I have created new users to access the db, switched off my firewall, using trusted connection. I have tried dozens of forums, no luck.
In dos command prompt I get the same error.
SQLState = 37000, NativeError = 4060
Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database requested in login '[HelpDesk-EasyPay'. Login fails.
Here is my SP:
#Path VARCHAR(100),
#UserName VARCHAR(15),
#PassWord VARCHAR(15),
#ServerName VARCHAR(15)
AS
set quoted_identifier off
set nocount on
declare #n int
declare #db varchar(40)
set #db=DB_NAME()
declare #TableName varchar(15)
declare #bcp varchar(200)
select identity(int,1,1) as tblNo,name tblname into #T from Sysobjects where xtype='u'
select #n=COUNT(*) from #T
WHILE (#n>0)
BEGIN
SELECT #TableName=tblname FROM #T WHERE tblno=#n
PRINT 'Now BCP out for table: ' + #TableName
SET #bcp = "master..xp_cmdshell 'BCP " + "[" + #db + ".." + #TableName + "]" + " OUT" + #Path + "" + #TableName+".txt -c -U" + #UserName + " -P" + #PassWord + " -S" + #ServerName + " -T" + "'"
EXEC(#bcp)
SET #n=#n-1
END
DROP TABLE #T
Can anyone advise. This seems to be a connection problem or BCP ? Not sure.
edit: I am running this from query analyzer because I have 118 tables to output to flat file. I seem to agree that its an authentication issue because I tried connecting to master db with username sa password root. which is what its set to and I get the same error: SQLState = 37000, NativeError = 4060

Your brackets are extending over the entire qualified table name - only the individual components should be bracketed:
bcp [HelpDesk-EasyPay].dbo.[customer] out d:\MSSQL\Data\customer.bcp -N -Utest -Ptest -T
should work, so you want:
SET #bcp = "master..xp_cmdshell 'BCP " + "[" + #db + "]..[" + #TableName + "]" + " OUT" + #Path + "" + #TableName+".txt -c -U" + #UserName + " -P" + #PassWord + " -S" + #ServerName + " -T" + "'"
in your code. It looks like the error message you gave was truncated, otherwise you would have been able to see that it was attempting to open database "[HelpDesk-EasyPay.dbo.customer]" which, of course, does not exist, and even if it did, you would then get an error that no table was specified.

I have the same issue for the OUT (the minus character kills everything event the ^ don't work)
I avoid it with the QUERYOUT. Like this :
SET #s = 'BCP "SELECT * FROM [HelpDesk-EasyPay].dbo.customers" QUERYOUT myfile.txt ...'

Maybe someone will come in handy: I have the same issue with SQL Server 2017. The reason was the square brackets around the database name.

Related

How to export table data from sql stored procedure to .csv in SSMS (without using BCP)

I have a DB "Test" and table "demo"(TRANSACT TYPE,TRANSACT_NUMBER,BALANCE,CREDIT AMOUNT,ACCOUNTING_DATE).
my purpose is:
to create a procedure which exports all the data of the table "demo" to csv file (without using bcp utility)
So far i have written the following code for stored proc:
CREATE PROCEDURE Test1
AS
SELECT * FROM demo
GO
EXEC Test1
and the following script in which I used the bcp utility (which gets an error: SQLState = S1000, NativeError = 0 Error = [Microsoft][ODBC Driver 13 for SQL Server]Unable to open BCP host data-file):
DECLARE #ExportFolderName NVARCHAR(90);
DECLARE #ExportFileName NVARCHAR(90);
SET #ExportFolderName = 'C:\Export\';
SET #ExportFileName = #ExportFolderName + 'demofile' + '.csv';
DECLARE #SqlStatement varchar(8000)
DECLARE #BcpStatement varchar(8000)
SET #SqlStatement = 'exec [SInterface].[dbo].[Test1]'
SET #BcpStatement = 'bcp "' +#SqlStatement + '" queryout "' + #ExportFileName + '" -c -t","-r"\n" -T'
exec master..xp_cmdshell #BcpStatement
for this reason I try to find a solution in which bcp is not used

Must declare the scalar variable #header

I have an issue with bcp to create xml file.
If I execute the single query
SELECT #header, #inland
FOR XML RAW(''), ROOT('root'), ELEMENTS, TYPE
I receive the correct XML data.
But if i insert the query into exec master..xp_cmdshell
declare #cmd varchar(2000) = 'bcp "SELECT #header,#inland FOR XML RAW(''''),ROOT(''root''), ELEMENTS, TYPE" queryout "\\server01\TEMP_SW\XML_TMS\test_'+#num+'.xml" -U xx -P xxxxx -c -C ANSI -t;' ;
exec master..xp_cmdshell #cmd;
The system returns the error
SQLState = 37000, NativeError = 137
Error = [Microsoft][SQL Native Client][SQL Server]Must declare the scalar variable "#header".
SQLState = 37000, NativeError = 8180
Error = [Microsoft][SQL Native Client][SQL Server]Statement(s) could not be prepared.
#header is declared as XML
Where is the error?
Thanks and regards
The error is just what is being reported. When using QUERYOUT option of BCP you get a new, separate SQL connection within which your SQL statement is executed (really it's the xp_cmdshell that first opens a new OS thread... then bcp-queryout opens a new SQL connection). This statement knows nothing of any earlier "declare" or "set/select" statements you may have executed before your xp_cmdshell command. So, looking at your SQL statement as the stand-alone query that it is, of course you will get an error that your variables have not been defined.
To do what you are trying to do, can you just resolve the values of your variables as you are buidling the #cmd string? Like this:
declare #cmd varchar(2000)
select #cmd = 'bcp "SELECT ' + #header + ',' + #inland + ' FOR XML RAW(''''),ROOT(''root''), ELEMENTS, TYPE" queryout "\\server01\TEMP_SW\XML_TMS\test_'+#num+'.xml" -U xx -P xxxxx -c -C ANSI -t;' ;
exec master..xp_cmdshell #cmd;
It looks like you are aleady doing this with the #num variable you add into the string later on. Just do the same with your #header and #inland variables.

Memory Allocation while creating database in SQL Server

For a bench-marking project I am currently working on, requires creating multiple databases on SQL Server. I am using Enterprise Edition instance on a VM, that has 8GB RAM and 4 core processor. I wanted to create dummy databases, with no data in it. I have the below script to generate the create database script.
create table createdb
(
dbname varchar(100),
createdbscript varchar(max)
)
DECLARE
#query as varchar(max), #NUM AS INT
SET #NUM = 1
CREATE TABLE #db_names(dbname varchar(250))
WHILE(#NUM <1001)
BEGIN
INSERT INTO #db_names values('NUM'+cast(#NUM as varchar))
SET #NUM = #NUM+1
END
SET #query = ''
insert into createdb
SELECT dbname, #query + 'CREATE DATABASE [' + dbname + ']
CONTAINMENT = NONE
ON PRIMARY
( NAME = N''' + dbname + ''',
FILENAME = N''c:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\' + dbname +'.mdf'' ,
SIZE = 10240KB ,
FILEGROWTH = 1024KB )
LOG ON
( NAME = N''' + dbname + '_log''' +',
FILENAME = N''c:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\' + dbname + '_log' +'.ldf'' ,
SIZE = 512KB ,
FILEGROWTH = 256KB )
' FROM #db_names
select * from createdb
drop table #db_names
I started to run create database commands in a batch of 100. It swamped my server's memory. After sometime, a batch of 2 create database commands was difficult.
I wanted to understand how the memory allocation happens for this kind of operations? What is the best way to create multiple databases? What hardware changes can impact this performance?

Using BCP and xp_cmdshell with T-SQL inside SSMS. "The syntax of the command is incorrect"

So, I am playing around with BCP to get to know it better, and ran into an issue I am having trouble figuring out. I am getting an error, "The Syntax of the command is incorrect".
I have tested the complete file path which is building correctly, and the select query by itself, which is completing correctly. Any thoughts?
The code I am using is:
DECLARE #fileName varchar(128)
DECLARE #filePath varchar(128)
DECLARE #completeFilePath varchar(128)
DECLARE #sqlCmd varchar(4000)
DECLARE #BCPSwitches VARCHAR(64)
SET #filePath = 'xxxxxx'
SELECT TOP 5 [EMP]
,[SSNO]
,[NAME]
,[STREET]
INTO #ParticipantIdentifiers
FROM xxxxxxxxx
SET #BCPSwitches = '-w -T -t |'
SET #fileName = 'xxxxx.txt'
SET #completeFilePath = #filePath + #fileName
SET #sqlCmd = 'bcp "SELECT * FROM #ParticipantIdentifiers" queryout "'+ #completeFilePath + '" ' + #BCPSwitches
EXEC DemoDB..xp_cmdshell #sqlCmd
I think the terminator "|" after -t (in the #BCPSwitches) needs to be enclosed in quotes as well since the shell might be interpreting this as a output pipe.

Execute BCP command in remote server

i am facing an issue while executing the BCP command in the remote server.
i have the following command in a batch file which executes a script file.
The script file process a temporary table and writes the records in temporary table to a file.
SQLCMD -SQA_Server236 -dtestdb -Usa -PPassword1 -i"D:\script\Writing to Files\Write to CSV.sql" -o"D:\script\script_logs.log"
--script files contains...
declare #table NVARCHAR(255)
declare #filename VARCHAR(100)
set #filename='C:\TextFile\abcd.csv'
set #table ='##Indexes_Add'
IF OBJECT_ID('tempdb..#Indexes_Add') IS NOT NULL
BEGIN
DROP TABLE ##Indexes_Add
END
CREATE TABLE ##Indexes_Add
(
id int IDENTITY(1,1) PRIMARY KEY,
alter_command NVARCHAR(MAX),
successfully_readded BIT NULL,
)
insert into ##Indexes_Add select 'a',0
insert into ##Indexes_Add select 'a',0
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..'+#table) IS NOT NULL
BEGIN
DECLARE
#sql NVARCHAR(MAX),
#cols NVARCHAR(MAX) = N'';
SELECT #cols += ',' + name
FROM tempdb.sys.columns
WHERE [object_id] = OBJECT_ID('tempdb..'+#table)
ORDER BY column_id;
SELECT #cols = STUFF(#cols, 1, 1, '');
SET #sql = N'EXEC master..xp_cmdshell ''bcp "SELECT '''''
+ REPLACE(#cols, ',', ''''',''''') + ''''' UNION ALL SELECT '
+ 'RTRIM(' + REPLACE(#cols, ',', '),RTRIM(') + ') FROM '
+ 'tempdb.dbo.'+#table + '" queryout "' + #filename + '" -c -t, -SQA_Server236 -Usa -PPassword1''';
EXEC sp_executesql #sql;
print #sql
END
My problem-:
When i run the above batch command in a batch file and i give my local server other than server name "QA_Server236" , i am getting the file "abcd.csv" created in my system but when i give the server name as "QA_Server236" the file is created in the remote machine i.e QA_Server236. But i want the file to be created in my system if the given server is a remote server say "QA_Server236"
Can anyone help me in this issue. i am not getting any method to do so.
If I'm right BCP does not allow saving result sets and/or logs to remote machines. But you could try to mount a folder on remote PC to a shared folder on your local machine and set the output location there, or maybe try using network path "\[YOURPC]....".As I'm not sure it works (actually, I think it won't), here's the only solution I can think of: add a line to your batch which moves the file(s) from the remote machine to your PC (xcopy or similar) after BCP finished executing (in batch, do this as "Call bcp.exe [params]" instead of just "bcp.exe ...")Hope this helps!

Resources