I have three fields that I concatenated into one field, but when I run the query the result-set is correct, but they are not evenly spaced within the one field. How would I space them neatly and correctly. Thank-you for the help.
Here is the query:
SELECT CONVERT(varchar(20),Book)+ Space(2) + '(' + CONVERT(varchar(30),Year)
+ ')' + Space(2) + '(' + CONVERT(varchar(30),Print) + ')' As 'Film Description', Genre,
Cost
FROM Film
Order By Year DESC, Book ASC
Since VARCHAR ignores trailing spaces, you need to use a different data type that doesn't (e.g. CHAR). A few other comments:
be careful about using reserved words such as year and print as column names
be careful about using 'single quotes' as alias delimiters ([square brackets] are more future-proof and harder to muddle with string literals)
you should use the schema prefix (e.g. dbo.Film)
DECLARE #Film TABLE(Book VARCHAR(255), [Year] INT, [Print] VARCHAR(255));
INSERT #Film
SELECT 'a', 2012, 'hello there this is at least 30 characters, right?'
UNION ALL
SELECT 'this must be at least 30 characters too, right?', 2011, 'b';
SELECT CONVERT(CHAR(20), Book)
+ SPACE(2)
+ '(' + CONVERT(CHAR(4),[Year]) + ')'
+ SPACE(2)
+ '(' + CONVERT(CHAR(30), [Print]) + ')'
As [Film Description]
FROM #Film
Order By [Year] DESC, Book;
Use Convert(Char( instead of Convert(Varchar(
Varchars have the spaces stripped off..
Related
How to check if any of this !##$%^&*()_-+ special characters exist in a string ?
i tried
SELECT PATINDEX('!##$%^&*()_-+', 'test-');
SELECT PATINDEX('[!##$%^&*()_-+]', 'test-');
SELECT PATINDEX('%[!##$%^&*()_-+]%', 'test-');
but all returns 0, it should return 5, any help ?
The - is a special character in the LIKE or PATINDEX() pattern. If it is anywhere other than the first position, it is a range of characters -- such as all digits being represented by [0-9].
You can do what you want by moving the condition:
PATINDEX('%[-!##$%^&*()_+]%', 'test-'),
Unfortunately, PATINDEX() patterns don't support an escape character. You can also express this logic as a LIKE and CASE:
(CASE WHEN 'test-' LIKE '%[-!##$%^&*()_+]%' ESCAPE '$' THEN 1 ELSE 0 END)
Or using a "not" pattern:
(CASE WHEN 'test-' NOT LIKE '%[^0-9a-zA-Z]%' THEN 0 ELSE 1 END)
You can use negation:
SELECT PATINDEX('%[^a-Z]%', 'test-');
This will find a character NOT in the range a-Z.
SELECT PATINDEX('%[-+!_#()*^#$%&]%', 'test-');
this solves my issue returns 5 the positon of -.
Apperently order matters.
DECLARE #myString VARCHAR(100) ='test-'
IF (#myString LIKE '%[^a-zA-Z0-9]%')
PRINT 'Contains "special" characters'
ELSE
PRINT 'Does not contain "special" characters'
select patindex('%[' + char(45) + ']%', 'test-');
But symbol '-' not working in range values, replace this symbol on another symbol
Next example find only writable symbols in #string:
declare #string varchar(max) = char(8) + char(9) + char(10) + char(11) + char(12) + char(13) + '-test string-';
select patindex(%[' + char(33) + '-' + char(255) + ']%', replace(#string, '-', '#'))
I'm trying to concatenate fields with VarChar and Date into one VarChar field for a database of tourdates. So, imagine a table of, say, Madonna tour dates as such:
TourName TourStDt TourEndDt
Like A Virgin 3/5/1985 12/1/1985
Material Girl 1/15/1986 10/10/1987
I'm sure the dates aren't accurate, but whatever... Anyway, so I want to create a query that concatenates the TourName, TourStDt and TourEndDt fields so that it looks like this:
Like A Virgin (3/5/1985 to 12/1/1985)
Material Girl (1/15/1986 to 10/10/1987)
I wrote a query like this:
Select DISTINCT
TourID,
TourName + '(' + TourStDt + ' to ' + TourEndDt + ')' AS TourName2
from [tblTours]
ORDER BY [TourID] ASC
When I do this, I get an error:
The data types nvarchar and date are incompatible in the add operator.
Can anyone tell me how to produce the results I outlined above?
You need to convert the values to strings:
Select DISTINCT TourID,
TourName + '(' + convert(varchar(255), TourStDt) + ' to ' + convert(varchar(255), TourEndDt) + ')' AS TourName2
from [tblTours]
ORDER BY [TourID] ASC ;
I would suggest that you add a third argument to convert() specifying the date format.
I have a large table of data where some of my columns contain line breaks. I would like to remove them and replace them with some spaces instead.
Can anybody tell me how to do this in SQL Server?
Thanks in advance
SELECT REPLACE(REPLACE(#str, CHAR(13), ''), CHAR(10), '')
This should work, depending on how the line breaks are encoded:
update t
set col = replace(col, '
', ' ')
where col like '%
%';
That is, in SQL Server, a string can contain a new line character.
#Gordon's answer should work, but in case you're not sure how your line breaks are encoded, you can use the ascii function to return the character value. For example:
declare #entry varchar(50) =
'Before break
after break'
declare #max int = len(#entry)
; with CTE as (
select 1 as id
, substring(#entry, 1, 1) as chrctr
, ascii(substring(#entry, 1, 1)) as code
union all
select id + 1
, substring(#entry, ID + 1, 1)
, ascii(substring(#entry, ID + 1, 1))
from CTE
where ID <= #max)
select chrctr, code from cte
print replace(replace(#entry, char(13) , ' '), char(10) , ' ')
Depending where your text is coming from, there are different encodings for a line break. In my test string I put the most common.
First I replace all CHAR(10) (Line feed) with CHAR(13) (Carriage return), then all doubled CRs to one CR and finally all CRs to the wanted replace (you want a blank, I put a dot for better visability:
Attention: Switch the output to "text", otherwise you wont see any linebreaks...
DECLARE #text VARCHAR(100)='test single 10' + CHAR(10) + 'test 13 and 10' + CHAR(13) + CHAR(10) + 'test single 13' + CHAR(13) + 'end of test';
SELECT #text
DECLARE #ReplChar CHAR='.';
SELECT REPLACE(REPLACE(REPLACE(#text,CHAR(10),CHAR(13)),CHAR(13)+CHAR(13),CHAR(13)),CHAR(13),#ReplChar);
I have the same issue, means I have a column having values with line breaks in it. I use the query
update `your_table_name` set your_column_name = REPLACE(your_column_name,'\n','')
And this resolves my issue :)
Basically '\n' is the character for Enter key or line break and in this query, I have replaced it with no space (which I want)
Keep Learning :)
zain
I have the following SQL Query in Access:
SELECT ID, CurrencyName + ' (' + CurrencySymbol + ')' AS [Currency],
CurrencyLocation, CurrencySymbol FROM Currencies ORDER BY SortOrder
What I noticed is that I get a full table of results except if if the field CurrencySymbol is left NULL or empty. If the CurrencySymbol field is null, rather than Concatenate nothing, Access skips over the record and continues as shown below
.
Did I get something wrong or is there a better way to write this Query?
If you concatenate strings with +, string + NULL yields NULL.
If you concatenate strings with &, string & NULL yields string.
Thus, you have two options to fix this:
Option 1: CurrencyName + ' (' + Nz(CurrencySymbol, '') + ')'. Nz (NullToZero) converts Null values to its second argument.
Option 2: CurrencyName & ' (' & CurrencySymbol & ')'
You can use this fact to create an expression that only shows the parenthesis when a currency symbol is present (Credit for this idea goes to this blog post):
CurrencyName & (' (' + CurrencySymbol + ')') will yield Points and Euro (€).
That's because concatenating a string and NULL results in NULL.
SELECT ID, CurrencyName + ' (' + Iif(IsNull(CurrencySymbol), '', CurrencySymbol) + ')'
AS [Currency], CurrencyLocation, CurrencySymbol
FROM Currencies
ORDER BY SortOrder
I have table that one of the fields needs to be cleaned up. The basic table structure is as follows:
create table testComments(id int, comments text)
In the comments column some of the rows had to many "carriage returns" (char(13)) and "line feed" (char(10)). If there is more then one grouping per line I need to be able to modify it. The basic select statement that I have so far is a follows:
select count(id)
from testComments
where comments like('%' + char(13) + char(10) + char(13) + char(10) + '%')
This query will find the results
"This is a entry in the testComments crlf
crlf
In the comments field that works"
Although the query will not find the results if the comment is listed as follows:
"This is an entry in the testComments crlf
crlf
crlf
That will not work"
The query will only return a count of 1 entry for the above data. Any idea how I can change the query to return a count of 2?
Using the code you gave us, your query should work properly. So the details appear to be different, and I suspect that GolezTrol's comment is on the right track -- some of the CRLF pairs are really just solo CR or LF characters.
Try this:
select count(id)
from #testComments
where comments like('%' + char(13) + char(10) + char(13) + char(10) + '%')
or comments like('%' + char(10) + char(10) + '%')
or comments like('%' + char(13) + char(13) + '%')
The query will only return a count of 1 entry for the above data. Any idea how I can change the query to return a count of 2?
I think you're misunderstanding something basic.
The COUNT-Function returns the count of all returned rows. In your example it is still returning one row.
So no matter if you have this:
"This is an entry in the testComments crlf
crlf
That will not work"
Or this:
"This is an entry in the testComments crlf
crlf
crlf
crlf
crlf
That will not work"
COUNT will still return 1! (If you have one record that has this string)
EDIT: If you literally want to count the characters for each row, here you go:
SELECT LEN(REPLACE(myColumn, 'yourCharacter', '')) FROM ...
Try using a virtual table. I added up the differences in length of the comments field and the comments field after replacing the characters that you are looking for with empty strings.
SELECT SUM(DIF) FROM (
select
(
LEN(comments)
- LEN( REPLACE( REPLACE ( comments, char(13), ''),char(10),'') )
)
AS DIF
from #testComments
) as VT;