How to save and Print new line character using SQL server 2008 - sql

I am trying to save data to the database with Multiline textbox.
and another process is to read from the database and prints to a text file.
My problem is:
1) when I am trying to save the data in the database as new line character its taking unusally number of spaces between two words.
Please can any body help me out how to insert new line character in to the database.
thanks

Char(13) is a carriage return and Char(10) is a line feed.
so...
UPDATE tblEXAMPLE
SET Contents=#FIRSTLINE + chAr(13) + chAr(10)
+ #secondline + chAr(10) + chAr(13)
+ #lastline
WHERE KEY=#PRIMARYKEy

Related

How to give line break between two strings in single column?

I have used single column to store multiple comments . In that column i have to store every comments in new line so that i can able to differentiate the comments.
I have tried CHAR(13) and CHAR(13) + CHAR(10) between two strings . But it's not working.I shown the records in single line.
Tried code:
DECLARE #text NVARCHAR(100)
SET #text = 'This is line 1.' + CHAR(13) + 'This is line 2.'
SELECT #text
Please suggest the solution.
You can use PRINT statement instead of SELECT statement to achieve what you want.
For example, you can use any of the followings:
PRINT 'This is line 1.' + CHAR(13) + 'This is line 2.'
Or
PRINT 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
Or
PRINT CONCAT(N'This is line 1.', 0xd000a, N'This is line 2.')
UPDATE: According to this forum,
You can not see char(13) in SSMS in the Grid format. This character is there and you can see it if you output the result into report, into text, into Excel. But in SSMS grid you can not see this character.
You can change settings from "Results to Grid" to "Results to Text"
from menu using the following steps:
Query -> Results to -> Results to Text
Then you will be able to view line break between two strings using any of the followings
SELECT 'This is line 1.' + CHAR(13) + 'This is line 2.'
Or
SELECT 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
Or
SELECT CONCAT(N'This is line 1.', 0xd000a, N'This is line 2.')
another way
select concat(N'This is line 1.', 0xd000a, N'This is line 2.')
or
select 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'

Enter key issue in SQL

I have a column that is defined as a nvarchar(100).
Sometimes office users press enter key wrongly and it causes problems in some applications. When I check the value it seems like double space character in SQL Server. Now my mission is finding the records that has this situation. I tried the code below to find the problematic records:
DECLARE #NewLineChar AS CHAR(2) = CHAR(10) + CHAR(13);
SELECT *
FROM TBLCASABIT
WHERE CARI_ISIM LIKE '%'+CHAR(10) + CHAR(13)+'%'
but it doesn't return the records I need.
If I use double space character I can see the test record I put and some other records has double space character. So I can't be sure if other records have the same situation or not.
How can I handle this situation? Any help will be appreciated.
I believe you are getting the order of CHAR(10) and CHAR(13) backwards. Here is what each of these characters is:
CHAR(13) - carriage return, or \r
CHAR(10) - line feed, or \n
In Windows, \r\n is a line ending, while in Unix \n by itself is interpreted as a line ending. So you should be searching for CHAR(13) followed immediately by CHAR(10), and not the other way around. Try the following query:
SELECT *
FROM TBLCASABIT
WHERE CARI_ISIM LIKE '%' + CHAR(13) + CHAR(10) + '%'
References:
MSDN Social
DOS vs. Unix Line Endings

new line into SELECT query sql server 2005

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.

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

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