سؤال

I am unloading the results of a query to a file. I need the result records to be displayed in a single line. For example,

unload to file.unl select col from table where col = "test";

The resulting file.unl would be like

test|
test|
....
test|

But what I would like to get is,

test|test|test|....|test|

Any guidance or ideas are appreciated.

Thanks

هل كانت مفيدة؟

المحلول

You are probably aware you can declare DELIMITER "|" in the SQL or via the DBDELIMITER environment variable. As far as I know, there is no way to change the default record terminator from NEWLINE to anything else.

So I suspect you will need to either write a custom function that iterates through the results and appends them to a variable which you then write out to a file, or write a separate piece of script that you call via RUN that pivots the data from rows to columns, eg:

UNLOAD TO file.unl SELECT col FROM table WHERE ...;    
RUN "/usr/bin/perl -ni -e 'chomp; print' file.unl";

I've assumed you're running on Unix and have perl handy. If you don't, you might find the iterator suggestion more practical than mucking about with installing perl on Windows, particularly if you have limited control over machines this code gets run on.

Update

My 4GL is very rusty, but I was decribing something very basic, eg:

DEFINE command CHAR(10100)
DEFINE long_string CHAR(10000)
DECLARE curs1 CURSOR FOR
  SELECT col FROM table WHERE ...

FOREACH curs1 INTO col1
    LET long_string = long_string CLIPPED || col1 CLIPPED || '|'
END FOREACH
LET command = "echo '" || long_string CLIPPED || "' > file.unl"
RUN command

It's 15 years or more since I wrote any 4GL, so treat that as pseudo-code at most, please. There might be a better way to write directly to a file, I honestly can't remember.

نصائح أخرى

CREATE Table #Table ( PKey INT Primary key, Field VARCHAR(10) )

INSERT INTO #Table select 1, 'ABS1' UNION ALL select 2, 'ABS2' UNION ALL select 3, 'ABS3'

DECLARE @results VARCHAR(MAX) = ''

select @results = COALESCE( @results + '|' + Field, @results ) from #Table

SELECT @results

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top