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
DECLARE #name1 VARCHAR(20),
#name2 VARCHAR(20)
SET #name1 = 'Hello'
SET #name2 ='World'
SELECT #name1 + CHAR(13)+CHAR(10) + #name2
Reslut is
Hello World
But I want Result Like this
Hello
World
char(13)+Char(10) not working for Line Feed (\n) and Carriage Return (\r)
Table Result will not show newline. Print it like below.
DECLARE #NewLineChar AS CHAR(2) = CHAR(13) + CHAR(10)
PRINT ('SELECT FirstLine AS FL ' +#NewLineChar + 'SELECT SecondLine AS SL' )
You need to switch to Result to Text to see the result in new line i.e, press CTRL + T and then execute the query.
Output:
------------------------------------------
Hello
World
(1 row(s) affected)
You can find this good reference to see why I say it is not possible:
When using the results to grid option, we use the standard Windows
grid control to display the results. This grid control treats each
cell value as a plain text and hence the new line characters are
ignored. The Save as function when executed from the results section
just takes the content from the grid as it is and hence the newline is
not found in the new file created from the grid. However if you use
the results to text option or the results to file the new line
characters are retained. SSMS is not really intended to be a reporting
tool, so we are unable to spend much time on the result formatting,
especially if some work arounds exist like mentioned above.
DECLARE #name1 VARCHAR(20),
#name2 VARCHAR(20)
SET #name1 = 'Hello'
SET #name2 ='World'
SELECT #name1
Union
select #name2
Try with this...
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
I have a lengthy stored procedure that builds a query string. It works fine until I add in a 'LIKE' description field (text) which has a wildcard in it, see below:
IF #AdDescription IS NOT NULL
IF #AdSection IS NOT NULL
BEGIN
SET #SQL = #SQL + #Wand + 'na.Section = '' + #AdDescription + '''
SET #Wand = ' AND '
END
ELSE
BEGIN
SET #SQL = #SQL + #Wand + '(na.AdDesc LIKE ''' + #AdDescription + '%'')'
SET #Wand = ' AND '
END
I've tried a few variations but as soon as #AdDescription has anything in it it fails. Is there something obvious that I am missing?
You are missing an apostrophe in your first "SET #SQL" line. There should be 3 apostrophes before you add the #AdDescription. The color coding in your code above shows this problem. The plus signs are red instead of black.
Try using print to see the SQl you have created, then you will likely see the error. And try really hard to avoid dynamic sql, it's hard to maintain, test, and debug properly.
Instead of exec the SQl just have it do:
Print #SQL
This will print the SQL Statement.
We usually havea debug parameter on any stored proc that uses dynamic SQl abd if it is set to 1, it prints the SQL and if it is set to 0 (the default), it executes the SQL. This makes it easier to see what is being created for a set of values later when the proc fails in production becasue of some obscure condition you didn't consider.
YOu can also get the SQl executed by running profiler, but usually it's simpler to just run with the same values in debug mode.
Edit Maybe it's just the quotes? I've added some spaces so the escaping is clearer.
IF #AdDescription IS NOT NULL
IF #AdSection IS NOT NULL
BEGIN
SET #SQL = #SQL + #Wand
+ 'na.Section = ' ''' + #AdDescription + ''' '
SET #Wand = ' AND '
END
ELSE
BEGIN
SET #SQL = #SQL + #Wand
+ '(na.AdDesc LIKE ' ''' + #AdDescription + '%'' )'
END
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