I've tried different things in SQL Server 2012 to append the columns. CONCAT merges the columns look like this: catdogparrot whereas I want it be in a list like:
cat
dog
parrot
I've also tried the + in SQL, giving me the same result. I saw '||' as well, but for some reason it says wrong syntax at the second pipe. Is there a way to append a column to a new one? Or would I have to create a new column from the multiple columns? These columns are in the same table. Any suggestions are advice are greatly appreciated, thanks!
I'm not sure what you are trying to do, but you could try to use
CONCAT(' - ', `column1`, ' - ', `column2`, ' - ', ... `column999`)
Eventually this could help you: You can set the separator to any sequence, even to CHAR(13)+CHAR(10), which is a windows line break.
DECLARE #dummyTbl TABLE(animal VARCHAR(10));
INSERT INTO #dummyTbl
VALUES('cat'),('dog'),('parrots');
DECLARE #separator VARCHAR(5)= ' / ';
SELECT STUFF(
(
SELECT #separator + animal
FROM #dummyTbl AS dt
FOR XML PATH(''),TYPE
).value('.','varchar(max)'),1,LEN(#separator),'');
Related
I have a table with data that holds a bunch of HTML attributes.
For example: '<HTML><BODY></BODY></HTML>'
I would like to be able to write a SELECT statement that can grab those values, but display them modified.
So instead of displaying
'<HTML><BODY>DATA</BODY></HTML>'
I want to show:
'<HTML>
<BODY>DATA</BODY>
</HTML>'
Essentially, breaking out each one to a new line, based on finding a '>' value, without modifying the data.
I can't seem to find a way to do this. I tried looking into STRING_SPLIT, but I can't get that to apply from the SELECT part.
Any suggestions where I look?
Edit 2/22 - it appears REPLACE gets me further, but when reviewing this more, it may not be possible.
How would SQL know to break out to a new line when the ending HTML tag appears?
It's almost like I need to use a RegEx in here...
REPLACE(TD.DefDetails, '</', CHAR(13) + CHAR(10) + '</') As DefDetails
STRING_SPLIT can split a single column into multiple rows. STRING_SPLIT does require SQL Server Version 2016+. The following snippet does show an example for this scenario.
USE tempdb;
GO
DECLARE #HTMLString AS VARCHAR(100) = '<HTML><BODY></BODY></HTML>';
SELECT *
FROM STRING_SPLIT(#HTMLString,'>');
Actually appears this is done using REPLACE.
REPLACE(Table.DefDetails, '>', '>'+ CHAR(13) + CHAR(10)) As DefDetails
Demo on db<>fiddle
You can achieve it in this way
SELECT REPLACE('<HTML><BODY></BODY></HTML>', '>', '>'+ CHAR(13))
Or if you want to get the value into rows, you can do this way.
Select value + '>'
from STRING_SPLIT('<HTML><BODY></BODY></HTML>', '>')
where value <> ''
Output
I'm currently using SQL Server 2016 with SQL_Latin1_General_CP1_CI_AI collation. As expected, queries with the letter e will match values with the letters e, è, é, ê, ë, etc because of the accent insensitive option of the collation. However, queries with a ' (U+0027) do not match values containing a ’ (U+2019). I would like to know if such a collation exists where this case would match, since it's easier to type ' than it is to know that ’ is keystroke Alt-0146.
I'm confident in saying no. The main thing, here, is that the two characters are different (although similar). With accents, e and ê are still both an e (just one has an accent). This enables you (for example) to do searches for things like SELECT * FROM Games WHERE [Name] LIKE 'Pokémon%'; and still have rows containing Pokemon return (because people haven't used the accent :P).
The best thing I could suggest would be to use REPLACE (at least in your WHERE clause) so that both rows are returned. That is, however, likely going to get expensive.
If you know what columns are going to be a problem, you could, therefore, add a PERSISTED Computed Column to that table. Then you could use that column in your WHERE clause, but display the one the original one. Something like:
USE Sandbox;
--Create Sample table and data
CREATE TABLE Sample (String varchar(500));
INSERT INTO Sample
VALUES ('This is a string that does not contain either apostrophe'),
('Where as this string, isn''t without at least one'),
('’I have one of them as well’'),
('’Well, I''m going to use both’');
GO
--First attempt (without the column)
SELECT String
FROM Sample
WHERE String LIKE '%''%'; --Only returns 2 of the rows
GO
--Create a PERSISTED Column
ALTER TABLE Sample ADD StringRplc AS REPLACE(String,'’','''') PERSISTED;
GO
--Second attempt
SELECT String
FROM Sample
WHERE StringRplc LIKE '%''%'; --Returns 3 rows
GO
--Clean up
DROP TABLE Sample;
GO
The other answer is correct. There is no such collation. You can easily verify this with the below.
DECLARE #dynSql NVARCHAR(MAX) =
'SELECT * FROM (' +
(
SELECT SUBSTRING(
(
SELECT ' UNION ALL SELECT ''' + name + ''' AS name, IIF( NCHAR(0x0027) = NCHAR(0x2019) COLLATE ' + name + ', 1,0) AS Equal'
FROM sys.fn_helpcollations()
FOR XML PATH('')
), 12, 0+ 0x7fffffff)
)
+ ') t
ORDER BY Equal, name';
PRINT #dynSql;
EXEC (#dynSql);
I am working in SQL Server Managment Studio 2014.
In the project I am working on I have three tables, each containing 2 columns, one datetime with the exact date (but on time is contained) and the other one - smallint containing time (8:55 is 855 value, while for example 14:45 is 1445).
What I want to do is to get minimum value which is merged from both of those columns from all of those three tables.
What I have figure out by myself until now is:
Use lpad("U_StartTime", 0, '4') to fill values like 855 into 0855 (for exact comparison). However lpad is not recognized at my studio.
lpad is not recognized built in function
Then I can merge both columns like this:
SELECT concat("U_StartDate", ' ', "U_StartTime") FROM "TABLE1".
This is ok until I try make it with lpad.
Then I may take all values to consider like this:
SELECT concat("U_StartDate", ' ', "U_StartTime") FROM "TABLE1"
UNION
SELECT concat("U_StartDate", ' ', "U_StartTime") FROM "TABLE2"
...
And I can take MIN(column) but I do not know how to get MIN from the whole UNION SELECT (of those three tables).
Thank you in advance for any advices on my current sql problems.
edit - image for NikHil:
EDIT:
I have changed the way a bit. Now I am modifying datetime object rather than working on string comparison. As an example for someone I paste part of the code:
select DATEADD(minute, "U_StartTime"%100, DATEADD(hour, "U_StartTime"/100, "U_StartDate")) from "TABLE1"
rather than
select MIN(concat("U_StartDate", ' ', RIGHT('0000' + "U_StartTime", '4'))) from "TABLE1"
You can use RIGHT instead of lpad
SELECT RIGHT('0000' + '855', 4) -- 0855
SELECT RIGHT('0000' + '1445', 4) -- 1445
Query looks like
SELECT MIN(RIGHT('0000' + YourColumn, 4) * 1)
FROM
Tbl
may be you can try this
select data from
(
select concat("U_StartDate", ' ', "U_StartTime")as 'data' from "TABLE1"
UNION
select concat("U_StartDate", ' ', "U_StartTime")as 'data' from "TABLE2"
...
)
where data is not null
order by data asc
LIMIT 1;
I am using a STUFF Command to pull in data from a column and concatenate them together into one cell.
STUFF((Select CAST(v.ID as VARCHAR)+ ', '
From Source
Where CriteriaIsMet
For XML Path('')),1,0,'') as MonitorID
What I am trying to accomplish is formatting the results at the end. The results from the code above come out like this:
12345, 23456, 34567, 456789,
I am looking for the code to have a line break. I want them all to still be in the same cell and not broken up but when placed in Excel I am hoping to have this be the results:
12345,
23456,
34567,
45678,
I have tried using:
STUFF((Select REPLACE(CAST v.ID as VARCHAR) + ', ' , ', ', +CHAR(13))
However the end results don't give me what I am looking for I end up with this:
123456
234567
I believe I need to do something at the end of the statement to make this happen, however, I am not sure how to accomplish this because I am using:
For XML Path('')),1,0,'')
I am hoping that someone may have a simple solution. I would greatly appreciate any assistance. Please note I am trying to keep the data in the same cell. The end result of this data pull goes into a Pivot table in Excel and i'd like for the numbers to display vertically rather than horizontally. When displayed Horizontally the numbers cut off after passing the length of the cell.
Try this...
SELECT STUFF((Select CAST(v.ID as VARCHAR(30)) + + ', '+ CHAR(10)
From Source
Where CriteriaIsMet
For XML Path(''),TYPE)
.value('.','NVARCHAR(MAX)'),1,0,'') as MonitorID
Instead of adding CHAR(13) and/or CHAR(10), CHAR(9) horizontal TAB worked for me. The complete STUFF argument and other possible large text fields should also be CASTED as varchar(255).
Should be something like: SELECT CAST(STUFF((...) + CHAR(9) as varchar(255)) as MonitorID
I have a requriment where user will provide many Ids(in Hundres/thousands) in a Text area in vb.net app, I need to use these IDs in T-Sql(Sql Server) to get the data. I dont want to save these Ids in any database table. Just want to pass using a paramater (type of varchar(max)) and use in the procedure.
actually, only read access is permitted for the vb application users.It is Sql-2005 database.Id field is atleaset 12 to 15 characters length.The user will copy/paste data from other source may be CSV or Excel file.
any idea how can i achive this.
any help is appreciated.
Thanks
If you do not want to use Table Valued Parameters, as suggested elsewhere, and you don't want to store the ID's in a temporary table, you can do the following.
Assuming your ID's are integer values, that are separated by commas, in the parameter string, you can use the LIKE operator in your SQL-statement's WHERE filter:
Say you have a parameter, #IDs of type varchar(max). You want to get only those records from MyTable where the ID-column contains a value that has been typed into the #IDs-parameter. Then your query should look something like this:
SELECT * FROM MyTable
WHERE ',' + #IDs + ',' LIKE '%,' + CAST(ID AS varchar) + ',%'
Notice how I prepend and append an extra comma to the #IDs parameter. This is to ensure that the LIKE operator will still work as expected for the first and last ID in the string. Make sure to take the nescessary precautions against SQL injection, for example by validating that users are only allowed to input integer digits and commas.
Try using CHARINDEX:
DECLARE #selectedIDs varchar(max) = '1,2,3'
Set #selectedIDs = ',' + #selectedIds + ',' --string should always start and end with ','
SELECT * FROM YourTable
WHERE CHARINDEX(',' + CAST(IDColumn as VARCHAR(10)) + ',', #selectedIds) > 0