NVARCHAR (MAX) TO PRINT DYNAMIC SQL QUERY TO A SQL FILE

Hi 
I have a requirement where i need to write an SP which would construct a huge query using dynamic SQL and save the Dynamic query to a file. 
The Dynamic SQL Variable I am using as @NVARCHAR(MAX) but since the query being built is large (>4000 characters), I am not able to select it into a table. PRINT @SQL prints the whole query but SELECT @SQL prints only upto 4000 characterrs. 
And I need to save this huge dynamix sql to a file using the SP.
Any thoughts as to how i can achieve this?
Rajiv

This is a know problem with dynamic SQL nvarchar(max) concatenation.
See below for correct assembly of large SQL strings:
CREATE table #temp(qry nvarchar(max));
declare @cmd nvarchar(max);
SELECT @cmd=CONCAT(CONVERT(nvarchar(max),N'SELECT '),
CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
CONVERT(nvarchar(max),N'FROM SYS.TABLES'));
insert into #temp SELECT @cmd;
select * from #temp;
select len(qry), datalength(qry) from #temp;
-- 16022 32044
drop table #temp;
Dynamic SQL:  http://www.sqlusa.com/bestpractices/dynamicsql/
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

Similar Messages

  • How to display the out put of the sql query in a text file using forms

    I want to display the out put of the sql query in a text file using forms 6.0.Same could be done using spool command in sqlplus but i want it using forms....Fiaz

    Have a look at the text_io package:
    http://www.oracle.com/webapps/online-help/forms/10g/state?navSetId=_&navId=3&vtTopicFile=f1_help/oraini/c_text_io.html&vtTopicId=
    cheers

  • Re: How to converting from PL/SQL query to T-SQL query

    How to converting from PL/SQL query to T-SQL query... Its Urgent

    Download the
    SQL Server Migration Assistant for Oracle.  It will convert whole Oracle databases, or single queries or PL/SQL stored procedures.
    With caution that If your database is using Collation which is case sensitive SSMA will not work.SSMA doesnt guarantees 100% for conversion of Queries/stored proc /database if it fails to do so for some queries you will have to do it manually.
    But you can try
    Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers

  • Sql query to downloaded csv file

    Hi.
    This is probably something really easy, but I cant find how to do it.
    I want to run a dynamic SQL query and have the output appear in csv format as a file the user can save to disk.
    Is this easy, if so how? Or is there a longer packaged based solution to this?
    Regards,
    Asim

    Asim,
    First you need to create a report, you can use a simple SQL query based report, or if your query is dynamic, use a region of type PL/SQL function returning SQL query. Then go to the reports attributes page and enable the CSV link for that report. When running your report page, you’ll notice a CSV export link that lets your download your report as a CSV file.
    Alternatively, If you don’t want to run the report as a regular HTML DB page at all, then you could just choose the CSV template as the report template on the reports attributes page. When running the page with that template, it opens a file download dialog for the CSV file right away. You could integrate this with your own application by placing a “download” button on some other page, that on clicking of this button branches to the CSV download page and by doing so, lets you download the file.
    Marc

  • How to use property file - sql query define in property file

    Hi All,
    Anybody please tell me how to use property file.
    I have placed sql query in propery file and I have to access this in my file.
    well so far this is my code but don't know how to implement in the following ...
    pstmt = con.prepareStatement("select * from registration where username=?");
    instead of writting the query I want to use the property file.
    so far I have developed the following code...
    FileInputStream fis = new FileInputStream("querysql.property");
    Properties dbProp = new Properties();
    dbProp.load(fis);is the code correct... or is there another way to access property file
    Please help.
    please reply soon....
    Thanks

    Before answering, check if it's already been done here http://www.jguru.com/forums/view.jsp?EID=1304182

  • SQL Query works in SQL Developer, but not always in MII

    Hi all,
    I encountered a strange behaviour with a query in MII 12.0.2. Maybe someone has a guess what happens.
    I have created a SQL query which runs against Oracle 10g tables. I have tested the query using SQL Developer, and it throws a couple of lines, depending on the contents of the where clause.
    Next I have copied the query to a MII SQL Query (FixedQuery). However, the output is empty most of the time, without showing any errors. After some testing I got the impression that older data are not displayed, but there is no time or date setting in MII.
    As the SQL Developer always returns rows, I am unsure where to search for the error.
    Regards
    Michael

    Michael,
    I would imagine that you have sub-select statements in your FixedQuery, all which will fall subject to the RowCount property of the query template (SQL defaults to 100), which is issued through the driver and typically honored by the database when returning the data from your request.
    Most of the native database query tools allow you to make unbound query requests with no limit on rows, which would probably account for the difference between SQL Developer and the query template.
    For SQLServer it's ROWCOUNT:  http://msdn.microsoft.com/en-us/library/ms188774.aspx
    For Oracle it's ROWNUM:  http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html
    So the answer would be not to make the query template row count some rediculous number, but more appropriately refine the way that the database request is issued.
    Regards,
    Jeremy

  • Can we run SQL query on a XML file?

    Hi All
    I have an XML document which stores data of a table.
    My requirement is to retreive data from this XML document by firing SQL
    query.
    i.e "SELECT * FROM EMP" should give me the data from the EMP.XML file
    whose name is the table name.
    Does Oracle provide this feature to retreive data from an XML document
    by issuing the same SQL statement that is used in Database?
    Any pointer for this requirement is highly appreciated.
    Thanks in advance..
    Ashish

    select '<EMPLOYEE><EPNUM>' || EPNUM || '</EPNUM><EMPNAME>' || EMPNAME || '</EMPNAME></EMPLOYEE>' from EMPLOYEE;

  • How do i get a output in CSV of a SQL query executed via SQL Command prompt

    Hi All,
    I have a question with reference to SQL command prompt. I have a sql query which runs properly and gives proper execution in SQL Management console in GUI.
    This report is used to pull the free disk space report of our servers
    As i want to schedule it as a report so i want to script it to run via SQL command prompt. I made the script and it works fine if i enter it in SQL command prompt. When i try to extract the output to a CSV File it fails. Below is the details of the command
    i am using to query to pull the data. Can anyone help me in getting the output of this query in SQL command prompt.
    sqlcmd -W -s , -S Servers FQDN
    use operationsmanager
    Go
    Query:"select Path, InstanceName, SampleValue 
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled" -s "," -o "C:\DataSqlCmd.csv"
    Go
    When i enter the command without the quotes when the query is starting and ending and also without the output command (-s "," -o "C:\DataSqlCmd.csv") it is working and shows the output in the command prompt. Below is the screen shot for
    your reference.
    Due to security reasons i have to erase the server names:
    But when i add the line to extract the output ( -s "," -o "C:\DataSqlCmd.csv") It gives me this error:
    The exact command would be:
    sqlcmd -W -s , -S CINMLVSCOM01.e2klab.ge.com
    use operationsmanager
    Go
    "select Path, InstanceName, SampleValue 
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled" -s "," -o "C:\DataSqlCmd.csv" -h-1
    Go
    saying the syntax is not correct or some thing as per the below screenshot.
    Can any one please help. Below is just the query whi i use to get the output in SQL management studio.
    Can any one make a command for the below quer so i can directly execute and test for getting the output.
    select Path, InstanceName, SampleValue 
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled
    Gautam.75801

    Can you try the below query?
    select Path, InstanceName, SampleValue
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < 20 and CounterName like '% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled
    -- replace the below query part in the below SQLCMD C:\>SQLCMD -S SERVERNAME -E -d operationsmanager -Q "select * from sys.databases ds with (nolock) where name='master'" -s "," -o "F:\PowerSQL\MyData.csv" -h -1
    SQLCMD -S SERVERNAME -E -d OperationsManager -Q "select Path, InstanceName, SampleValue
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled" -s "," -o "c:\MyData.csv" -h -1
    Refer for the other ways 
    http://dba.stackexchange.com/questions/23566/writing-select-result-to-a-csv-file
    --Prashanth

  • How to write the output of an SQL query to a text file?

    I am using Oracle 11g and SQL plus.
    I have a large table called rating.
    Whenever I do
    SQL> select * from rating;
    The output goes much beyond what the SQL Plus screen can show. I want to therefore store the output of this query into a text file.
    How can this be done? Please help. Thanks.

    SQL> SPOOL results.txt
    SQL> select * from rating;
    SQL> SPOOL OFF

  • Optimizing an SQL Query using Oracle SQL Developer

    Hi ,
    Currently i am using Oracle SQL Developer as my Database IDE .
    Is it possible to use Orqcles SQLDeveloper for the purpose of Optimizing an SQL Query ??
    For example assume i am having a query as :
    Select from Tranac_Master where CUST_STATAUS='Y' and JCC_REPORT='N'*
    Could anybody please tell me how can i use Oracle SQL Developer to optimize this query or any other SQL queries ??
    Please share your ideas , thanks in advance .

    1. Your query looks very simplistic as it is, so I fail to see how you can better optimise it (unless 'Tranac_Master' is a view, in which case I'd need to see the view details).
    2. No tool can automagically optimise your SQL to any degree of practical use. Very minor adjustments may be possible automatically, but really it is a question of you knowing your data & database design accurately, and then you applying your expert knowledge to tune it.

  • Can anybody provide the SQL query to find the files uploaded in a particular folder?

    Hi All,
    Can anybody provide the SQL query to find the documents (document name) uploaded in a particular folder? While clicking on folder in
    GUI I'm hitting the Timeout error. I would like to find the files uploaded into this folder from SQLPLUS.
    Any help is greatly appreciated.
    With best regards,
    Nevin

    Nevin,
    Be great if we could know the version of Portal. For Rel. 1, here's the query
    select id,masterthingid from wwv_things
    where siteid = &site
    and cornerid = &corner
    &site - Content Area id
    &corner - Folder id
    if you don't know the folder id, use
    select id from wwv_corners where siteid = &site
    and name = &folder
    Hope this helps. I have run into this situation before. Usually, the culprits were
    one of the following:
    1. Junk Characters in description of item (caused due to Copy-Paste)
    2. Special Characters in the File name
    Hi All,
    Can anybody provide the SQL query to find the documents (document name) uploaded in a particular folder? While clicking on folder in
    GUI I'm hitting the Timeout error. I would like to find the files uploaded into this folder from SQLPLUS.
    Any help is greatly appreciated.
    With best regards,
    Nevin

  • Need sql query or pl/sql query urgent

    Hi Experts,
    The requirement is that
    SELECT 'N' flag, sysdate init_date,
    '' vendor_name,
    DECODE (pa.address_type,
    'P', 'Present Address',
    'R', 'Permanent Address',
    pa.address_type
    ) address_type,
    pa.address_line1
    || ','
    || pa.address_line2
    || ','
    || pa.town_or_city
    || ','
    || meaning
    || ','
    || pa.POSTAL_CODE "Address",
    TRUNC (TO_CHAR (pa.date_from, 'YYYY')) YEAR,
    TO_CHAR (pa.date_from, 'MON') MONTH,''station
    FROM per_addresses pa, fnd_lookup_values, per_all_people_f pf
    WHERE (pf.employee_number = :1 or pf.APPLICANT_NUMBER = :2)
    and pf.EFFECTIVE_END_DATE='31-DEC-4712'
    AND pa.person_id = pf.person_id
    AND pa.business_group_id = 42
    --AND pa.date_to IS NULL
    AND lookup_type = 'PER_US_COUNTRY_CODE'
    AND lookup_code = pa.country
    AND enabled_flag = 'Y'
    AND (end_date_active IS NULL OR end_date_active > SYSDATE)
    if i run the above query the output is coming like that
    Present Address |     Flat No. 1201, OC - 15, Orange County, Plot No. GH - 4,Ahinsa Khand 1st, Indrapuram,Ghaziabad,India,201010|     2,010|     JUL
    Permanent Address |     Q.No. 354, Sector - 3 / B,,Bokaro Steel City,India,827003     |2,010     |JUL
    Present Address |     4, Sitara,Chandra Reddy layout, S.T. Bed,Bangalore,India,0|     2,006|     JAN
    Present Address |     101,,Ushma Urja Apartments,Noida,India,201301 |     2,006 |     JUL
    Permanent Address |     F-19, Maccon Colony, Opp. DAV Shyamali School,,Ranchi,India,834002 |     2,009 |     FEB
    Present Address |     Flat no. 604, B - 1, Krishna Apra Gardens,Vaibhav Khand, Plot - 7,Ghaziabad,India,201010 |     2,009     FEB
    But the requirement is the output should come like that
    Permanent Address     |Q.No. 354, Sector - 3 / B,,Bokaro Steel City,India,827003|     2,010     |JUL                    
    Permanent Address 1|     F-19, Maccon Colony, Opp. DAV Shyamali School,,Ranchi,India,834002|     2,009 |     FEB
    Present Address |     Flat No. 1201, OC - 15, Orange County, Plot No. GH - 4,Ahinsa Khand 1st, Indrapuram,Ghaziabad,India,201010|     2,010 |     JUL                    
    Present Address 1 |     Flat no. 604, B - 1, Krishna Apra Gardens,Vaibhav Khand, Plot - 7,Ghaziabad,India,201010|     2,009 |     FEB                    
    Present Address 2 |     101,,Ushma Urja Apartments,Noida,India,201301|     2,006|     JUL     
    Present Address 3 |     4, Sitara,Chandra Reddy layout, S.T. Bed,Bangalore,India,0 |     2,006|     JAN     
    Please provide logice how i need to write a sql query or procedure or function or package
    Thanks & Regards
    Venu

    You can use analytics here :
    SELECT
        flag,
        init_date,
        vendor_name,
        address_type   ||' ' ||rn AS address_type,
        Address,
        YEAR,
        MONTH,
        station
    FROM
            SELECT
                'N' flag,
                sysdate init_date,
                '' vendor_name,
                DECODE (pa.address_type, 'P', 'Present Address', 'R','Permanent Address', pa.address_type ) address_type,
                row_number() over(partition BY pa.address_type order by 1) AS rn,
                pa.address_line1
                || ','
                || pa.address_line2
                || ','
                || pa.town_or_city
                || ','
                || meaning
                || ','
                || pa.POSTAL_CODE "Address",
                TRUNC (TO_CHAR (pa.date_from, 'YYYY')) YEAR,
                TO_CHAR (pa.date_from, 'MON') MONTH,
                '' station
            FROM
                per_addresses pa,
                fnd_lookup_values,
                per_all_people_f pf
            WHERE
                    pf.employee_number  = :1
                 OR pf.APPLICANT_NUMBER = :2
            AND pf.EFFECTIVE_END_DATE='31-DEC-4712'
            AND pa.person_id         = pf.person_id
            AND pa.business_group_id = 42
                --AND pa.date_to IS NULL
            AND lookup_type  = 'PER_US_COUNTRY_CODE'
            AND lookup_code  = pa.country
            AND enabled_flag = 'Y'
            AND
                    end_date_active IS NULL
                 OR end_date_active  > SYSDATE
        );

  • Change "SQL Query" report to "SQL Query (updateable report)" report?

    I manually made a report, because the tabular report made by the wizard gave me no possibility to use a popup LOV. Now I have this report, but I cant apply an MRU process on it, becuase it's not an "SQL Query (updateable report)". How can I change my report to a "SQL Query (updateable report)"? I only can choose between SQL Query and SQL QUERY (PL/SQL function body returning SQL query).

    Hi Tom
    You can just write the processes yourself. Although trickier this can give you a lot more control over row processing.
    APEX_APPLICATION.G_F01, F02 etc are global variables in the apex_application package that are defined as arrays.
    These are regularly used in tabular forms to reference values within them. The normal ordering would be column 1 = G_F01, column 2 = G_F02 etc etc. Although you can change these and even assign more than one column to an array.
    The example
    FOR i IN 1..APEX_APPLICATION.G_F01.COUNT LOOP
    INSERT INTO my_table VALUES(:P1_EMPID , APEX_APPLICATION.G_F01(i));
    END LOOP;Is saying - for the number of values in the array G_F01 (probably column 1) loop insert into the table the value of the associated value in the array. So first time through i=1 - so the first value in the array (probably row 1 in column 1), next time i=2 so the second value in the array is used (probably row 2 in column 1) and so on...
    When you've created a manual tabular form (what I would call what you've done) you have created the items using the APEX_ITEM package in your query. The first parameter for this is p_idx which defines which global array to hold it in.
    Cheers
    Ben

  • SQL query question for SQL Swing Applet

    Hi
    I am building a little SQL Swing applet.
    I was wondering if there is a SQL query statement to
    find:
    * The names of all the tables in the Database loaded.
    * The number of tables in a database loaded.
    Thank you very much in advance, A.

    Not positive, but check out Connection.getMetaData(). It returns a DatabaseMetaData instance that has a number of get... methods that may provide the info you need.

  • Pivot Dynamic for Query in Oracle SQL DEVELOPER ??

    Hi
    I have the following question, someone who has a dynamic pivot.
    I need a dynamic query that is that when the transfer column to row do receiving any type declared as these can change data.
    Example:
    ID_PROJECT
    PROJECT STAGES
    DATE
    12345
    Requirement Analysis
    17-01-2013
    12345
    Quotation
    20-01-2013
    12345
    Project Preparation
    29-01-2013
    12345
    Model Verification
    04-02-2013
    12345
    Closed requirement
    10-02-2013
    23456
    Building and Unit Tests
    With dynamic pivot:
    ID_PROJECT
    Requirement Analysis
    Quotation
    Project Preparation
    Model Verification
    Closed requirement
    12345
    17-01-2013
    20-01-2013
    29-01-2013
    04-02-2013
    10-02-2013
    I mean that in this case the stages of the project will be changing.

    Hello,
    Do you want to do this in an SQL - Developer application-setting or by using any SQL / PLSQL block or both ?

Maybe you are looking for

  • EPrint Print Report Not Printing

    I've set up my HP Photosmart 7510 e All-In-One printer wirelessly and it works fine, but I just got an iPhone and now I'm attempting to set up ePrint. When I go on my printer and click "Print Report," I get a message that the report will take a few m

  • Installing and deploying a .webpart file in SharePoint 2013

    I have a webpart that took from a SharePoint 2010 web site from its webparts library. This webpart has the .webpart extension. I downloaded it as a copy. Now I want to install it to a SharePoint 2013 site ti its webpart gallery. I tried using Visual

  • Alternative tcode for AL02 in ECC 6.0

    Hi All, AL02 is a tcode in 4.7, its obsolete in ECC 6.0 . i want the alternate tcode for this in ECC 6.0. can u suggest me some process to find such alternative tcodes for the obsolete one in the higher versions.

  • Abap development question

    hi i have created a table student with fields client, student id and student name in which  student id fieldu2019s domain maintain fixed values 1,2,3,4,5,6,7,8,9,10. now i have to Create a report which should take input student id and name, and shoul

  • Direct path temp write

    Hi, Oracle Version : 11.2.0.1(Standard Edition) Operating System : RHEL-5 We are having one Procedure which is causing Direct Path Temp Write Even. How can we avoid that and it is taking lot of time for execution. Please help me how solve my problem.