Sort columns based on the order inside SQL in function - sql

i have a query like the one below and i want records to be returned in the same order as the id's specified inside the 'in' function.
SELECT * FROM table 1 where id in(12,6,4,3,13)
Can i do this using sql alone or do i need to write my own sorting function.

create a table with your ID's, then join to table, ordering by another identity column.
Presumably if you have 10k id's they will not be manually entered, so prehaps able to build sort/join table in a different way. SHould also be more efficient than using large in
create table #tempID(idSort int identity(1,1), id int)
insert into #tempID(id)
select 12 union all
select 6 union all
select 4 union all
select 3 union all
select 13
select * from table t1
inner join #tempID t2
on t1.id = t2.id
order by t2.idSort
To create sort table dynamically, you need this function (or similar):
create FUNCTION [dbo].[comma_sep_var_intSort] (#list nvarchar(MAX))
RETURNS #tbl TABLE (idSort int identity(1,1), id int NOT NULL
) AS
BEGIN
DECLARE #pos int,
#nextpos int,
#valuelen int
SELECT #pos = 0, #nextpos = 1
WHILE #nextpos > 0
BEGIN
SELECT #nextpos = charindex(',', #list, #pos + 1)
SELECT #valuelen = CASE WHEN #nextpos > 0
THEN #nextpos
ELSE len(#list) + 1
END - #pos - 1
INSERT #tbl (id)
VALUES (cast(substring(#list, #pos + 1, #valuelen) as int))
SELECT #pos = #nextpos
END
RETURN
END
Then join like this:
declare #idList varchar(max)
set #idLIst = '12,6,4,3,13'
select * from table t1
inner join [dbo].[comma_sep_var_int](#idList) t2
on t1.id = t2.id
order by t2.idSort

you can use CASE to custom sort the records,
ORDER BY CASE WHEN ID = 12 THEN 1
WHEN ID = 6 THEN 2
WHEN ID = 4 THEN 3
WHEN ID = 3 THEN 4
WHEN ID = 13 THEN 5
ELSE 6
END, ID
SQLFiddle Demo

Related

Parse text field and join tables

I have 2 tables.
Table Heroes - 2 records
Name NVARCHAR(50)
PowerIds NVARCHAR(50)
Name PowerIds
'Hulk' '1,3'
'Reed Richards' '2'
Table Powers - 3 records
PowerId INT
PowerDescr NVARCHAR(50)
PowerId PowerDescr
1 'Strength'
2 'Intelligence'
3 'Durability'
What would be the smartest way to achieve this in a SELECT:
Name Powers
'Hulk' 'Strength, Durability'
'Reed Richards' 'Intelligence'
I cannot change the table structure, since this is a third party product.
The smartest way would be to normalize your table. Change the Heroes table to
Name PowerId
'Hulk' 1
'Hulk' 3
'Reed Richards' 2
or remove the power from the Heroes table and add another table that holds only the reference to a hero and the powers like this
HeroID PowerID
1 1
1 3
2 2
Never store multiple data in one column!
Try This:
SELECT Name,
STUFF(
(SELECT ',' + CAST(P.PowerDescr as VARCHAR(MAX))
FROM fn_ParseCsvString(H1.PowerIds, ',') H2
INNER JOIN Powers P ON P.PowerId = H2.ParsedString
FOR XML path('')),1,1,''
) AS Strength
FROM Heroes H1
Function:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fn_ParseCsvString]
(
#csvString VARCHAR(MAX),
#delimiter VARCHAR(MAX)
)
RETURNS #parsedStringTable TABLE (ParsedString VARCHAR(MAX))
AS
BEGIN
DECLARE #startIndex INT, #targetedIndex INT
SELECT
#startIndex = 1
WHILE #startIndex <= LEN(#CSVString)
BEGIN
SELECT
#targetedIndex = charindex(#Delimiter, #CSVString, #startIndex)
IF #targetedIndex = 0
BEGIN
SELECT
#targetedIndex = len(#CSVString) + 1
END
INSERT #parsedStringTable
SELECT
SUBSTRING(#CSVString, #startIndex, #targetedIndex - #startIndex)
SELECT #startIndex = #targetedIndex + LEN(#Delimiter)
END
RETURN
END
GO
Here you can find a SQL Fiddle example.

Convert Comma Delimited String to bigint in SQL Server

I have a varchar string of delimited numbers separated by commas that I want to use in my SQL script but I need to compare with a bigint field in the database. Need to know to convert it:
DECLARE #RegionID varchar(200) = null
SET #RegionID = '853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'
SELECT a.ClassAdID, -- 1
a.AdURL, -- 2
a.AdTitle, -- 3
a.ClassAdCatID, -- 4
b.ClassAdCat, -- 5
a.Img1, -- 6
a.AdText, -- 7
a.MemberID, -- 9
a.Viewed, -- 10
c.Domain, -- 11
a.CreateDate -- 12
FROM ClassAd a
INNER JOIN ClassAdCat b ON b.ClassAdCAtID = a.ClassAdCAtID
INNER JOIN Region c ON c.RegionID = a.RegionID
AND a.PostType = 'CPN'
AND DATEDIFF(d, GETDATE(), ExpirationDate) >= 0
AND a.RegionID IN (#RegionID)
AND Viewable = 'Y'
This fails with the following error:
Error converting data type varchar to bigint.
RegionID In the database is a bigint field.. need to convert the varchar to bigint.. any ideas..?
Many thanks in advance,
neojakey
create this function:
CREATE function [dbo].[f_split]
(
#param nvarchar(max),
#delimiter char(1)
)
returns #t table (val nvarchar(max), seq int)
as
begin
set #param += #delimiter
;with a as
(
select cast(1 as bigint) f, charindex(#delimiter, #param) t, 1 seq
union all
select t + 1, charindex(#delimiter, #param, t + 1), seq + 1
from a
where charindex(#delimiter, #param, t + 1) > 0
)
insert #t
select substring(#param, f, t - f), seq from a
option (maxrecursion 0)
return
end
change this part:
AND a.RegionID IN (select val from dbo.f_split(#regionID, ','))
Change this for better overall performance:
AND DATEDIFF(d, 0, GETDATE()) <= ExpirationDate
Your query does not know that those are separate values, you can use dynamic sql for this:
DECLARE #RegionID varchar(200) = null
SET #RegionID = '853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'
declare #sql nvarchar(Max)
set #sql = 'SELECT a.ClassAdID, -- 1
a.AdURL, -- 2
a.AdTitle, -- 3
a.ClassAdCatID, -- 4
b.ClassAdCat, -- 5
a.Img1, -- 6
a.AdText, -- 7
a.MemberID, -- 9
a.Viewed, -- 10
c.Domain, -- 11
a.CreateDate -- 12
FROM ClassAd a
INNER JOIN ClassAdCat b ON b.ClassAdCAtID = a.ClassAdCAtID
INNER JOIN Region c ON c.RegionID = a.RegionID
AND a.PostType = ''CPN''
AND DATEDIFF(d, GETDATE(), ExpirationDate) >= 0
AND a.RegionID IN ('+#RegionID+')
AND Viewable = ''Y'''
exec sp_executesql #sql
I use this apporach sometimes and find it very good.
It transfors your comma-separated string into an AUX table (called #ARRAY) and then query the main table based on the AUX table:
declare #RegionID varchar(50)
SET #RegionID = '853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'
declare #S varchar(20)
if LEN(#RegionID) > 0 SET #RegionID = #RegionID + ','
CREATE TABLE #ARRAY(region_ID VARCHAR(20))
WHILE LEN(#RegionID) > 0 BEGIN
SELECT #S = LTRIM(SUBSTRING(#RegionID, 1, CHARINDEX(',', #RegionID) - 1))
INSERT INTO #ARRAY (region_ID) VALUES (#S)
SELECT #RegionID = SUBSTRING(#RegionID, CHARINDEX(',', #RegionID) + 1, LEN(#RegionID))
END
select * from your_table
where regionID IN (select region_ID from #ARRAY)
It avoids you from ahving to concatenate the query string and then use EXEC to execute it, which I dont think it is a very good approach.
if you need to run the code twice you will need to drop the temp table
I think the answer should be kept simple.
Try using CHARINDEX like this:
DECLARE #RegionID VARCHAR(200) = NULL
SET #RegionID =
'853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'
SELECT 1
WHERE Charindex('834', #RegionID) > 0
SELECT 1
WHERE Charindex('999', #RegionID) > 0
When CHARINDEX finds the value in the large string variable, it will return it's position, otherwise it return 0.
Use this as a search tool.
The easiest way to change this query is to replace the IN function with a string function. Here is what I consider the safest approach using LIKE (which is portable among databases):
AND ','+#RegionID+',' like '%,'+cast(a.RegionID as varchar(255))+',%'
Or CHARINDEX:
AND charindex(','+cast(a.RegionID as varchar(255))+',', ','+#RegionID+',') > 0
However, if you are explicitly putting the list in your code, why not use a temporary table?
declare #RegionIds table (RegionId int);
insert into #RegionIds
select 853 union all
select 834 union all
. . .
select 303
Then you can use the table in the IN clause:
AND a.RegionId in (select RegionId from #RegionIds)
or in a JOIN clause.
I like Diego's answer some, but I think my modification is a little better because you are declaring a table variable and not creating an actual table. I know the "in" statement can be a little slow, so I did an inner join since I needed some info from the Company table anyway.
declare #companyIdList varchar(1000)
set #companyIdList = '1,2,3'
if LEN(#companyIdList) > 0 SET #companyIdList = #companyIdList + ','
declare #CompanyIds TABLE (CompanyId bigint)
declare #S varchar(20)
WHILE LEN(#companyIdList) > 0 BEGIN
SELECT #S = LTRIM(SUBSTRING(#companyIdList, 1, CHARINDEX(',', #companyIdList) - 1))
INSERT INTO #CompanyIds (CompanyId) VALUES (#S)
SELECT #companyIdList = SUBSTRING(#companyIdList, CHARINDEX(',', #companyIdList) + 1, LEN(#companyIdList))
END
select d.Id, d.Name, c.Id, c.Name
from [Division] d
inner join [Company] c on d.CompanyId = c.Id
inner join #CompanyIds cids on c.Id = cids.CompanyId

SQL Server - Compare Varchar values using IN

In my table, I have a varchar column whereby multi-values are stored. An example of my table:
RecNum | Title | Category
-----------------------------------------
wja-2012-000001 | abcdef | 4,6
wja-2012-000002 | qwerty | 1,3,7
wja-2012-000003 | asdffg |
wja-2012-000004 | zxcvbb | 2,7
wja-2012-000005 | ploiuh | 3,4,12
The values in the Category column points to another table.
How can I return the relevant rows if I want to retrieve the rows with value 1,3,5,6,8 in the Category column?
When I tried using IN, I get the 'Conversion failed when converting the varchar value '1,3,5,6,8' to data type int' error.
Breaking the Categories out into a separate table would be a better design if that's a change you can make... otherwise, you could create a function to split the values into a table of integers like this:
CREATE FUNCTION dbo.Split(#String varchar(8000), #Delimiter char(1))
returns #temptable TABLE (id int)
as
begin
declare #idx int
declare #slice varchar(8000)
select #idx = 1
if len(#String)<1 or #String is null return
while #idx!= 0
begin
set #idx = charindex(#Delimiter,#String)
if #idx!=0
set #slice = left(#String,#idx - 1)
else
set #slice = #String
if(len(#slice)>0)
insert into #temptable(id) values(convert(int, #slice))
set #String = right(#String,len(#String) - #idx)
if len(#String) = 0 break
end
return
end
Then call it from your query:
SELECT ...
FROM ...
WHERE #SomeID IN (SELECT id FROM dbo.Split(Category, ','))
Or if you're looking to provide a list of categories as an input parameter (such as '1,3,5,6,8'), and return all records in your table that contain at least one of these values, you could use a query like this:
SELECT ...
FROM ...
WHERE
EXISTS (
select 1
from dbo.Split(Category, ',') s1
join dbo.Split(#SearchValues, ',') s2 ON s1.id = s2.id
)
you can do like this
declare #var varchar(30); set #var='2,3';
exec('select * from category where Category_Id in ('+#var+')')
Try this solution:
CREATE TABLE test4(RecNum varchar(20),Title varchar(10),Category varchar(15))
INSERT INTO test4
VALUES('wja-2012-000001','abcdef','4,6'),
('wja-2012-000002','qwerty','1,3,7'),
('wja-2012-000003','asdffg',null),
('wja-2012-000004','zxcvbb','2,7'),
('wja-2012-000005','ploiuh','3,4,12')
select * from test4
Declare #str varchar(25) = '1,3,5,6,8'
;WITH CTE as (select RecNum,Title,Category from test4)
,CTE1 as (
select RecNum,Title,RIGHT(#str,LEN(#str)-CHARINDEX(',',#str,1)) as rem from CTE where category like '%'+LEFT(#str,1)+'%'
union all
select c.RecNum,c.Title,RIGHT(c1.rem,LEN(c1.rem)-CHARINDEX(',',c1.rem,1)) as rem from CTE1 c1 inner join CTE c
on c.category like '%'+LEFT(c1.rem,1)+'%' and CHARINDEX(',',c1.rem,1)>0
)
select RecNum,Title from CTE1
As mentioned by others, your table design violates basic database design principles and if there is no way around it, you could normalize the table with little code (example below) and then join away with the other table. Here you go:
Data:
CREATE TABLE data(RecNum varchar(20),Title varchar(10),Category varchar(15))
INSERT INTO data
VALUES('wja-2012-000001','abcdef','4,6'),
('wja-2012-000002','qwerty','1,3,7'),
('wja-2012-000003','asdffg',null),
('wja-2012-000004','zxcvbb','2,7'),
('wja-2012-000005','ploiuh','3,4,12')
This function takes a comma separated string and returns a table:
CREATE FUNCTION listToTable (#list nvarchar(MAX))
RETURNS #tbl TABLE (number int NOT NULL) AS
BEGIN
DECLARE #pos int,
#nextpos int,
#valuelen int
SELECT #pos = 0, #nextpos = 1
WHILE #nextpos > 0
BEGIN
SELECT #nextpos = charindex(',', #list, #pos + 1)
SELECT #valuelen = CASE WHEN #nextpos > 0
THEN #nextpos
ELSE len(#list) + 1
END - #pos - 1
INSERT #tbl (number)
VALUES (convert(int, substring(#list, #pos + 1, #valuelen)))
SELECT #pos = #nextpos
END
RETURN
END
Then, you can do something like this to "normalize" the table:
SELECT *
FROM data m
CROSS APPLY listToTable(m.Category) AS t
where Category is not null
And then use the result of the above query to join with the "other" table. For example (i did not test this query):
select * from otherTable a
join listToTable('1,3,5,6,8') b
on a.Category = b.number
join(
SELECT *
FROM data m
CROSS APPLY listToTable(m.Category) AS t
where Category is not null
) c
on a.category = c.number

SQL Query return values in a set sequence

I have been trying for a while now to return data from the database with the ID(int) values in the following order.
3, 6, 1, 9, 2, 5.
Is there anyway this can be done?
EDIT: Ok i made a bit of a stuff up in my post. the ID's above are just an example.
I am trying to do this dynamically, based around how many records from another table are linked to the record i want to pull out, e.g. i host 3 branches and each branch has a group of shops how would i determine which has the most?
I hope this helps.
Yes, something like this:
select ID from tablename
order by
CASE WHEN ID = 3 THEN 1
WHEN ID = 6 THEN 2
WHEN ID = 1 THEN 3
WHEN ID = 9 THEN 4
WHEN ID = 2 THEN 5
WHEN ID = 5 THEN 6
ELSE 7 END, ID ASC
This will put 3,6,1,9,2,5 and afterwords the other numbers in ascending order.
select cols from table where
order by
case ID when 3 then 0
when 6 then 1
when 1 then 2
when 9 then 3
...
end
You get the idea...
Create a table for the sorting.
CREATE TABLE SortPriority (
SourceID int NULL,
Priority int NULL)
Populate it with the ids and what order they should showup in. Join to the table. and use SortPriority.Priority in your sorting.
You can more easily change the sorting around this way. You would just need to modify the data. You can also later write scripts to populate the table to handle predictable needs in the changing of the sorting.
A split function like this one:
CREATE FUNCTION fnSplit(#str varchar(max), #dlm char(1))
RETURNS #result TABLE (id int, value varchar(50))
AS BEGIN
DECLARE
#id int, #value varchar(50),
#lastpos int, #pos int, #len int;
SET #id = 0;
SET #len = LEN(#str);
SET #lastpos = 1;
SET #pos = CHARINDEX(#dlm, #str + #dlm);
IF #pos <> 0
WHILE 1 = 1 BEGIN
SET #value = SUBSTRING(#str, #lastpos, #pos - #lastpos);
IF #value <> '' BEGIN
SET #id = #id + 1;
INSERT INTO #result VALUES (#id, #value);
END;
IF #pos > #len BREAK;
SET #lastpos = #pos + 1;
SET #pos = CHARINDEX(#dlm, #str + #dlm, #lastpos);
END;
RETURN;
END
would return a row set containing not only the values, but also their indexes within the list. You could then use the function in this way:
SELECT
…
FROM atable t
LEFT JOIN dbo.Split('3,6,1,9,2,5', ',') s ON t.Value = s.Value
ORDER BY
CASE WHEN s.id IS NULL THEN 2147483647 ELSE s.id END

Need help to write a SQL query?

I have a SQL table with column which contain string like 'type|type1|type2|type3|type4'.
I need to select the string, id. Split string and insert to another table. First item should be default and I need to get identity of it and insert to another table with the type value.
Please help me to create T-SQL query to accomplish desirable result.
Example
Step 1 To select Items from Table 1.
Step 2 Split to array
Step 3 Insert to Table 2 (first item will be default)
Step 4 Update Table 1 with default Type Value based on TypeID and Default True
Table 1
ID Items Default
--------------------------------------------------
1 type|type1|type2|type3|type4
2 type|type1|type2|type3|type4
Table 2
ID TypeID Type Default(bool)
--------------------------------------------------
1 1 type1 1
2 1 type2 0
Using the split function from Arnold Fribble's answer on this thread
Create FUNCTION dbo.Split (#sep char(1), #s varchar(512))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(#sep, #s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(#sep, #s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(#s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM Pieces
)
GO
You can write the following (I made some guesses about the ID field in table2 and what the defaultTypeID should be in table1 but you should be able to adjust that)
CREATE TABLE #table1 (
id INT,
items VARCHAR(MAX),
defaulttypeid INT
)
CREATE TABLE #table2 (
id INT IDENTITY,
typeid INT,
TYPE VARCHAR(5),
isdefault BIT
)
INSERT INTO #table1
VALUES (1,
'type|type1|type2|type3|type4',
NULL),
(2,
'type|type1|type2|type3|type4',
NULL)
INSERT INTO #table2
(typeid,
TYPE,
isdefault)
SELECT id typeid,
Rtrim(split.s) AS item,
CASE
WHEN ( split.pn = 1 ) THEN 1
ELSE 0
END AS isdefault
FROM #table1
CROSS APPLY test.dbo.Split('|', items) AS split
UPDATE #table1
SET defaulttypeid = t2.ID
FROM #table1 t1
INNER JOIN #table2 t2
ON t1.id = t2.typeid
AND t2.isdefault = 1
DROP TABLE #table1
DROP TABLE #table2
This outputs
ID Items DefaultTypeID
----------- ------------------------------ -------------
1 type|type1|type2|type3|type4 1
2 type|type1|type2|type3|type4 6
ID TypeID Type IsDefault
----------- ----------- ----- ---------
1 1 type 1
2 1 type1 0
3 1 type2 0
4 1 type3 0
5 1 type4 0
6 2 type 1
7 2 type1 0
8 2 type2 0
9 2 type3 0
10 2 type4 0
Though I totally disagree with the use of cursors I can't think of another way. This solution isn't tested but It looks like it should be ok.
DECLARE #pos INT
DECLARE #id INT
DECLARE #string VARCHAR(MAX)
DECLARE #default INT
DECLARE #substring VARCHAR(MAX)
DECLARE tempCursor CURSOR FOR
SELECT id, string
FROM table_name
OPEN tempCursor;
FETCH NEXT FROM tempCursor
INTO #id, #string
WHILE ##FETCH_STATUS = 0
BEGIN
SET #default = 1
SET #pos = CHARINDEX('|', #string)
WHILE (#pos <> 0)
BEGIN
SET #substring = SUBSTRING(#string, 1, #pos - 1)
INSERT INTO table_name2(typeid, type, default) VALUES (#id, #substring, #default)
SET #string = substring(#string, #pos+1, LEN(#string))
SET #pos = charindex('|', #string)
SET #default = 0
END
FETCH NEXT FROM tempCursor
INTO #id, #string
END
CLOSE EWSCursor;
DEALLOCATE EWSCursor;
Hope this helps.