new line into SELECT query sql server 2005 - sql

I want to do a new line in my sql select
I try this but it won't work
SELECT '1' + char(13) + '2'
AND
SELECT '1' + char(13) + char(10) + '2'
it always return 12
thanks for your answers
in fact I try to export data from sql to TXT file
but when I execute the bcp file it return concatenate rows

The new line is in your result. If you copy and paste the result from your query into notepad, for example, you'll see 1, new line, 2. The reason you see 1 2 in your result in the results window is because you are returning 1 row. Notice that len('1' + char(13) + char(10) + '2') = 4, that is because your chars are present, it's just represented as a single row (with multiple lines in the row).

That's just the way SSMS displays the results. If you copy the result out into Notepad, or as Lamak says choose Results to Text you should see the newlines in place.

Related

SQL: Insert a linebreak in varchar string

I've searched StackOverflow for all the possible solutions concerning how to insert a linebreak in a SQL text string. I've referred this link but to no avail. How to insert a line break in a SQL Server VARCHAR/NVARCHAR string
But none of the solutions are working for me.
This is what I'm trying to do:
insert into sample (dex, col)
values (2, 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.')
But this is the output generated: (Select Col from sample where dex = 2)
This is line 1. This is line 2.
This is the output that I desire:
This is line 1.
This is line 2.
I'm using SQL server and SSMS if that helps.
Any ideas why it isn't working?
Well your query works perfectly fine.
SSMS by default shows all query out put in the grid view, which does not display the line break character.
To see it you can switch to text view using cntrl + T shortcut or like below
The results I got for your query are below( and they work)
It works perfectly:
CREATE TABLE sample(dex INT, col VARCHAR(100));
INSERT INTO sample(dex, col)
VALUES (2, 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.');
SELECT *
FROM sample;
LiveDemo
Output:
The "problem" is SSMS grid view that skips newline characters (and others too). Otherwise you will get different rows height like in Excel.
You could observe the same behaviour in SEDE.
LiveDemo-SEDELiveDemo-SEDE-TextView
Output:
You could compare it using:
SELECT 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.';
PRINT 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.';
The CR/LF chars are there, it's just that in the format of your output, they are being ignored.
I've created a fiddle to illustrate this, with 2 VARCHAR columns. In the first one I insert the text with no CR/LF, in the second I include them
CREATE TABLE sample (dex INT, colnocr VARCHAR(50), col VARCHAR(50)) ;
insert into sample (dex, colnocr, col) values
(2,
'This is line 1.' + 'This is line 2.',
'This is line 1.' + CHAR(13) + CHAR(10) + 'This is line 2.'
)
;
if you run the query
SELECT * FROM sample
The result in plain text are:
| dex | colnocr | col |
|-----|--------------------------------|----------------------------------|
| 2 | This is line 1.This is line 2. | This is line 1.
This is line 2. |
but if you run it in tabular :
dex colnocr col
2 This is line 1.This is line 2. This is line 1. This is line 2.
Check it : SqlFiddleDemo
A bit late to this discussion, but in SSMS 2016, there is an option on the Tools | Options menu under Query Results / SQL Server / Results to Grid called "Retain CR/LF on copy or save". Checking this box will allow you to copy values from a cell in a grid result to, say, another query window and still have the line breaks.

New line in TSQL

I am getting records from database as comma separated. I am getting contact
titles as:
greg w.workcerf, ashir ali, asdddfgjk
This is comma separated has been defined in SQL function getCommaListTitle()
What i want is to get these record on new lines as
greg w.workcerf,
ashir ali,
asdddfgjk
Any idea about what should i use in sql function instead of ','
Append after the comma in getCommaListTitle, CHAR(13) + CHAR(10) for a
new line
CHAR(13) is a new line char and CHAR(10) is a line feed.
See http://msdn.microsoft.com/en-us/library/ms187323.aspx
You should do this in your front end, like on data access layer or may be at presentation layer because your application could be any one a web app or a window app and in both there's different in new line syntax like in web we use <br/> tag whereas in window we use /n.
use the replace function
replace(field, ',', ',' + char(13)+char(10)
...however DO NOT do this in your database, database is about DATA and of course it 'should' be presented in some form... but starting with a line break, and finally you'll end with something like:
SELECT #s = '<tr><td>' + firstname + '</td><td>' + substr(lastname, 1, 30) + '</td></tr>'
FROM ....
RETURN '<table>' + #s + '</TABLE>'
and that is not to route to choose grasshopper

SQL Select Error When using Case

CASE WHEN PFW_Access__c = 1
THEN 'New Employee (' + New_Employee_Name__c + ') needs PFW Access'
ELSE ''
END AS PFWAccessDesc,`
The line above is just one of many lines in my select statement. It outputs correctly with New Employee (name) needs PFW Access. What I'm trying to do is to add another field to the output Description_Short__c but when I tried to add it to the statement I receive an error. I'm not sure how to add it in to the statement to show in the output.
is this waht you are after?
CASE WHEN PFW_Access__c = 1
THEN 'New Employee (' + ISNULL(New_Employee_Name__c,'') + ') needs PFW Access '
+ISNULL(Description_Short__c,'')
ELSE ''
END AS PFWAccessDesc,
If I remember correctly from a previous question, Description_Short__c is a text field in your database. If you're trying to do just about anything w/ this column, you're going to have to use cast(Description_Short__c as varchar(max)) instead of Description_Short__c.

Sql Server Split and Concatenation

I have data in the following format in a sql server database table
[CPOID] [ContractPO] [ContractPOTitle]
1 10-SUP-CN-CNP-0001 Drytech
2 10-SUP-CN-CNP-0002 EC&M
I need to write a stored procedure to generate the following result
[CPOID] [ContractPO] [ContractPOTitle] [ConcatField]
1 10-SUP-CN-CNP-0001 Drytech CNP-0001-Drytech
2 10-SUP-CN-CNP-0002 EC&M CNP-0002-EC&M
where [ConcatField] generate the result using split the last two values of the [ContractPOTitle] column and combine with the [ContractPOTitle]
If the ContractPO field is always the same length, you could just do:
SELECT
CPOID,
ContractPO,
ContractPOTitle,
RIGHT(ContractPO, 8) + '-' + ContractPOTitle as [ConcatField]
FROM MyTable
Assuming that the length of the ContractPO field is not fixed AND we have to rely on stripping out the text after the next to last '-', the following SQL will work. It's a bit ugly, but these types of operations are necessary because there doesn't appear to be a LASTINDEX function available out of the box in SQL Server.
SELECT
CPOID,
ContractPO,
ContractPOTitle,
RIGHT(ContractPO, CHARINDEX('-', REVERSE(ContractPO), CHARINDEX('-', REVERSE(ContractPO)) + 1) - 1) + '-' + ContractPOTitle as [ConcatField]
FROM #myTable

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.
char(13) is CR. For DOS-/Windows-style CRLF linebreaks, you want char(13)+char(10), like:
'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
I found the answer here: http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/
You just concatenate the string and insert a CHAR(13) where you want your line break.
Example:
DECLARE #text NVARCHAR(100)
SET #text = 'This is line 1.' + CHAR(13) + 'This is line 2.'
SELECT #text
This prints out the following:
This is line 1.
This is line 2.
Another way to do this is as such:
INSERT CRLF SELECT 'fox
jumped'
That is, simply inserting a line break in your query while writing it will add the like break to the database. This works in SQL server Management studio and Query Analyzer. I believe this will also work in C# if you use the # sign on strings.
string str = #"INSERT CRLF SELECT 'fox
jumped'"
All of these options work depending on your situation, but you may not see any of them work if you're using SSMS (as mentioned in some comments SSMS hides CR/LFs)
So rather than driving yourself round the bend, Check this setting in
Tools | Options
Run this in SSMS, it shows how line breaks in the SQL itself become part of string values that span lines :
PRINT 'Line 1
Line 2
Line 3'
PRINT ''
PRINT 'How long is a blank line feed?'
PRINT LEN('
')
PRINT ''
PRINT 'What are the ASCII values?'
PRINT ASCII(SUBSTRING('
',1,1))
PRINT ASCII(SUBSTRING('
',2,1))
Result :
Line 1
Line 2
Line 3
How long is a blank line feed?
2
What are the ASCII values?
13
10
Or if you'd rather specify your string on one line (almost!) you could employ REPLACE() like this (optionally use CHAR(13)+CHAR(10) as the replacement) :
PRINT REPLACE('Line 1`Line 2`Line 3','`','
')
Following a Google...
Taking the code from the website:
CREATE TABLE CRLF
(
col1 VARCHAR(1000)
)
INSERT CRLF SELECT 'The quick brown#'
INSERT CRLF SELECT 'fox #jumped'
INSERT CRLF SELECT '#over the '
INSERT CRLF SELECT 'log#'
SELECT col1 FROM CRLF
Returns:
col1
-----------------
The quick brown#
fox #jumped
#over the
log#
(4 row(s) affected)
UPDATE CRLF
SET col1 = REPLACE(col1, '#', CHAR(13))
Looks like it can be done by replacing a placeholder with CHAR(13)
Good question, never done it myself :)
I got here because I was concerned that cr-lfs that I specified in C# strings were not being shown in SQl Server Management Studio query responses.
It turns out, they are there, but are not being displayed.
To "see" the cr-lfs, use the print statement like:
declare #tmp varchar(500)
select #tmp = msgbody from emailssentlog where id=6769;
print #tmp
I'd say
concat('This is line 1.', 0xd0a, 'This is line 2.')
or
concat(N'This is line 1.', 0xd000a, N'This is line 2.')
Here's a C# function that prepends a text line to an existing text blob, delimited by CRLFs, and returns a T-SQL expression suitable for INSERT or UPDATE operations. It's got some of our proprietary error handling in it, but once you rip that out, it may be helpful -- I hope so.
/// <summary>
/// Generate a SQL string value expression suitable for INSERT/UPDATE operations that prepends
/// the specified line to an existing block of text, assumed to have \r\n delimiters, and
/// truncate at a maximum length.
/// </summary>
/// <param name="sNewLine">Single text line to be prepended to existing text</param>
/// <param name="sOrigLines">Current text value; assumed to be CRLF-delimited</param>
/// <param name="iMaxLen">Integer field length</param>
/// <returns>String: SQL string expression suitable for INSERT/UPDATE operations. Empty on error.</returns>
private string PrependCommentLine(string sNewLine, String sOrigLines, int iMaxLen)
{
String fn = MethodBase.GetCurrentMethod().Name;
try
{
String [] line_array = sOrigLines.Split("\r\n".ToCharArray());
List<string> orig_lines = new List<string>();
foreach(String orig_line in line_array)
{
if (!String.IsNullOrEmpty(orig_line))
{
orig_lines.Add(orig_line);
}
} // end foreach(original line)
String final_comments = "'" + sNewLine + "' + CHAR(13) + CHAR(10) ";
int cum_length = sNewLine.Length + 2;
foreach(String orig_line in orig_lines)
{
String curline = orig_line;
if (cum_length >= iMaxLen) break; // stop appending if we're already over
if ((cum_length+orig_line.Length+2)>=iMaxLen) // If this one will push us over, truncate and warn:
{
Util.HandleAppErr(this, fn, "Truncating comments: " + orig_line);
curline = orig_line.Substring(0, iMaxLen - (cum_length + 3));
}
final_comments += " + '" + curline + "' + CHAR(13) + CHAR(10) \r\n";
cum_length += orig_line.Length + 2;
} // end foreach(second pass on original lines)
return(final_comments);
} // end main try()
catch(Exception exc)
{
Util.HandleExc(this,fn,exc);
return("");
}
}
This is always cool, because when you get exported lists from, say Oracle, then you get records spanning several lines, which in turn can be interesting for, say, cvs files, so beware.
Anyhow, Rob's answer is good, but I would advise using something else than #, try a few more, like §§##§§ or something, so it will have a chance for some uniqueness. (But still, remember the length of the varchar/nvarchar field you are inserting into..)
In some special cases you may find this useful (e.g. rendering cell-content in MS Report )
example:
select * from
(
values
('use STAGING'),
('go'),
('EXEC sp_MSforeachtable
#command1=''select ''''?'''' as tablename,count(1) as anzahl from ? having count(1) = 0''')
) as t([Copy_and_execute_this_statement])
go