I want to "concatenate" all the "Text"-rows into one single row and get one row as a result. Is this even possible? I use MSSQL Server 2005.
Use FOR XML PATH:
SELECT [Text]+' ' AS 'text()' FROM _table FOR XML PATH('')
Another option - use string concatenation:
DECLARE #s nvarchar(max)
SELECT #s = ISNULL(#s, '') + t + ' ' FROM _table OPTION (MAXDOP 1)
SELECT #s
Please note that the latter one isn't guaranteed to work, afaik, officially the behaviour of "#s = #s + ..." for multi-row resultset is undefined.
MAXDOP 1 hint is used here to prevent the optimizer from creating a parralel execution plan, as this will yield an incorrect result for sure.
I believe you're looking for something like this:
DECLARE #string nvarchar(max)
SET #string = N''
SELECT #string = #string + [Text] + N' ' FROM [YourTable]
SELECT #string
This will concatenate all of the values for the [Text] column into a single variable. You can then select the variable to retrieve all of the values in a single row.
Something like:
DECLARE #result varchar(max)
SELECT #result = COALESCE(#result + ' ','') +[Text] FROM [Table]
SELECT #result
Related
My variable looks like this:
DECLARE #number AS NVARCHAR(1000)
SET #number = '1,2,3,4,5,6'
What I have in my WHERE statement is this:
WHERE V.client IN (#number)
My V.Client column is an integer. What I am trying to do is remove the '' from the #number and make it look like 1,2,3,4,5,6. I have tried to do this,
',' + #number + ',' LIKE '%,' + CAST(V.client AS VARCHAR) + ',%'
but it only returns results for 1 and not the other numbers.
Does anyone have any ideas as to what I can do?
Another option
DECLARE #number AS nvarchar(1000)
SET #number = '1,2,3,4,5,6'
...
WHERE V.client IN (
Select RetVal = B.i.value('(./text())[1]', 'int')
From (Select x = Cast('<x>' + replace(#Number,',','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
)
If 2016+, use string_split()
Dynamic sql is the most common option, here's a snippet how to use it
DECLARE #number AS nvarchar(1000)
SET #number = N'1,2,3,4,5,6'
declare #cmd nvarchar(1000) = N'select case when 1 in ' + Quotename(#number, '()') + ' then 1 else 0 end'
exec sp_executesql #cmd
which will prepare following query
select case when 1 in (1,2,3,4,5,6) then 1 else 0 end
Other options you can consider:
Split the string and use standard sql queries.
In new sql server there is function string_split which make exacly what you want https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-2017.
In older versions you can create custom fuction doing exactly the same thing How do I split a string so I can access item x?
I have 'param1, param2, parma3' coming from SSRS to a stored procedure as a varchar parameter: I need to use it in a query's IN clause but then need to change its format like this first:
select *
from table1
where col1 in('param1', 'param2', 'param3')
What is the best way to reformat the parameter without creating functions and parameter tables?
Try this one, Just need to add commas at the beginning and at the end of #params string.
Declare #params varchar(100) Set #params = ',param1,param2,param3,'
Select * from t
where CHARINDEX(','+cast(col1 as varchar(8000))+',', #params) > 0
SQL FIDDLE
you can use split function and use it as in following way
here my split fnSplitString return splitdata
select * from tb1 where id in(select splitdata from dbo.fnSplitString((select col1 from tb12 where id=3),','))
create FUNCTION [dbo].[fnSplitString]
(
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE #start INT, #end INT
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output(splitdata)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
RETURN
END
If you are using SQL 2016 and above string_split you can use.
-- #param is where you keep your comma separated values example:
declare #param = 'param1,param2,param3'
select * from table1 where col1 in (select TRIM(value) from string_split(#param,',')
More information about string_split check offical documemt
Furthermore, TRIM() is used to trim values from white spaces.
We can use STRING_SPLIT() in SQL SERVER
DECLARE #params varchar(max)= 'param1,param2,param3'
SELECT *
FROM table1
WHERE col1 IN (SELECT value FROM STRING_SPLIT( #params , ','))
"Best way" is arguable, but one classic approach that remains without "creating functions and table parameters" is to simply employ dynamic SQL in the stored procedure:
-- FORNOW: local to act as the SP param and arg
declare #values varchar(100) = 'param1, param2, param3'
-- Add opening and closing single quotes, then quotes around each
-- comma-separated list item.
select #values = '''' + REPLACE(#values, ', ', ''', ''') + ''''
-- FORNOW: for clarity/debugging
print #values
--'param1', 'param2', 'param3'
-- Run the desired query as dynamic SQL.
DECLARE #sql as nvarchar(250);
SET #sql = 'select * from table1 where col1 in (' + #values + ')';
EXEC sp_executesql #sql;
This assumes a couple things, though:
That commas in the list of values are followed by a space. Variations on this solution can address deviations in this respect of course, but it is important to be aware of this assumption.
That the comma-separated values do not themselves have commas in them – unlikely but worth mentioning since whether values will satisfy this constraint sometimes goes unconsidered.
Load the Params into a string and execute as an sql :
declare #param varchar(1000) = 'param1, param2, parma3'
declare #sql varchar(4000)
select #sql =
'select *
from table1
where col1 in(''' + replace(#param,',',''',''') + ''')'
-- print #sql -- to see what you're going to execute
exec sp_executesql #sql
DECLARE #params varchar(max) = '1,2,3,4'
SELECT * FROM table2 WHERE colId IN (SELECT value FROM SPLIT(#params,','))
Base on id we can find.
Suppose I have two rows in my SQL Server table as below
Id Name Address
---------------------
1 Kamal Kathmandu
2 Rahul Pokhara
I want to store these two rows a single string like this,
1,Kamal,Kathmandu#2,Rahul,Pokhara
DECLARE #xml XML = (SELECT *,'#' as Sep FROM YourTable FOR XML PATH(''))
SELECT Replace(Replace(stuff((SELECT ',' + node.value('.', 'varchar(max)')
FROM #xml.nodes('/*') AS T(node)
FOR XML PATH(''), type).value('.','varchar(max)')
, 1, 1, ''),',#,','#'),',#','');
try to use this query.
declare #str varchar(max)
SET #str=STUFF((SELECT
'#'+cast(Id as varchar)+','+Name+','+Address
FROM tablename
ORDER BY '#'+Id
FOR XML PATH('')),1, 1, '')
print #str
DECLARE #ResultString varchar(max)
SET #ResultString = ''
SELECT #ResultString = #ResultString + cast(Id as varchar) + ','
+ Name + ',' + Address + '#'
FROM yourTable
SELECT #ResultString
#ResultString will contain single comma seprated string
1,Kamal,Kathmandu#2,Rahul,Pokhara
Ok, this is a bad idea, you are doing something wrong, but ...
DECLARE #badIdea nvarchar(max);
SET #badIdea = '';
SELECT #badIdea = #badIdea +
STR(Id) + N',' +
Name + N',' +
Address + N'#'
FROM SomeTable;
IF ##ROWCOUNT > 0
SET #badIdea = SUBSTRING(#badIdea, 0, LEN(#badIdea) - 1);
SELECT #badIdea;
Depending on what you want, you can do it in two ways :
Use concatenation, like in the example here : http://blog.sqlauthority.com/2010/11/25/sql-server-concat-function-in-sql-server-sql-concatenation/ . This method simple involved a query like
SELECT str(id)+','+name+','+address FROM tblName
If your aim is to actually export it to a file - you can export using SSMS(which I guess you're using, since you have an MSSQL server). Right click the query results (when using a normal SELECT * FROM tblName), and click "Save Results As...". Then you can save the file into a CSV, which will output a file with the exact format you specified.
I have string from which I have to extract substring and query on their values.
declare #str varchar(max)
#str='Hello,world,continent,nation,city'
select * from mytable
where col_word in(SELECT REPLACE(#str,',',''','''))
The sub query
SELECT REPLACE(#str,',',''',''')
results in
Hello,'world','continent','nation','city
I want the above result be enclosed by single quotes so that it can work for IN
But this returns only for first col_word value Hello which is first substring in #str.
What should I do ?
Try this:
You cannot make part of your query as string. We have to make the whole query as a string, then execute it with EXEC() command.. or sp_executesql stored procedure. The latter is recommended.
declare #str varchar(max);
select #str='Hello,world,continent,nation,city';
SELECT #str=''''+REPLACE(#str,',',''',''')+''''
exec('select * from mytable where col_word in('+#str +')')
Try this:
declare #str varchar(max)
declare #pattern varchar(max)
SET #str='Hello,world,continent,nation,city'
SELECT REPLACE(#str,',',''',''')
SET #pattern = REPLACE('Hello,world,continent,nation,city', ',', ''',''')
EXEC('select * from mytable where col_word in(''' + #pattern + ''')')
I'm running a query using "EXEC sp_helptext Object", but it returns multiple lines with a column name Text. I'm trying to concatenate that value into a single string but I'm having trouble trying to figure out the best way to do it using T-SQL.
You can try something like this
DECLARE #Table TABLE(
Val VARCHAR(MAX)
)
INSERT INTO #Table EXEC sp_helptext 'sp_configure'
DECLARE #Val VARCHAR(MAX)
SELECT #Val = COALESCE(#Val + ' ' + Val, Val)
FROM #Table
SELECT #Val
This will bring back everything in one line, so you might want to use line breaks instead.
Assuming SQL Server 2005 and above (which is implied by varchar(max) in astander's answer), why not simply use one of these
SELECT OBJECT_DEFINITION('MyObject')
SELECT definition FROM sys.sql_modules WHERE object_id = OBJECT_ID('MyObject')
This is not very glamorous, but it works ...
DECLARE #Table TABLE(
Val VARCHAR(MAX)
)
INSERT INTO #Table EXEC sp_helptext 'sp_configure'
DECLARE #Val VARCHAR(MAX)
SET #Val = ''
SELECT #Val = #Val + REPLACE(REPLACE(REPLACE(Val, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')
FROM #Table
-- Replaces line breaks and tab keystrokes.
SELECT #Val