Link to home
Start Free TrialLog in
Avatar of DLockwood
DLockwood

asked on

export a complex query into a file

I have a long and complex query that needs to be exported to a data file. The problem is that the user needs to supply 1 Parameter to the query for it to process the required data.

When I try to bcp it from within a Stored Procedure in which the Parameter is passed, I get an error that the query is too long.

Any ideas of another way to supply the Parameter, run the query, and then export the data?
Avatar of curtis591
curtis591

I am not sure if this will work or not, but what if you execute the query so that it puts the results into a temporary table and then do a select * from #temptable in the bcp.
Use VBScript to write the SQL to a file.  Here is an example:

declare @cmd sysname, @mfn sysname
SET @cmd = 'SELECT * FROM PUBS' -- Build query with parm.
SET @mfn = '"C:\MyFileName.sql"' -- My File Name
EXEC @cmd -- Execute query
EXEC master..xp_cmdshell 'cscript C:\WriteSQL.vbs ' + @mfn + ' "' + @cmd + '"' -- Write query string to MyFileName

C:\WriteSQL.vbs (contents below)
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set m_objWshShell = Wscript.CreateObject("Wscript.Shell")
'// Create a FileSystemObject object
Set m_objFileSystem = CreateObject("Scripting.FileSystemObject")
'// Open output file, forcing creation if it doesn't already exist.
Set m_objFile = m_objFileSystem.OpenTextFile(WScript.Arguments.Item(0), ForAppending, True, 0)
m_objFile.WriteLine (WScript.Arguments.Item(1))

The SQL server needs to be able to run VBScript files.  Windows 2000 does this or NT with WSH (Windows Scripting Host) install does it also.  Hope this helps.

Todd A. Baldridge
ASKER CERTIFIED SOLUTION
Avatar of miron
miron
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DLockwood

ASKER

miron,

Excellent suggestion. Works beautifully.

DLockwood