How to add commas to a value? - sql

Is it possible to add to the result value inside a column commas?
I mean for example I create new value:
insert into dbo.SAPID (TEST2)
Values (110)
I want the value to be with commas='110' inside the column result set.

insert into dbo.SAPID (TEST2)
Values (char(39) + '110' + char(39))

Please clarify your request. It seems like TEST2 is an Integer and you would like to return a string with single quotes surrounding it.
To do this you can cast the value when selected and append the quote:
SELECT '''' + CAST( TEST2 AS NVARCHAR(10) ) + '''' FROM SAPID

I believe you are thinking of single quotes '' like you provided in your example above:
I want the value to be with commas='110'
In that case, you could just do something like this:
--your column in the table will need to be a string instead of int
create table dbo.SAPID (TEST2 nvarchar(10));
--insert string value with single quotes
insert into dbo.SAPID(TEST2)
VALUES ('''' + '110' + '''');
--select statement
select * from dbo.SAPID
Single quote is an escape character in SQL much like other languages.Single quotes are escaped by doubling them up, just as shown in above example.
SQL Fiddle Demo

Related

Insert a period before the last two characters of a sql column

Hello I have a column in sql and I need to insert a "." before the last two characters. The column is not fixed length. Can someone help me go about this?
You can do it with an UPDATE and SUBSTRING.
UPDATE table
SET column = (SELECT SUBSTRING(column, 1, LEN(column)-2)
+ '.'
+ SUBSTRING(column, LEN(column)-1, LEN(column))
If you would like to check what the query will do to your column, just use:
SELECT
SUBSTRING(column, 1, LEN(column)-2)
+ '.'
+ SUBSTRING(column, LEN(column)-1, LEN(column))
FROM table
It looks messy but this should do it:
SELECT LEFT(COL_NAME, LEN(COL_NAME)-1)+'.'+RIGHT(COL_NAME,1)
FROM Table
Or if you want to update the value in the database rather than just the output
Update Table
SET COL_NAME = LEFT(COL_NAME, LEN(COL_NAME)-1)+'.'+RIGHT(COL_NAME,1)
You can use sp_rename like this:
EXEC sp_rename 'dbo.DatabaseName.ColumnName', 'ColumnNa.me', 'COLUMN';
If you need to apply this to multiple columns, then I would suggest using the substring method. No real use to do it for just one UPDATE on a column.
Question is not very clear. If you are trying to insert . before last 2 characters into the column data, you could use STUFF() function.
For ex:
Declare #s varchar(50) = '12345678'
Select Stuff(#s, Len(#s)-1, 0, '.')
--> 123456.78
Applying to your table query:
Select Stuff(yourCol, Len(yourCol)-1, 0, '.')
From yourTable
Please note that If Len(yourCol) is less than 2, a null string will be returned.

struggling with creating Insert query

I create Insert statement for organization table like this:
select'Insert into Organizations(Name,ContactPerson,ContactNumber,Mobilenumber)values('''+Nameofthecompany+''+','+Nameofthepersonresponsibleforrecruitment+','+PhoneNumber+','+MobileNumber+''')' from Organization
When I execute this statement I get insert statement. But the issue is where the value is null, it shows all columns null.
Example: (in database)
Name: xxxx
ContactPerson: zzzz
ContactNumber:444444
MobileNumber: null
so my insert statement looks like:
Null.
I want only that column provide null. other details showing properly. Is there any way in sql server? Help me anyone...
The result of concatenating anything to NULL, even itself, is always NULL. Workaround with ISNULL function:
select'Insert into Organizations(Name,ContactPerson,ContactNumber,Mobilenumber)
values('''+ISNULL(Nameofthecompany, 'NULL')+''+','
+ISNULL(Nameofthepersonresponsibleforrecruitment, 'NULL')+','
+ISNULL(PhoneNumber, 'NULL')+','
+ISNULL(MobileNumber, 'NULL')+''')'
from Organization
Demo on SQLFiddle
Sure - just use ISNULL(..) to turn a NULL into e.g. an empty string:
SELECT
'INSERT INTO Organizations(Name, ContactPerson, ContactNumber, Mobilenumber) VALUES(''' +
ISNULL(Nameofthecompany, '') + '' + ',' +
ISNULL(Nameofthepersonresponsibleforrecruitment, '') + ',' +
ISNULL(PhoneNumber, '') + ',' + ISNULL(MobileNumber,'') + ''')'
FROM Organization
When you are adding each of the parameters to the SQL statement, you need to check whether they're null, and if so use the keyword NULL, otherwise include a literal string surrounded with single quotes, but bearing in mind that if the string contains any single quotes, they need to be replaced with two single quotes.
Update the SQL for each parameter something like the following:
CASE WHEN MobileNumber IS NULL THEN 'NULL' ELSE '''' + REPLACE(MobileNumber, '''', '''''') + '''' END

How to include double quotes in select statement?

i have a table like
id name
10 bob
20 bill
i want to select only name column in output with double quotes
like select '"'||name||'"' from table
it is giving me the correct output but is there any other way without using concatenation ...
Thank you..
Using this you can get result with double quotes
' " ' + columnName + ' " '
Example
Query
SELECT '"'+Name+'"' , Age
FROM customer
Result
"Viranja" | 27
Create a virtual column that adds the quotes:
CREATE TABLE
....
quoted_name VARCHAR2 GENERATED ALWAYS AS ('"' || name || '"') VIRTUAL,
...
See here for more information:
http://www.oracle-base.com/articles/11g/virtual-columns-11gr1.php
this will check for any name with at least one double quote
select * from table
where name like '%"%'
If your intention is to be able to "export" the result into space or comma-delimited text file, use a view to "format" your data. You will need to this for your date columns as well.
There are two scenarios you would want to use double quotes in sql in my opinion.
Updating a string column which contains single multiple quotes in it. (you have to escape it)
updating blog contents in columns which you cant edit in "edit top 200 rows"
so, if you want to use double quotes follow this.
SET QUOTED_IDENTIFIER OFF
BEGIN
DECLARE #YourSqlStmt AS VarChar(5000) -- Declare a variable.
SET #YourSqlStmt = "ok"
PRINT #YourSqlStmt -- do your operations here
END
This saves time and you need not to escape single quotes in a existing string content of the column.

Alter All Column Values using TRIM in SQL

I want to modify (Remove all white spaces) all the values of Column
"Name" .
How do I use TRIM and modify all column values of Name .
Example :
Before : " rishi.ranka " After : "rishi.ranka"
Thank you very much in Advance.
Use a combination of LTRIM (Left Trim) & RTRIM (Right Trim):
UPDATE [TableName]
SET [Name]=LTRIM(RTRIM([Name]))
If the datatype of name column is varchar then don't need to use rtrim function the right side spaces will be automatically trim. use only LTRIM only.
update tablename
set name = ltrim(name)
where <condition>;
Run this see the how it trims the right spaces automatically.
DECLARE #mytb table
(
name varchar(20)
);
INSERT INTO #mytb VALUES (' stackoverflow ');
SELECT len(name) from #mytb;
SELECT ltrim(name),len(ltrim(name)) from #mytb;

String manipulation SQL

I have a row of strings that are in the following format:
'Order was assigned to lastname,firsname'
I need to cut this string down into just the last and first name but it is always a different name for each record.
The 'Order was assigned to' part is always the same.......
Thanks
I am using SQL Server. It is multiple records with different names in each record.
In your specific case you can use something like:
SELECT SUBSTRING(str, 23) FROM table
However, this is not very scalable, should the format of your strings ever change.
If you are using an Oracle database, you would want to use SUBSTR instead.
Edit:
For databases where the third parameter is not optional, you could use SUBSTRING(str, 23, LEN(str))
Somebody would have to test to see if this is better or worse than subtraction, as in Martin Smith's solution but gives you the same result in the end.
In addition to the SUBSTRING methods, you could also use a REPLACE function. I don't know which would have better performance over millions of rows, although I suspect that it would be the SUBSTRING - especially if you were working with CHAR instead of VARCHAR.
SELECT REPLACE(my_column, 'Order was assigned to ', '')
For SQL Server
WITH testData AS
(
SELECT 'Order was assigned to lastname,firsname' as Col1 UNION ALL
SELECT 'Order was assigned to Bloggs, Jo' as Col1
)
SELECT SUBSTRING(Col1,23,LEN(Col1)-22) AS Name
from testData
Returns
Name
---------------------------------------
lastname,firsname
Bloggs, Jo
on MS SQL Server:
declare #str varchar(100) = 'Order was assigned to lastname,firsname'
declare #strLen1 int = DATALENGTH('Order was assigned to ')
declare #strLen2 int = len(#str)
select #strlen1, #strLen2, substring(#str,#strLen1,#strLen2),
RIGHT(#str, #strlen2-#strlen1)
I would require that a colon or some other delimiter be between the message and the name.
Then you could just search for the index of that character and know that anything after it was the data you need...
Example with format changing over time:
CREATE TABLE #Temp (OrderInfo NVARCHAR(MAX))
INSERT INTO #Temp VALUES ('Order was assigned to :Smith,Mary')
INSERT INTO #Temp VALUES ('Order was assigned to :Holmes,Larry')
INSERT INTO #Temp VALUES ('New Format over time :LootAt,Me')
SELECT SUBSTRING(OrderInfo, CHARINDEX(':',OrderInfo)+1, LEN(OrderInfo))
FROM #Temp
DROP TABLE #Temp