SQL Aliases ',' and + function - sql

What is the function of ',' and + on the given following SQL script?
SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS Address
FROM Customers;

' is the delimiter for a string literal. ', ' is a string containing a comma and a blank.
So obviously this query selects CustomerName plus a concatenation of address and a comma and a blank and city and a comma and a blank and country, calling this new string Address.
The DBMS in question accepts a + for string concatenation. Either additionally to or instead of the standard operator || .

This query will give you two columns: CustomerName and Address.
The Address will be composed of: Address, City, PostalCode and Country seperated by comma (,)
The + sign is used for concatenating strings in this specific SQL query.
Some DBMS like (MySql and Sybase) use the + for concatenation of strings.

Related

usage of concat function

Write a query to display address details by concatenating address and city of students . Give an alias as Address and sort the result based on the concatenated column in descending order.
You can Concatenate using pipe symbol || in oracle or use + symbol in sql server.Once you concatenate give alias name (address1 || address 2)as address, sorting is done by order by clause .
provide some sample to help you

LEN(firstName) + LEN(lastName) does not equal LEN(firstName + lastName)

I'm trying to search a table based on the concatentation of the firstName and lastName columns. Both of these are defined as NVARCHAR(50) NOT NULL
The query sometimes fails to find a match because the concatenated column is padded with extra spaces. Here's the query:
SELECT firstName + lastName AS fullName, LEN(firstName) + LEN(lastName) AS realLength, LEN(firstName + lastName) AS concatLength FROM UsersTable
And here's an image with the results:
What is the deal with this? How can I avoid the extra spaces? If I do SELECT RTRIM(firstName) + RTRIM(lastName) ... I get the correct full name with no extra spaces, but using RTRIM is too expensive because my data set is very big. This would lead me to think that the issue is the data itself, except that LEN(firstName) is the same as LEN(RTRIM(firstName))
You have spaces at the end of your FirstName. It is easy enough to check that the following returns 4:
select len(N'abcd ')
This is a property of the varchar() data types and len(). Of course, when you concatenate them, then SQL Server decides to recognize the spaces at the end.
This behavior is documented in the "Remarks" section of the documentation:
Remarks
LEN excludes trailing blanks. If that is a problem, consider using the
DATALENGTH (Transact-SQL) function which does not trim the string. If
processing a unicode string, DATALENGTH will return twice the number
of characters.
As the comments suggest, you can ltrim()/rtrim() the values before concatenating them. Or, use like.

Replace quote in SQL Select

I have a scenario in my vb.net project where users need to select a name from a combobox (or type a new name).
Names of course can have ' as in Tina O'Hara which in the database would be stored as Tina O''Hara.
My combobox is populated from a sql select command. I have tried to use a Replace so that the names display correctly in the dropdown.
SqlStr = "SELECT Replace(ContactName, '''', ''') AS ddlText FROM tbl_Visits Where CustID = " & hd_CustID.value & " ORDER By ContactName"
PopulateCMBX(cmbx_ContactName, SqlStr, "Please Select")
PopulateCMBX... This gets a list of names from the supplied SqlStr and populates the combobox itemlist with a 'Please Select' as the first option.
SqlStr is producing an error as there is not a matching set of ' how do I fix this. Thanks
When referencing single quotes in MS-SQL, you need to escape each single quote (') with two single quotes ('').
If the name is stored in the database with two single quotes, such as (''), then when you do the replace you need to use four single quotes (''''). In addition to these, you need to enclose the string with single quotes.
What this means is that your replace should look like this:
SqlStr = "SELECT Replace(ContactName, '''''', '''') ...
The 2nd param in the replace has 6 single quotes: 4 to represent the two single quotes you are replacing, and 2 to make it a string. The 3rd param has 4 single quotes: 2 to represent a single escaped quote and two to make it a string.
Try with this, maybe not the best solution but it works (check this example):
select Replace(Replace(ContactName, '''', '$&'),'$&$&','''') from tbl_Visits
Note that $& is like a key that should not affect the values ​​in your field, for example, could be a word: &&k&& or %%key%%, etc.
Back to clarify, it is not the best solution, but sometimes i've used.

SQL 'LIKE' query using '%' where the search criteria contains '%'

I have an SQL query as below.
Select * from table
where name like '%' + search_criteria + '%'
If search_criteria = 'abc', it will return data containing xxxabcxxxx which is fine.
But if my search_criteria = 'abc%', it will still return data containing xxxabcxxx, which should not be the case.
How do I handle this situation?
If you want a % symbol in search_criteria to be treated as a literal character rather than as a wildcard, escape it to [%]
... where name like '%' + replace(search_criteria, '%', '[%]') + '%'
Use an escape clause:
select *
from (select '123abc456' AS result from dual
union all
select '123abc%456' AS result from dual
)
WHERE result LIKE '%abc\%%' escape '\'
Result
123abc%456
You can set your escape character to whatever you want. In this case, the default '\'. The escaped '\%' becomes a literal, the second '%' is not escaped, so again wild card.
See List of special characters for SQL LIKE clause
The easiest solution is to dispense with "like" altogether:
Select *
from table
where charindex(search_criteria, name) > 0
I prefer charindex over like. Historically, it had better performance, but I'm not sure if it makes much of difference now.
To escape a character in sql you can use !:
EXAMPLE - USING ESCAPE CHARACTERS
It is important to understand how to "Escape Characters" when pattern matching. These examples deal specifically with escaping characters in Oracle.
Let's say you wanted to search for a % or a _ character in the SQL LIKE condition. You can do this using an Escape character.
Please note that you can only define an escape character as a single character (length of 1).
For example:
SELECT *
FROM suppliers
WHERE supplier_name LIKE '!%' escape '!';
This SQL LIKE condition example identifies the ! character as an escape character. This statement will return all suppliers whose name is %.
Here is another more complicated example using escape characters in the SQL LIKE condition.
SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!%' escape '!';
This SQL LIKE condition example returns all suppliers whose name starts with H and ends in %. For example, it would return a value such as 'Hello%'.
You can also use the escape character with the _ character in the SQL LIKE condition.
For example:
SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!_' escape '!';
This SQL LIKE condition example returns all suppliers whose name starts with H and ends in _ . For example, it would return a value such as 'Hello_'.
Reference: sql/like
Select * from table where name like search_criteria
if you are expecting the user to add their own wildcards...
You need to escape it: on many databases this is done by preceding it with backslash, \%.
So abc becomes abc\%.
Your programming language will have a database-specific function to do this for you. For example, PHP has mysql_escape_string() for the MySQL database.
Escape the percent sign \% to make it part of your comparison value.
May be this one help :)
DECLARE #SearchCriteria VARCHAR(25)
SET #SearchCriteria = 'employee'
IF CHARINDEX('%', #SearchCriteria) = 0
BEGIN
SET #SearchCriteria = '%' + #SearchCriteria + '%'
END
SELECT *
FROM Employee
WHERE Name LIKE #SearchCriteria

MYSQL merge columns

I'm using MySQL and do a select:
SELECT LTRIM(Firstname + ' ' Lastname) AS Fullname FROM Persons
My result is 0 for every result.
Even if i remove the LTRIM, Using CONCAT is giving the same problem.
You are arithmetically adding the string values together; unless you have "1ohn 5mith" in the db, this will always be 0.
Does SELECT LTRIM(CONCAT(Firstname,' ',Lastname)) AS Fullname FROM Persons give you the same problem? (note that there are 3 parameters to CONCAT() here: Firstname, a one-character string containing a space, and Lastname; this function takes as many arguments as you throw at it and outputs them as a string)