Convert table to text in result of a query - sql-server

Result of a query is table,is it possible to write a query that convert this result to a text (for example imagine that result is a table with 4 rows with value 1 to 4 and convert it to 1,2,3,4)

Yes, you can do that using FOR XML PATH(''). For example:
create table test(col varchar(10))
insert into test values ('1'),('2'),('3'),('4')
select STUFF( (select ',' + col
from test
FOR XML PATH('')), 1, 1, '')

Try the below query
declare #Var varchar(1000);
set #var = ''
select #Var = #var + CONVERT(varchar, Column1) + ','
from Table1
select #var

Try this
DECLARE #result varchar(1000)
SET #result = ''
SELECT #result = #result + StudentId + ',' FROM Student WHERE condition = xyz
select substring(#result, 1, len(#result) -1 --trim extra "," at end
Op like
1,2,3,4,..........
Happy Coding

Related

How can I convert values from one column into a quoted, comma-separated list?

Hi I am using SQLServer2008.
In my table there is one field 'Code'.
When i write query
select Code from Table1
then it gives below output
Code
----
9
8
7
6
5
10
31
and my required output is :
["9","8","7","6","5","10","31"]
I have approx 14000 code in Table.
How can i get this result? Thanks.
Try this one -
DECLARE #temp TABLE(Code INT)
INSERT INTO #temp (Code)
VALUES (9),(8),(7),(6),(5),(10),(31)
SELECT STUFF((
SELECT ', "' + CAST(Code AS VARCHAR(10)) + '"'
FROM #temp
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '[') + ']'
Output:
["9", "8", "7", "6", "5", "10", "31"]
Here is your query:
DECLARE #var varchar(8000)
SET #var = '['
SELECT #var = #var + '"' + convert(varchar(100),Code) + '",' FROM Table1
SET #var = SUBSTRING(#var,0,LEN(#var)) + ']'
SELECT #var
SUBSTRING(#var,0,LEN(#var)) removes unnecessary comma at the end of the string
try this
DECLARE #Str VARCHAR(MAX)
SELECT #Str = COALESCE(#Str + ',', '') + '"'+CAST(Code AS VARCHAR(50))+'"'
FROM Table1
SELECT '['+#Str+']'
Try This
declare #formattdstring varchar(100)
set #formattdstring=''
select #formattdstring=#formattdstring+'"'+ Code +'",' from Table1
select '['+#formattdstring+']' as formattedstring
Cheers!!!

How to return a string in reverse separated by a special character in SQL?

I have a string like this "Planck, Albert, Bohr"
I want the output as "Bohr Albert Planck"
I want this done using SQL server. I saw many string split functions all return the data as a table and in the forward order. These don't server my purpose.
Any pointers will be helpful.
This what you want:
DECLARE #source VARCHAR(MAX)
DECLARE #dest VARCHAR(MAX)
DECLARE #lenght INT
SET #source = 'Planck, Albert, Bohr'
SET #dest = ''
WHILE LEN(#source) > 0
BEGIN
IF CHARINDEX(' ', #source) > 0
BEGIN
SET #dest = SUBSTRING(#source,0,CHARINDEX(' ', #source)) + ' ' + #dest
SET #source = LTRIM(RTRIM(SUBSTRING(#source,CHARINDEX(' ',
#source)+1,LEN(#source))))
END
ELSE
BEGIN
SET #dest = #source + ' ' + #dest
SET #source = ''
END
END
SELECT REPLACE(REPLACE(#dest,Char(44),''),Char(13), '')
Char(44) is the ASCII value for , so at last I am just replacing that character.
This will print Bohr Albert Planck.
If you use a split string function like this you can do something like this.
declare #S varchar(20) = 'Planck, Albert, Bohr'
select
(
select ltrim(s)+' '
from dbo.Split(',', #S)
order by pn desc
for xml path(''), type
).value('.', 'varchar(max)')
SQL Fiddle
Declare #inStr varchar(1000)='Planck, Albert, Bohr'
;WITH CTE AS(
select ltrim(rtrim(reverse(left(reverse(#instr),CHARINDEX(',',reverse(#instr),1)-1)))) as strg,RIGHT(reverse(#instr),LEN(reverse(#instr))-CHARINDEX(',',reverse(#instr),1)) as rem
union all
select CASE WHEN CHARINDEX(',',c.rem,1)>0 then ltrim(rtrim(reverse(left(rem,CHARINDEX(',',rem,1)-1)))) else reverse(rem) end,
CASE WHEN CHARINDEX(',',c.rem,1)>0 then RIGHT(c.rem,LEN(rem)-CHARINDEX(',',rem,1)) else '' end
from CTE c
where len(rem) > 0 --CHARINDEX(',',c.rem,1)>0
)
select stuff((select ' '+strg from CTE for xml path('')),1,1,'')

Return rows containing all words in a string

I want to retrieve all rows in which a certain column contains all words passed in a string parameter regardless of the order in which they appear.
If the parameter is 'hi abc' then I want this row: abc def hijk and not hijk lmnop qr
I managed to do it but I suspect it is not very good so I would like to see alternatives. How to better accomplish what my code below do?
create table t (s varchar(200));
insert into t (s) values
('abc def hijk'),
('hijk lmnop qr'),
('stu'),
('v xyz')
;
create function dbo.matchRows (#string varchar(max))
returns varchar(max)
begin
set #string = replace(#string, '''', '''''');
set #string = replace(#string, ' ', ' ');
set #string = replace(#string, ' ', ' ');
set #string = replace(#string, ' ', '%'' and s like ''%');
set #string = 's like ''%' + #string + '%''';
set #string = 'select * from t where ' + #string;
return #string;
end;
declare #query varchar(max);
set #query = (select dbo.matchRows('hi abc'));
execute (#query);
Something like this should work. It converts your search params into XML and then splits it into a table variable. After that, it searches your #t table for all of the split up parameters that you passed in (where the count of the found words equaling the number of search parameters makes it match all of them).
DECLARE #SearchStringParams varchar(max),
#Split char(1),
#Xml xml,
#NumOfSearchTerms Int
DECLARE #SplitTable table (valToSearchFor varchar(100));
SELECT #SearchStringParams = 'hi,abc',
#Split = ','
SELECT #Xml = CONVERT(xml,'<root><s>' + REPLACE(#SearchStringParams,#Split,'</s><s>') + '</s></root>')
INSERT #SplitTable
SELECT [Value] = T.c.value('.','varchar(20)')
FROM #Xml.nodes('/root/s') T(c)
SELECT #NumOfSearchTerms = ##ROWCOUNT
DECLARE #t table (searchWords varchar(200));
insert into #t (searchWords) values
('abc def hijk'),
('hijk lmnop qr'),
('stu'),
('v xyz')
;
select t.searchWords
from #t t inner join #SplitTable s
on t.searchWords like ('%' + s.valToSearchFor + '%')
group by t.searchWords
having count(t.searchWords) = #NumOfSearchTerms

Not able to run a statement because of issue with the sql syntax

This solution is for an unbounded Gridview paging and having problem with the syntax of this query:
> #currTable varchar(20),
#startRowIndex int,
#maximumRows int,
#totalRows int OUTPUT
AS
DECLARE #first_id int, #startRow int
IF #startRowIndex = 1
SET #startRowIndex = 1
ELSE
SET #startRowIndex = ((#startRowIndex - 1) * #maximumRows)+1
SET ROWCOUNT #startRowIndex
DECLARE #sql varchar(250);
SET #sql = 'SELECT ID, StringID_from_Master, GUID, short_Text, lang_String, date_Changed, prev_LangString, needsTranslation, displayRecord, brief_Descrip FROM ' + #currTable + ' ';
EXECUTE(#sql);
PRINT #first_id
SET ROWCOUNT #maximumRows
SELECT #sql = 'SELECT ' + CAST(#first_id as varchar(20)) + ' = ID FROM ' + QUOTENAME(#currTable) + ' ORDER BY ID ' ;
EXEC (#sql);
SET ROWCOUNT 0
-- Get the total rows
SET #sql = 'SELECT ' + + CAST(#totalRowsas varchar(20)) + ' = COUNT(ID) FROM ' + #currTable + ' ';
EXECUTE(#sql);
RETURN
<
The errors is:
Conversion failed when converting the varchar value ''SELECT ' to data type int.
Tried also
nvarchar and varchar. = + CAST(#first_id as varchar(10)) +
If you're trying to implement paging, this is wrong in so many ways. First, you're using SET ROWCOUNT to limit to #startRowIndex, but then you're selecting ALL n rows (with no ORDER BY), then getting the first ID, then counting the total rows by selecting from the table? Might I suggest a better approach?
CREATE PROCEDURE dbo.PageSmarter
#Table NVARCHAR(128), -- table names should not be varchar(20)
#FirstRow INT,
#PageSize INT,
#TotalRows INT OUTPUT
AS
BEGIN
SET NOCOUNT ON; -- always, in every stored procedure
DECLARE
#first_id INT,
#startRow INT,
#sql NVARCHAR(MAX);
SET #sql = N'WITH x AS
(
SELECT
ID,
rn = ROW_NUMBER() OVER (ORDER BY ID)
FROM
' + #Table + '
)
SELECT rn, ID
INTO #x FROM x
WHERE rn BETWEEN ' + CONVERT(VARCHAR(12), #FirstRow)
+ 'AND (' + CONVERT(VARCHAR(12), #FirstRow)
+ ' + ' + CONVERT(VARCHAR(12), #PageSize) + ' - 1);
SELECT first_id = MIN(ID) FROM #x;
SELECT
ID, StringID_from_Master, GUID, short_Text, lang_String, date_Changed,
prev_LangString, needsTranslation, displayRecord, brief_Descrip
FROM ' + #Table + ' AS src
WHERE EXISTS
(
SELECT 1 FROM #x
WHERE ID = src.ID
);';
EXEC sp_executeSQL #sql;
SELECT #totalRows = SUM(row_count)
FROM sys.dm_db_partition_stats
WHERE [object_id] = OBJECT_ID(#Table);
END
GO
DECLARE #tr INT;
EXEC dbo.PageSmarter 'dbo.tablename', 10, 2, #tr OUTPUT;
SELECT #tr;
I haven't tested all edge cases with this specific implementation. I will confess, there are much better ways to do this, but they usually aren't complicated with the additional requirement of dynamic table names. This suggests that there is something inherently wrong with your design if you can run the exact same queries against any number of tables and get similar results.
In any case, you can review some of the (quite lengthy) discussion about various approaches to paging over at SQL Server Central:
http://www.sqlservercentral.com/articles/T-SQL/66030/
There are 62 comments following up on the article:
http://www.sqlservercentral.com/Forums/Topic672980-329-1.aspx
I am guessing your #first_id field is an int. If so, then you need to CAST/Convert your #first_id value to a string/varchar.
CAST(#first_id as varchar(10))
or
Convert(varchar(10), #first_id)
MSDN documentation on CAST/Convert for SQL server
EDIT: After looking at your query again, I notice that you are setting your #first_id = ID, This is incorrect syntax, the correct syntax would be below.
SELECT #sql = 'SELECT ID AS ' + CAST(#first_id as varchar(10)) + ' FROM ' +
QUOTENAME(#currTable) + ' ORDER BY ID ' ;
EXEC (#sql);
It appears you're trying to create an alias for your column ID. The string you're building won't result in a valid SQL statement if it contains a number. It would come out to something like this:
SELECT 123 = ID FROM dbo.MyTable ORDER BY ID
Try this:
SELECT ID AS '123' FROM dbo.MyTable ORDER BY ID
To achieve that:
SELECT #sql = 'SELECT ID AS ''' + CAST(#first_id as varchar(10)) +
''' FROM ' + QUOTENAME(#currTable) +
' ORDER BY ID ' ;
I would do it this way
create table #e (a int)
SET #sql = 'insert #e SELECT COUNT(ID) FROM ' + #currTable + ' ';
exec(#sql)
select #totalRows = a from #e
drop table #e

split text in stored procedure

How to split text in stored procedure.
CREATE PROCEDURE
(
#ArrayList nvarchar(1000)
)
BEGIN
--I want to split #ArrayList. That is contains string. ex '1,2,3,4,5,6...'
END
declare #ArrayList nvarchar(1000) = '1,2,3,4,5,6'
declare #XMLList xml
set #XMLList = cast('<I>'+replace(#ArrayList, ',', '</I><I>')+'</I>' as xml)
select
I.value('.', 'int') as Value
from #XMLList.nodes('I') as I(I)
Use should use XML PATH method as below :
SELECT STUFF(
(SELECT TOP 10 ',' + STOCKNO FROM ItemMaster FOR XML PATH('')), 1, 1, ''
) as Data
Result:
Data
150200006,150200010,150200014,150200018,150200021,150200025,150400078,150400082,150200005,150200009

Resources