How to modify temp table inside cursor? - sql-server

I have temp table data in sql. I need modify data in that table.
Please find snapshot attached
I need to have a col having month data like for 01-03 jan-mar
this is code I have written. It's not working:
DECLARE #month VARCHAR(50) -- month
DECLARE #year VARCHAR(256) -- year
DECLARE #monthf VARCHAR(256) -- year
DECLARE #months VARCHAR(256) -- year
DECLARE db_cursor CURSOR FOR
SELECT months,[year] FROM #temp where len(months)>4
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #month,#year
WHILE ##FETCH_STATUS = 0
BEGIN
IF SUBSTRING(#month,0,3) = '01'
set #monthf='Jan'
ELSE IF SUBSTRING(#month,0,3) = '02'
set #monthf='Feb'
ELSE IF SUBSTRING(#month,0,3) = '03'
set #monthf='Mar'
ELSE IF SUBSTRING(#month,0,3) = '04'
set #monthf='Apr'
ELSE IF SUBSTRING(#month,0,3) = '05'
set #monthf='May'
ELSE IF SUBSTRING(#month,0,3) = '06'
set #monthf='Jun'
ELSE IF SUBSTRING(#month,0,3) = '07'
set #monthf='Jul'
ELSE IF SUBSTRING(#month,0,3) = '08'
set #monthf='Aug'
ELSE IF SUBSTRING(#month,0,3) = '09'
set #monthf='Sep'
ELSE IF SUBSTRING(#month,0,3) = '10'
set #monthf='Oct'
ELSE IF SUBSTRING(#month,0,3) = '11'
set #monthf='Nov'
ELSE IF SUBSTRING(#month,0,3) = '12'
set #monthf='Dec'
IF SUBSTRING(#month,4,2) = '01'
set #months='Jan'
ELSE IF SUBSTRING(#month,4,2) = '02'
set #months='Feb'
ELSE IF SUBSTRING(#month,4,2) = '03'
set #months='Mar'
ELSE IF SUBSTRING(#month,4,2) = '04'
set #months='Apr'
ELSE IF SUBSTRING(#month,4,2) = '05'
set #months='May'
ELSE IF SUBSTRING(#month,4,2) = '06'
set #months='Jun'
ELSE IF SUBSTRING(#month,4,2) = '07'
set #months='Jul'
ELSE IF SUBSTRING(#month,4,2) = '08'
set #months='Aug'
ELSE IF SUBSTRING(#month,4,2) = '09'
set #months='Sep'
ELSE IF SUBSTRING(#month,4,2) = '10'
set #months='Oct'
ELSE IF SUBSTRING(#month,4,2) = '11'
set #months='Nov'
ELSE IF SUBSTRING(#month,4,2) = '12'
set #months='Dec'
update #temp set [Month]= where months=
Delete from #temp where months=SUBSTRING(#month,0,3) and [Year]=#year
Delete from #temp where months=SUBSTRING(#month,4,2) and [Year]=#year
FETCH NEXT FROM db_cursor INTO #month,#year
END
CLOSE db_cursor
DEALLOCATE db_cursor
I need another column with month names like: for 01-03 it should give jan-mar
Can you please help me out? I need a separate column for month string data.

You don't need a cursor at all.
IF OBJECT_ID('tempdb..#Data') IS NOT NULL
DROP TABLE #Data
CREATE TABLE #Data (
Month VARCHAR(100),
ResultMonthText VARCHAR(100))
INSERT INTO #Data (
Month)
VALUES
('01-03'),
('07'),
('03'),
('03-05'),
('05-09'),
('02')
;WITH ParsedMonths AS
(
SELECT
D.Month,
D.ResultMonthText,
First = CONVERT(INT, SUBSTRING(D.Month, 1, 2)),
Second = CONVERT(INT, NULLIF(SUBSTRING(D.Month, 4, 2), ''))
FROM
#Data AS D
),
MonthNames AS
(
SELECT
D.Month,
D.ResultMonthText,
FirstAsName = SUBSTRING(
DATENAME(
MONTH,
DATEADD(MONTH, D.First, 0) - 1 ),
1,
3),
SecondAsName = SUBSTRING(
DATENAME(
MONTH,
DATEADD(MONTH, D.Second, 0) - 1 ),
1,
3)
FROM
ParsedMonths AS D
)
UPDATE D SET
ResultMonthText = D.FirstAsName + ISNULL('-' + D.SecondAsName, '')
FROM
MonthNames AS D
SELECT
*
FROM
#Data AS D
/*
Result:
Month ResultMonthText
------- ------------
01-03 Jan-Mar
07 Jul
03 Mar
03-05 Mar-May
05-09 May-Sep
02 Feb
*/
EDIT: Do this if you still want to keep your cursor (although I strongly suggest you stop using them whenever you can):
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #month,#year
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #FirstMonthNumber INT = CONVERT(INT, SUBSTRING(#month, 1, 2))
DECLARE #SecondMonthNumber INT = CONVERT(INT, NULLIF(SUBSTRING(#month, 4, 2), ''))
DECLARE #FirstMonthText VARCHAR(10) = SUBSTRING(
DATENAME(
MONTH,
DATEADD(MONTH, #FirstMonthNumber, 0) - 1 ),
1,
3)
DECLARE #SecondMonthText VARCHAR(10) = SUBSTRING(
DATENAME(
MONTH,
DATEADD(MONTH, #SecondMonthNumber, 0) - 1 ),
1,
3)
update #temp set
YourNewMonthColumn = #FirstMonthText + ISNULL('-' + #SecondMonthText, '')
WHERE
months = #month
FETCH NEXT FROM db_cursor INTO #month,#year
END
I don't know why you update the column and then delete the row also.

Maybe
update #temp set [Month] = #monthf where months = #months

Related

Generate free time between 2 dates in blocks of length depending on task

I'm trying to generate free blocks for workers and work fine if the working hours are like 08:00 to 16:00. But when I change the working hours to 07:30 to 15:30 it doesn't act as I want it to. If my task length is 1 hour/60 minutes, the first available time will be 8.00, which was supposed to be 7:30.
Any suggestions about how I can resolve this issue?
Output:
expected to be starting at 7:30, 8:30 etc
stored procedure
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[ProcedureGenerateFreetimeForOneStakeholder]
(
#EmployeeId uniqueidentifier,
#NumberOfDaysBeforeBooking int,
#NumberOfDays int,
#Rebuild int
)
AS
DECLARE #workHours TABLE (
[CompanyKeyValuePairSettingsId] uniqueidentifier,
[Value] nvarchar(249)
)
DECLARE #CompanyId uniqueidentifier = (select top 1 CompanyId from tblStakeholder where StakeholderId = #EmployeeId)
SET #NumberOfDaysBeforeBooking =(select [value] FROM tblCompanyToCompanyKeyValuePairSettings WHERE CompanyId = #CompanyId AND CompanyKeyValuePairSettingsId = '06B546A9-C47E-4A8B-AE13-E3F9F0C87DEC')
SET #NumberOfDays =(select [value] FROM tblCompanyToCompanyKeyValuePairSettings WHERE CompanyId = #CompanyId AND CompanyKeyValuePairSettingsId = '87C6406F-BC47-4F42-B58B-450C9F4EBC9E')
-- Insert user work time to #workHours
INSERT INTO #workHours ([CompanyKeyValuePairSettingsId], [Value]) (SELECT s.[CompanyKeyValuePairSettingsId], s.[Value] FROM [dbo].[tblCompanyToCompanyKeyValuePairSettings] as s
INNER JOIN [dbo].[tblCompanyKeyValuePairSettings] as p on s.[CompanyKeyValuePairSettingsId] = p.CompanyKeyValuePairSettingsId
WHERE p.[Section] = 'workingHours' and [CompanyId] = #CompanyId and p.[CompanyKeyValuePairSettingsId] not in (
SELECT [IsOverwriteTo]
FROM [dbo].[tblCompanyUserKeyValuePairSettings]
INNER JOIN [dbo].[tblCompanyUserToStakeholderIdKeyValuePairSettings] on [tblCompanyUserKeyValuePairSettings].[CompanyUserKeyValuePairSettingsId] = [tblCompanyUserToStakeholderIdKeyValuePairSettings].[CompanyUserKeyValuePairSettingsId]
WHERE Section = 'WorkingHours' AND IsOverwriteTo is not null and StakeholderId = #EmployeeId))
INSERT INTO #workHours ([CompanyKeyValuePairSettingsId], [Value] ) (SELECT [IsOverwriteTo], [tblCompanyUserToStakeholderIdKeyValuePairSettings].[Value]
FROM [dbo].[tblCompanyUserKeyValuePairSettings]
INNER JOIN [dbo].[tblCompanyUserToStakeholderIdKeyValuePairSettings] on [tblCompanyUserKeyValuePairSettings].[CompanyUserKeyValuePairSettingsId] = [tblCompanyUserToStakeholderIdKeyValuePairSettings].[CompanyUserKeyValuePairSettingsId]
WHERE Section = 'WorkingHours' AND IsOverwriteTo is not null and StakeholderId = #EmployeeId)
declare #TimeSlots table (
StartTime [nchar](5) NOT NULL,
EndTime [nchar](5) NOT NULL
)
DECLARE #Today DateTime = CONVERT (date, DATEADD(day, 0, GETDATE()))
DECLARE #FirstDay DateTime = CONVERT (date, DATEADD(day, #NumberOfDaysBeforeBooking, GETDATE()))
DECLARE #Last DateTime = CONVERT (date, DATEADD(day, #NumberOfDays,GETDATE()))
DECLARE #current DateTime = CONVERT (date, DATEADD(day, 0, GETDATE()))
DECLARE #MinuteBeginDay int
DECLARE #MinuteEndDay int
DECLARE #MinuteAssignmentBegin int
DECLARE #MinuteAssignmentEnd int = 1440;
if(#Rebuild = 1)
Begin
DELETE FROM [dbo].[tblEmployeeFreetime] WHERE [StakeholderId] = #EmployeeId
End
if(#Rebuild = 0)
Begin
DELETE FROM [dbo].[tblEmployeeFreetime] WHERE [StakeholderId] = #EmployeeId and [StartTime] <= #FirstDay
End
-- Insert blocked time
WHILE (#current <= #FirstDay)
BEGIN
INSERT INTO #TimeSlots (StartTime,EndTime) values ('23:59','23:59')
set #MinuteBeginDay = (select CONVERT(INT, (SELECT SUBSTRING((select top (1) StartTime from #TimeSlots), 1, 2))) * 60 + CONVERT(INT, (SELECT SUBSTRING((select top (1) StartTime from #TimeSlots), 4, 5))))
set #MinuteEndDay = (select CONVERT(INT, (SELECT SUBSTRING((select top (1) EndTime from #TimeSlots), 1, 2))) * 60 + CONVERT(INT, (SELECT SUBSTRING((select top (1) EndTime from #TimeSlots), 4, 5))))
set #MinuteAssignmentBegin = 30
While (#MinuteAssignmentBegin < #MinuteAssignmentEnd - #MinuteAssignmentBegin)
Begin
INSERT INTO [dbo].[tblEmployeeFreetime] ([StakeholderId], StartTime,EndTime,[AssignmentLength])
(select #EmployeeId, #current , DATEADD(minute, #MinuteEndDay, #current),#MinuteAssignmentBegin)
SET #MinuteAssignmentBegin = #MinuteAssignmentBegin + 30
End
DELETE FROM #TimeSlots
Set #current = CONVERT (date, DATEADD(day, 1, #current))
End
-- Insert free time on workdays and weekends
SET #current = CONVERT (date, DATEADD(day, 1, (SELECT TOP (1) [EndTime] FROM [dbo].[tblEmployeeFreetime] where [StakeholderId] = #EmployeeId order by [EndTime] desc)))
Declare #SetTime datetime
while (#current <= #Last)
Begin
declare #str VARCHAR(MAX)
set #str = FORMAT(#current, 'dddd')
-----
declare #StartSlot nvarchar(5) = (SELECT w.Value FROM #workHours as w
INNER JOIN tblCompanyKeyValuePairSettings as s on w.[CompanyKeyValuePairSettingsId] = s.[CompanyKeyValuePairSettingsId] where s.Name Like #str + 'StartTime%')
declare #EndSlot nvarchar(5) = (SELECT w.Value FROM #workHours as w
INNER JOIN tblCompanyKeyValuePairSettings as s on w.[CompanyKeyValuePairSettingsId] = s.[CompanyKeyValuePairSettingsId] where s.Name Like #str + 'EndTime%')
INSERT INTO #TimeSlots (StartTime,EndTime) VALUES (#StartSlot,#EndSlot)
----
set #MinuteBeginDay = (select CONVERT(INT, (SELECT SUBSTRING((select top (1) StartTime from #TimeSlots), 1, 2))) * 60 + CONVERT(INT, (SELECT SUBSTRING((select top (1) StartTime from #TimeSlots), 4, 5))))
set #MinuteEndDay = (select CONVERT(INT, (SELECT SUBSTRING((select top (1) EndTime from #TimeSlots), 1, 2))) * 60 + CONVERT(INT, (SELECT SUBSTRING((select top (1) EndTime from #TimeSlots), 4, 5))))
set #MinuteAssignmentBegin = 30
While (#MinuteAssignmentBegin < #MinuteAssignmentEnd - #MinuteAssignmentBegin)
Begin
INSERT INTO [dbo].[tblEmployeeFreetime] ([StakeholderId], StartTime,EndTime,[AssignmentLength]) (select #EmployeeId, #current , DATEADD(minute, #MinuteBeginDay, #current),#MinuteAssignmentBegin)
if #StartSlot != #EndSlot
begin
set #SetTime = DATEADD(minute, #MinuteEndDay - #MinuteAssignmentBegin, #current)
INSERT INTO [dbo].[tblEmployeeFreetime] ([StakeholderId], StartTime,EndTime,[AssignmentLength]) (select #EmployeeId, #SetTime, DATEADD(minute, 1439, #current),#MinuteAssignmentBegin)
end
set #MinuteAssignmentBegin = #MinuteAssignmentBegin + 30
End
delete from #TimeSlots
Set #current = CONVERT (date, DATEADD(day, 1, #current))
End

While loop to populate a table

I am trying to use a while loop to populate a table in SQL Server. The data is to be in 5 minute increments from 8:00 am to 7:00 pm for Monday through Friday.
Below is the code that I have in place when I try to pass the variable #Beg to #Temp I get an error:
Msg 102, Level 15, State 1, Line 85
Incorrect syntax near '#Temp'.
Msg 102, Level 15, State 1, Line 90
Incorrect syntax near '#Beg'.
My code:
Create Table TIMESLOT
(
TIMESLOTID int not null identity(1,1),
Beg_Time datetime not null,
End_Time datetime not null,
TimeDayOFWeek varChar(25) not null
);
DECLARE #Beg as Time;
DECLARE #Temp as Time;
DECLARE #End as Time;
DECLARE #Day as dayofweek;
set #Beg = '08:00 AM';
Set #End = '07:00 PM';
set #Day = 'Monday';
While (#Day != 'Saturday' )
Begin
While (#Beg <= #End)
Begin
#Temp = #Beg;
DateAdd(minute,5,#Temp)
Insert into TIMESLOT (Beg_Time, End_Time, TimeDay0fWeek)
Values (#Beg, #Temp, #Day)
if (#Beg <= #End)
#Beg = #Temp
Else
#Beg = '08:00 AM'
#Day = Datadd(day, 1, #Day)
End
End
End
try the below. Your syntax was not quite correct
Create Table TIMESLOT
(
TIMESLOTID int not null identity(1,1),
Beg_Time datetime not null,
End_Time datetime not null,
TimeDayOFWeek varChar(25) not null
);
DECLARE #Beg as Time;
DECLARE #Temp as Time;
DECLARE #End as Time;
DECLARE #Day as dayofweek;
set #Beg = '08:00 AM';
Set #End = '07:00 PM';
set #Day = 'Monday';
While (#Day != 'Saturday' )
Begin
While (#Beg <= #End)
Begin
Set #Temp = #Beg;
Set #Temp = DateAdd(MINUTE,5,#Temp)
Insert into TIMESLOT (Beg_Time, End_Time, TimeDayOFWeek)
Values (#Beg, #Temp, #Day)
If (#Beg <= #End)
Begin
Set #Beg = #Temp
End
Else
Begin
Set #Beg = '08:00 AM'
Set #Day = DateAdd(day,1, #Day)
End
End
End
This is the code that finally fixed the issue, Wheels73 was correct my syntax was wrong. But I also had the if statement and the variable #beg reset in the wrong area.
While (#Day != 'Saturday' ) -- first end
Begin
While (#Beg < #End)
Begin--Second
Set #Temp = #Beg
Set #Temp = DateAdd(MINUTE,5,#Temp)
Insert into TIMESLOT (Beg_Time, End_Time, TimeDayOFWeek)
Values (#Beg, #Temp, #Day)
Set #Beg = #Temp
End--Second
Set #Beg = '08:00 AM'
if(#Day = 'Monday')
Begin
Set #Day = 'Tuesday'
End
Else if(#Day = 'Tuesday')
Begin
Set #Day = 'Wednesday'
End
Else if (#Day = 'Wednesday')
Begin
Set #Day = 'Thursday'
End
Else if (#Day = 'Thursday')
Begin
Set #Day = 'Friday'
End
Else
Begin
Set #Day = 'Saturday'
End
End--firstenter code here

SQL Server Row Into Column

We have a table showing amounts (CHGCNT) for 3 dates (5-9-2016, 5-10-2016, 5-11-2016) for each store & Depts.
I want to be able to see the records in a table like this:
I already applied the following query
declare #dt as datetime
declare #dt1 as varchar(10)
declare #dt2 as varchar(10)
declare #dt3 as varchar(10)
select distinct #dt = min(effdt) from [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
-- print CONVERT(CHAR(10), #dt, 110) + ' ---- ' + CONVERT(CHAR(10), #dt+1 , 110)
set #dt1 = CONVERT(CHAR(10), #dt, 110)
set #dt2 = CONVERT(CHAR(10), #dt +1 , 110)
set #dt3 = CONVERT(CHAR(10), #dt + 2 , 110)
--print #dt1 + ' ---- ' + #dt2 + '-----' + #dt3
SELECT DEPTNM, DEPT, [#dt1] , [#dt2] , [#dt3]
FROM [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
PIVOT
(
SUM(CHGCNT)
FOR effdt IN ( [#dt1] , [#dt2] , [#dt3])
) AS P
but it is returning dates
I like the SUM-CASE approach:
SELECT deptnm,
SUM(CASE WHEN effdt = '2016-05-09' THEN chgcnt ELSE 0 END) "2016-05-09",
SUM(CASE WHEN effdt = '2016-05-10' THEN chgcnt ELSE 0 END) "2016-05-10",
SUM(CASE WHEN effdt = '2016-05-11' THEN chgcnt ELSE 0 END) "2016-05-11",
SUM(effdt) Total
FROM [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
GROUP BY deptnm;

order by column based on starting Number(Number may be decimal) in a string in sql server

i have a column named name in my table and example data i have included below
name
-----
1.arun888
2.nikl55555
11.abcd5566
1.123.bhdf
2.767ss777
1.21cdm
and i want to sort the deatils like below
name
----
1.arun888
1.123.bhdf
1.21cdm
2.nikl55555
2.767ss777
11.abcd5566
I have tried many ways but nothing works for me
first method i had used
DECLARE #string varchar(100),
#start int,
#end int,
#len int
SET #string = '66555.12tttthe hollies 12345 Test Ad77dress Dr.'
set #string = replace(#string, ' ' , '')
set #len = len(#string)
set #start = PATINDEX('%[0-9]%',#string)
set #end = PATINDEX('%[^0-9]%',substring(#string, #start, #len))-1
print substring(#string, #start, #end)
but it gives only 66555
but i need
66555.12
second method i had used
CREATE FUNCTION dbo.fn_GetNumeric
(#strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE #intAlpha INT
SET #intAlpha = PATINDEX('%[^0-9]%', #strAlphaNumeric)
BEGIN
WHILE #intAlpha > 0
BEGIN
SET #strAlphaNumeric = STUFF(#strAlphaNumeric, #intAlpha, 1, '' )
SET #intAlpha = PATINDEX('%[^0-9]%', #strAlphaNumeric )
END
END
RETURN ISNULL(#strAlphaNumeric,0)
END
GO
i have used the above function but it wil return all the numbers from string
example
if string is 12.dddh5555
then it return 125555
so i am stuck here. i hope somebody can help me to find this
Try this code:
DECLARE #t TABLE ( name VARCHAR(20) )
INSERT INTO #t
VALUES ( '1.arun888' ),
( '2.nikl55555' ),
( '11.abcd5566' ),
( '1.123.bhdf' ),
( '2.767ss777' ),
( '1.21cdm' );
WITH cte
AS ( SELECT name ,
SUBSTRING(name, 1, PATINDEX('%[^0-9.]%', name) - 1) d
FROM #t
)
SELECT *
FROM cte
ORDER BY CAST(CASE WHEN RIGHT(d, 1) = '.' THEN SUBSTRING(d, 1, LEN(d) - 1)
WHEN d = '' THEN '0'
ELSE d
END AS DECIMAL(30, 10))
First I select substrings till the first symbol that is not dot or digit. Then just remove last dot and order by the result.
With function:
CREATE FUNCTION dbo.fn_GetNumeric
(
#strAlphaNumeric VARCHAR(256)
)
RETURNS DECIMAL(30, 10)
AS
BEGIN
DECLARE #s1 VARCHAR(256) = SUBSTRING(#strAlphaNumeric, 1,
PATINDEX('%[^0-9.]%',
#strAlphaNumeric) - 1)
RETURN CAST(CASE WHEN RIGHT(#s1, 1) = '.' THEN SUBSTRING(#s1, 1, LEN(#s1) - 1)
WHEN #s1 = '' THEN '0'
ELSE #s1
END AS DECIMAL(30, 10))
END
GO
SELECT * FROM TableName
ORDER BY dbo.fn_GetNumeric(name)

how to convert to specific value when input is in binary string format

I have a situation, where i will get a string like days varchar(7), days='1001101'
I want to produce an output like
1:sunday
0:absent
0:absent
1:wensday
1:thursday
0:abset
1:saturday
final output:sunday wensday thursday saturday
How can I achieve it by using T-SQL function. (Function with input output parameter)
Use CHOOSE function to get the result. Try this..
Note : This will work only in SQL SERVER 2012+.. If you want to use it on earlier version just use Case statements instead of Choose. Just to simply the code i have used CHOOSE function
CREATE FUNCTION dbo.Func (#dayss VARCHAR(1000))
returns VARCHAR(1000)
BEGIN
DECLARE #cnt INT =1,
#outpt VARCHAR(100),
#fina VARCHAR(100)='',
#outpt1 VARCHAR(100)=''
WHILE #cnt <= Len(#dayss)
BEGIN
SET #outpt = Substring(#dayss, #cnt, 1)
SELECT #outpt1 = CASE
WHEN #outpt = 1 THEN #outpt
+ Choose(#cnt, ':sunday ', ':monday ', ':tuesday ', ':wednesday ', ':thursday ', ':friday ', ':saturday ')
ELSE #outpt + ':absent '
END
SET #fina += #outpt1
SET #cnt+=1
END
RETURN #fina
END
SELECT dbo.Func('1001101')
OUTPUT : 1:sunday 0:absent 0:absent 1:wednesday 1:thursday 0:absent 1:saturday
To get the final OUTPUT
CREATE FUNCTION dbo.Funcfinal (#dayss VARCHAR(1000))
returns VARCHAR(1000)
BEGIN
DECLARE #cnt INT =1,
#outpt VARCHAR(100),
#fina VARCHAR(100)='',
#outpt1 VARCHAR(100)=''
WHILE #cnt <= Len(#dayss)
BEGIN
SET #outpt = Substring(#dayss, #cnt, 1)
SELECT #outpt1 = CASE
WHEN #outpt = 1 THEN Choose(#cnt, 'sunday ', 'monday ', 'tuesday ', 'wednesday ', 'thursday ', 'friday ', 'saturday ')
ELSE ''
END
SET #fina += #outpt1
SET #cnt+=1
END
RETURN #fina
END
SELECT dbo.Funcfinal('1001101')
OUTPUT : sunday wednesday thursday saturday
Traditional way of doing using CASE.
WHILE ( #i <= Len(#input) )
BEGIN
SET #temp = Substring(#input, #i, 1)
SET #output += ' '+(SELECT CASE
WHEN #temp = 1
AND #i = 1 THEN 'Sunday'
WHEN #temp = 1
AND #i = 2 THEN 'Monday'
WHEN #temp = 1
AND #i = 3 THEN 'Tuesday'
WHEN #temp = 1
AND #i = 4 THEN 'Wednesday'
WHEN #temp = 1
AND #i = 5 THEN 'Thursday'
WHEN #temp = 1
AND #i = 6 THEN 'Friday'
WHEN #temp = 1
AND #i = 7 THEN 'Saturday'
ELSE ''
END)
SET #i = #i + 1
END
PRINT #output
create function dateconvert(#input varchar(100))
returns varchar(1000)
begin
declare
#i int=1,
#temp varchar(1000)='',
#output1 varchar(1000)='',
#output varchar(1000)
while (#i<=len(#input))
begin
set #temp = substring(#input, #i, 1)
set #output= ( select case
when #temp = '1'
and #i = 1 then 'sunday'
when #temp = '1'
and #i = 2 then 'monday'
when #temp = '1'
and #i = 3 then 'tuesday'
when #temp = '1'
and #i = 4 then 'wednesday'
when #temp = '1'
and #i = 5 then 'thursday'
when #temp = '1'
and #i = 6 then 'friday'
when #temp = '1'
and #i = 7 then 'saturday'
else '_'
end )
set #output1=#output1+#output
set #i = #i + 1
end
return #output1
end

Resources