Using ColdFusion and Microsoft SQL we are exporting data to an Excel Spreadsheet using the cfx_excel plugin. The data contains a varchar(6000) which has CHAR(13)/line-breaks inputted in each entry.
The line-breaks are appearing as square brackets every time the report is generated in Excel format.
How would I go about removing the CHAR(13) within a SQL query?
Thank you.
try this
update YourTable
set YourColumn =replace(YourColumn,CHAR(13),'')
or just for a select
SELECT replace(YourColumn,CHAR(13),'')
FROM YourTable
for char(10) and char(13) you can do this
SELECT replace(replace(YourColumn,CHAR(13),''),CHAR(10),'')
FROM YourTable
'' will replace it with a blank, if you want a space then use ' ' instead of ''
To replace both char(10) and char(13) you should be able to just do a
replaceList(textToReplaceIn,"#chr(10)#,#chr(13)#",",")
If that doesn't work you can just do 2 replaces as in
replace(replace(textToReplaceIn,chr(10),"","all"),chr(13),"","all")
Related
I am writing a SELECT query that has multiple id, and I have to manually add '','' (e.g '12L','22C').
I have around 2000 id in an Excel sheet.
Is there any quicker way to add '','' to all the ID?
SELECT id, name
FROM table
WHERE id IN ('12L', '22C', 33j, 7k, 44J, 234C)
DECLARE #Ids VARCHAR(MAX) = '12L,22C,33j,7k,44J,234C'
--Your question's answer.
DECLARE #Splitted VARCHAR(MAX) = STUFF((
SELECT CONCAT(',''', value, '''')
FROM string_split(#Ids, ',')
FOR XML PATH('')), 1, 1, '')
SELECT #Splitted
--'12L','22C','33j','7k','44J','234C'
OR simplified
SELECT id, name from table where id in (SELECT value FROM string_split(#Ids, ','))
string_split: for more information docs
concat: for more information docs
Here is a conceptual example for you. It will work in SQL Server 2012 onwards.
It is a three step process:
Convert input string into XML.
Convert XML into a relational resultset inside the CTE.
Join with a DB table.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (ID INT IDENTITY PRIMARY KEY, Code VARCHAR(10), City VARCHAR(50));
INSERT INTO #tbl (Code, City) VALUES
('10T', 'Miami'),
('45L', 'Orlando'),
('50Z', 'Dallas'),
('70W', 'Houston');
-- DDL and sample data population, end
DECLARE #Str VARCHAR(100) = '22C,45L,50Z,105M'
, #separator CHAR(1) = ',';
DECLARE #parameter XML = TRY_CAST('<root><r><![CDATA[' +
REPLACE(#Str, #separator, ']]></r><r><![CDATA[') +
']]></r></root>' AS XML);
;WITH rs AS
(
SELECT c.value('.', 'VARCHAR(10)') AS Code
FROM #parameter.nodes('/root/r/text()') AS t(c)
)
SELECT t.*
FROM #tbl AS t INNER JOIN
rs ON t.Code = rs.Code;
Two alternatives if you're ok doing the transformation outside of SQL.
As one of the comments on your question suggests, you could do this in Excel using this as a formula:
="'" & A1 & "',"
Replace the "A1" with whatever cell your first ID is in. After you enter the formula, click the cell it's in, and there will be a small square on the bottom right. Double click that and it will apply the formula to every cell in the column, automatically shifting the cell reference to match the current row. You can then copy the values from that column and erase the comma at the end.
You could also use an editor that supports regular expression like SSMS, Azure Data Studio, Notepad++, etc and do a Find+Replace:
Paste your IDs in
Hit the replace hotkey (Ctrl+H in all 3 of the ones I listed). There will be an option to enable Regular Expression (SSMS/ADS have a little .* icon, Notepad++ has a labeled radio button). Click it
Find this:
(\w+)
Replace it with this
'$1',
Copy and paste the formatted IDs into your query. Same as above, you'll have to erase the final comma
This will work as long as your IDs are alphanumeric with no spaces, punctuation, etc. If the formatting is more complex, the regex (the (\w+) you search for) will need to be more complex as well. Using this strategy, you could also get rid of the linebreaks by using the regex (\w+)\r\n.
hei, you can use Function CONCATENATE in Excel before you copy those ID in sql.
I'm using SQL Server Management Studio.
Let's say I have a table with 100 fields, and I want to show 75 of them, how can I show all of the columns so then I can just comment out the ones I don't want? Basically de-nest the *...
Thanks!
You can open the columns "folder" under the table in the object explorer and drag the folder to your query window. It will generate the entire list of columns with commas. Not nicely formatted since it drops all the columns on a single line but it works.
You could also use sys.columns to help. This would let you copy and paste the results into your query window.
select name + ', '
from sys.columns
where object_id = object_id('YourTableName')
There are also lots and lots of third party tools that can do this kind of thing.
SSMS support GUI tool for it , but if you don't like GUI then you can use below script
declare
#table_name varchar(200) = 'Employees',
#column_sql varchar(max) = 'select ';
select
#column_sql = #column_sql + 'T.[' + COLUMN_NAME + '],'
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME=#table_name;
select left(#column_sql,len(#column_sql)-1) + ' from ' + #table_name + ' T';
In NorthWind Employee Sample will get below result :
select
T.[EmployeeID],T.[LastName],T.[FirstName],T.[Title],
T.[TitleOfCourtesy],T.[BirthDate],T.[HireDate],
T.[Address],T.[City],T.[Region],T.[PostalCode],
T.[Country],T.[HomePhone],T.[Extension],T.[Photo],
T.[Notes],T.[ReportsTo],T.[PhotoPath]
from Employees T
I am trying to add a '~' sign between two columns in SQL Server:
SELECT CODE + '~' + NAME FROM TEST_TABLE
It should return 'CCC~NNN' but it displays a newline instead of '~'. How can I fix this?
Maybe theres a hidden new line char in one of the selected fields. Try this:
SELECT REPLACE(REPLACE(CODE + '~' + NAME, CHAR(13), ''), CHAR(10), '') FROM TEST_TABLE
I would suggest using different column names in the future.
For now, it might suffice to simply surround your column names with brackets:
SELECT [CODE] + '~' + [NAME] FROM TEST_TABLE
Works fine for me.
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
I am a bit of an sql noob so please forgive. I can't seem to find a usage example of LTRIM anywhere.
I have a NVARCHAR column in my table in which a number of entries have leading whitespace - I'm presuming if I run this it should do the trick:
SELECT LTRIM( ColumnName)
From TableName;
Will this give the desired result?
No, it will trim leading spaces but not all white space (e.g. carriage returns).
Edit
It seems you are looking for an UPDATE query that will remove leading and trailing whitespace.
If by that you only mean "normal" spaces just use
UPDATE TableName
SET ColumnName = LTRIM(RTRIM(ColumnName ))
For all white space this should do it (from the comments here). Backup your data first!
UPDATE TableName
SET ColumnName =
SUBSTRING(
ColumnName,
PATINDEX('%[^ ' + char(09) + char(10) + char(13) + char(20) + ']%',
ColumnName),
LEN(ColumnName) - PATINDEX('%[^ ' + char(09) + char(10) + char(13) + char(20) + ']%'
, ColumnName) -
PATINDEX('%[^ ' + char(09) + char(10) + char(13) + char(20) + ']%',
REVERSE(ColumnName)) + 2)
Your example will work to remove the leading spaces. This will only select it from the database. IF you need to actually change the data in your table, you will need to write an UPDATE statement something like:
UPDATE TableName
SET ColumnName = LTRIM(ColumnName)
If you need to remove spaces from the right side, you can use RTRIM.
Here is a list of the string functions in SQL Server 2005 that I always refer to:
http://msdn.microsoft.com/en-us/library/ms181984(v=SQL.90).aspx
Did you run it to find out? It's just a select, it won't blow up your database. But, yes.
Select LTRIM(myColumn) myColumn
From myTable
Should return the myColumn values with any leading whitespace removed. Note this is only leading whitespace.
EDIT To Update the column, with the above, you'd do:
Update myTable
Set myColumn = LTRIM(myColumn)
From myTable