SQL Server order by part of string - sql-server

One of my tables have values like this..
Year 1
Year 9
Year 4
Kindy [can be any word without numbers]
Pre-School [can be any word without numbers]
Year 8
Year 22
Year 15....
How can I select Them in alphabetically first and then by numerically in ascending order like this..
Kindy [can be any word without numbers]
Pre-School [can be any word without numbers]
Year 1
Year 4
Year 8
Year 9
Year 15
Year 22
I could not extract the integer and order in this case as some of the years don't have it..
UPDATE
MY ANSWER -- MISSING DISTINCT
SELECT YearLevel FROM Student
ORDER BY
CASE WHEN YearLevel NOT LIKE '%[0-9]%' THEN 0
ELSE CAST(RIGHT(YearLevel, LEN(YearLevel) - 5) AS int)
END

Try this in the ORDER BY clause:
ORDER BY
CASE WHEN col = 'Kindy' then 0
WHEN col = 'Pre-School' then 1
ELSE CAST(SUBSTRING(col,6,LEN(col)) AS INT) + 1
END

In first you must create following function for get text part and number part of your string :
CREATE FUNCTION [dbo].[GetNumbersFromText](#String varchar(2000))
RETURNS INT
AS BEGIN
DECLARE #Count INT = 0,
#IntNumbers VARCHAR(1000) = '',
#FindNumber BIT = 0
WHILE #Count <= LEN(#String) BEGIN
IF SUBSTRING(#String,#Count,1) >= '0' AND SUBSTRING(#String,#Count,1) <= '9' BEGIN
SET #IntNumbers = #IntNumbers + SUBSTRING(#String,#Count,1)
SET #FindNumber = 1
END ELSE IF (#FindNumber = 1) BEGIN
BREAK
END
SET #Count = #Count + 1
END
RETURN CAST(#IntNumbers AS INT)
END
CREATE FUNCTION [dbo].[GetTextPartOfText](#String varchar(2000))
RETURNS INT
AS BEGIN
DECLARE #Count INT = 0,
#Text VARCHAR(1000) = '',
WHILE #Count <= LEN(#String) BEGIN
IF SUBSTRING(#String,#Count,1) >= '0' AND SUBSTRING(#String,#Count,1) <= '9' BEGIN
BREAK
END ELSE BEGIN
SET #Text = #Text + SUBSTRING(#String,#Count,1)
END
SET #Count = #Count + 1
END
RETURN #Text
END
In second you use following query for your sort:
SELECT *
FROM YourTable
ORDER BY [dbo].[GetTextPartOfText](TextColumn),[dbo].[GetNumbersFromText](TextColumn), TextColumn

SELECT YearLevel FROM student
GROUP BY YearLevel
ORDER BY
(CASE
WHEN YearLevel LIKE 'Year%'
THEN 'Year' + CONVERT(varchar,LEN(YearLevel)) + YearLevel
ELSE YearLevel
END)

Related

Regex to get only last occurrence of each digit in string

I am working with SQL Server and have come to encounter a situation for which I have no answer. It is as follows:
Given a string diuuuu, for example, I would like this output diu. The logic behind it is the last occurrance of each digit (d, i, u) in order. Other examples:
diudi = udi
dididi = di
A Regex solution would be greatly appreciated. Thank you!
This isn't particularly pretty, but it does do the job:
WITH VTE AS(
SELECT *
FROM (VALUES('diudi'),('diuuuu'),('dididi'),('ddddd'))V(YourColumn)),
Ranks AS(
SELECT V.YourColumn,
CI.C,
CI.I,
RANK() OVER (PARTITION BY V.YourColumn ORDER BY CI.I) AS R
FROM VTE V
CROSS APPLY (VALUES(REVERSE(V.YourColumn)))R(YourColumn)
CROSS APPLY (VALUES('d',CHARINDEX('d',R.YourColumn)),
('i',CHARINDEX('i',R.YourColumn)),
('u',CHARINDEX('u',R.YourColumn)))CI(C,I))
SELECT YourColumn,
REVERSE(CONCAT(MAX(CASE WHEN R = 1 AND I > 0 THEN C END),MAX(CASE WHEN R = 2 AND I > 0 THEN C END),MAX(CASE WHEN R = 3 AND I > 0 THEN C END)))
FROM Ranks
GROUP BY YourColumn;
This should work:
(.)(?!.*\1)
The groups returned, concatenated together, give you what you want.
Here's a SQL Answer:
CREATE FUNCTION dbo.udf_LastChars(#str VARCHAR(100))
RETURNS VARCHAR(100)
AS
BEGIN
DECLARE #result VARCHAR(100)
DECLARE #char CHAR(1)
DECLARE #i INT = 1
WHILE (#i <= LEN(#str))
BEGIN
SET #char = SUBSTRING(#str, #i, 1)
SET #result = CONCAT(REPLACE(#result, #char, ''), #char)
SET #i = #i + 1
END
RETURN #result
END

Unicode (Hexadecimal) to varchar conversion

Here is the problem, the system I use can create a saved search which basically generates a 'Where' clause and saves it in the database as type Image ..
I am trying to convert the image entry to a readable format, it is saved in 2 forms (Unicode and non unicode) now I can get the non unicode entries fine and they display correctly, however when I try and convert the Unicode entries it does not display correctly an example of what I am trying to convert is
0x01000000FFFEFF00FFFEFF0001050000FFFEFF05510075006F007400650006000000060000000100000001000000000000000000000080000000000000FD00000000000000000700000001050000FFFEFF254E006F0072006700720065006E005F00470072006F007500700020004900640020003D00200030007800300030003000300030003000300030003000300030003000300030003200330004000000060000000100000002000000000000000000002380000000000022B00000000000000001000000FFFEFF5454005400490044005F003400330034005200390032003300370020005F005F00530051004C005F00440045004C0049004D005F005F002000510075006F00740065005F002E004E006F0072006700720065006E005F00470072006F00750070005F004900640020003D00200054005400490044005F00340033003400520039003200330037002E004E006F0072006700720065006E005F00470072006F00750070005F00490064000000000001050000FFFEFF0C45006D0070006C006F0079006500650020003D0020003F0004000000060000000100000002000000000000000000000080000000000001030101000000000001000000FFFEFFA754005400490044005F00320035005200310032003400350034002E0054005400490044005F0032003300520038003600340052003100320034003500340020005F005F00530051004C005F00440045004C0049004D005F005F002000510075006F00740065005F002E0053006800690070005F0054006F005F0043006F006D00700061006E0079005F004900640020003D00200054005400490044005F00320035005200310032003400350034002E0043006F006D00700061006E0079005F0049006400200041004E004400200054005400490044005F00320035005200310032003400350034002E004100630063006F0075006E0074005F004D0061006E0061006700650072005F004900640020003D00200054005400490044005F003200330052003800360034005200310032003400350034002E0045006D0070006C006F007900650065005F00490064000000000001050000FFFEFF0C45006D0070006C006F0079006500650020003D0020003F0004000000060000000100000002000000000000000000000080000000000001030101000000000001000000FFFEFFB354005400490044005F00320035005200310032003400350034002E0054005400490044005F00320033005200380037003000390052003100320034003500340020005F005F00530051004C005F00440045004C0049004D005F005F002000510075006F00740065005F002E0053006800690070005F0054006F005F0043006F006D00700061006E0079005F004900640020003D00200054005400490044005F00320035005200310032003400350034002E0043006F006D00700061006E0079005F0049006400200041004E004400200054005400490044005F00320035005200310032003400350034002E0049006E007400650072006E0061006C005F0043006F006D006D00650072006300690061006C005F00530061006C00650073005F004900640020003D00200054005400490044005F0032003300520038003700300039005200310032003400350034002E0045006D0070006C006F007900650065005F00490064000000000001050000FFFEFF13510075006F0074006500200054006F00740061006C0020003E003D00200032003000300030000400000006000000010000000200000000000000000000008000000000001847010101080000000000000000409F400000000001000000FFFEFF15510075006F00740065005F0020005F005F00530051004C005F00440045004C0049004D005F005F0020000000000001050000FFFEFF1F46006F006C006C006F007700200055007000200053007400610074007500730020003D00200054006F00200046006F006C006C006F007700200055007000040000000600000001000000020000000000000000000000800000000000392F0000000000000001000000FFFEFF15510075006F00740065005F0020005F005F00530051004C005F00440045004C0049004D005F005F0020000200000001050000FFFEFF1F46006F006C006C006F007700200055007000200053007400610074007500730020003D00200049006E00200046006F006C006C006F007700200055007000050000000600000001000000020000000000000000000000800000000000392F0000000000000001000000FFFEFF15510075006F00740065005F0020005F005F00530051004C005F00440045004C0049004D005F005F0020000000000001050000FFFEFF1F46006F006C006C006F007700200055007000200053007400610074007500730020003D0020004E006F00200046006F006C006C006F007700200055007000050000000600000001000000020000000000000000000000800000000000392F0000000000000001000000FFFEFF15510075006F00740065005F0020005F005F00530051004C005F00440045004C0049004D005F005F0020000000000001050000FFFEFF20510075006F0074006500200046006F006C006C006F00770020004500780070006900720065007300200049006E002000440061007900730020003E002000310004000000060000000100000002000000000000000000000080000000000039DD0000000000000001000000FFFEFF4854005400490044005F003700310035004C003100340034003600330020005F005F00530051004C005F00440045004C0049004D005F005F002000510075006F00740065005F002E00510075006F00740065005F005F004900640020003D00200054005400490044005F003700310035004C00310034003400360033002E00510075006F00740065005F005F00490064000000000001050000FFFEFF11510075006F00740065005F0020004900640020004E006F007400200049006E00200004000000060000000100000002000000000000000000000080000000000018F5000000040000000100000000000000000000000000000001000000FFFEFF15510075006F00740065005F0020005F005F00530051004C005F00440045004C0049004D005F005F0020000000000003000000010000000000000000002F9680000000000018F5000000000000000000000000
the SQL code I am using to convert is the following
with saved_lookups_cte as
(select
table_id,
table_name,
saved_lookups_id,
saved_lookup_name,
case
when charindex('WhereDelim',query_text) > 0 then
substring(query_text,len(query_text) - charindex(reverse('WhereDelim'),reverse(query_text)) + 3,4000)
else query_text
end query_text
, sql_tree_binary
from (select
table_id,
table_name,
saved_lookups_id,
saved_lookup_name,
case isUnicode
when 1 then [Production_ED].dbo.[RemoveNonASCII] (cast(cast(substring(sql_tree_binary, startIndex, queryLength * 2) as nvarchar(max))as varchar(max)))
else cast(substring(sql_tree_binary, startIndex, queryLength) as varchar(8000))
end query_text
, sql_tree_binary
from (
select
saved_lookup_name,
case
when substring(sql_tree_binary,1,5) = 0x0100000000 then 0
when substring(sql_tree_binary,1,5) = 0x01000000FF then 1
end isUnicode,
cast(case
when substring(sql_tree_binary,1,5) = 0x0100000000 then
case
when substring(sql_tree_binary,6,1) = 0xFF then substring(sql_tree_binary,8,1) + substring(sql_tree_binary,7,1)
else substring(sql_tree_binary,6,1)
end
when substring(sql_tree_binary,1,5) = 0x01000000FF then
case
when substring(sql_tree_binary,12,1) = 0xFF then substring(sql_tree_binary,14,1) + substring(sql_tree_binary,13,1)
else substring(sql_tree_binary,12,1)
end
end as int) queryLength,
case
when substring(sql_tree_binary,1,5) = 0x0100000000 then
case
when substring(sql_tree_binary,6,1) = 0xFF then 9
else 7
end
when substring(sql_tree_binary,1,5) = 0x01000000FF then
case
when substring(sql_tree_binary,12,1) = 0xFF then 15
else 13
end
end startIndex,
s.table_id,
t.table_name,
s.saved_lookups_id,
s.sql_tree_binary
from
Production_Ed.dbo.Saved_Lookups s inner join
tables t on s.table_id = t.tables_id
-- where substring(saved_lookups_id,1,1) <> 0x00
where saved_lookup_name = 'DE Quotes Open Account Manager >=2000'
) x
) y
)
select * from saved_lookups_cte
The part of the query that does the conversion is
when 1 then [Production_ED].dbo.[RemoveNonASCII]
(cast(cast(substring(sql_tree_binary, startIndex, queryLength * 2) as
nvarchar(max))as varchar(max)))
now this actually returns nothing, however if I set the startIndex to 17 and change the queryLength to 3000 * 2 (unicode byte = 2) I get
??Quote?????Norgren_Group Id = 0x0000000000000023???A??????????????? ????????????? ??????????????????????? ? ??????????????????????????????A?????????? ? ???A??Aa??TTID_25R12454.TTID_23R864R12454 __SQ
Returned, although I can read parts, it is not the full query ... yet even if I extend the length I get no more.
Any help would be greatly appreciated.
Code for the RemoveNonASCII function:
ALTER FUNCTION [dbo].[RemoveNonASCII]
(
#nstring nvarchar(max)
)
RETURNS varchar(max)
AS
BEGIN
DECLARE #Result varchar(max)
SET #Result = ''
DECLARE #nchar nvarchar(1)
DECLARE #position int
SET #position = 1
WHILE #position <= LEN(#nstring)
BEGIN
SET #nchar = SUBSTRING(#nstring, #position, 1)
IF ASCII(#nchar) between 32 and 255
SET #Result = #Result + #nchar
SET #position = #position + 1
END
RETURN #Result
END
GO
Ok, so I found the issue, inside the hex string there were null values, which caused the rest of the returned varchar string to become null .. So I just changed the function to:
AS
BEGIN
DECLARE #Result varchar(max)
SET #Result = ''
DECLARE #nchar nvarchar(1)
DECLARE #position int
SET #position = 1
WHILE #position <= LEN(#nstring)
BEGIN
SET #nchar = SUBSTRING(#nstring, #position, 1)
IF ASCII(#nchar) between 1 and 125
SET #Result = #Result + #nchar
SET #position = #position + 1
END
RETURN #Result
END
Eradicating 0 being the ASCII Null value!

Adding Rows from one table to Another Table based on days of month SQL

I have a table named Students having 10 records of students
ID StudentName
1 Student a
2 Student b
- ------ -
10 Student N
now i want to add these 10 students to another table based on days of month e.g
ID StudentName DayOfMonth
1 Student a 1
2 Student a 2
- --------- -
- Student a 31
- Student b 1
- ------- b 31
And for all the students is there any SQL dynamic Solution
I tried using Cursor but it takes approx 2 minutes if there are 55 Students in a table. While I checked the table during execution of proc it generate 1705 rows i.e (55x31) in a matter of seconds but than it reacts as it is hanged or something and after 2 minutes it shows the success message.
any help will be greatly appreciated.
#fkStudentID int,
#fkClassID int,
#fkSessionID int,
#Dated date,
AS
Declare #Days as int
Set #Days = DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,#Dated),0)))
Declare #OffSet as int
DECLARE #MyCursor CURSOR;
DECLARE #MyField int;
BEGIN
SET #MyCursor = CURSOR FOR
select fkStudentID from dbo.tblAdmission
where fkClassID = #fkClassID and fkSessionID = #fkSessionID
OPEN #MyCursor
FETCH NEXT FROM #MyCursor
INTO #MyField
WHILE ##FETCH_STATUS = 0
BEGIN
While(#OffSet <= #Days)
Begin
if(IsNull((Select count(RegisterID) from tblRegister where #MyField = fkStudentID and fkClassID = #fkClassID and fkSessionID = #fkSessionID and [Dayofmonth] = #OffSet),0) = 0)
Begin
Insert into tblRegister (fkStudentID, fkClassID, fkSessionID, [DayOfMonth], Dated) values (#MyField, #fkClassID, #fkSessionID, #OffSet, DATEADD(DAY, (#OffSet - 1), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)))
End
Set #OffSet = #OffSet + 1
End
Set #OffSet = 1
FETCH NEXT FROM #MyCursor
INTO #MyField
END;
CLOSE #MyCursor ;
DEALLOCATE #MyCursor;
END;
I'm not sure why you see a delay before the proc ends but it is best to use a set-based query instead of cursor whenever possible for best performance. I expect the example below will run in less than a second as long as you have appropriate indexes (ideally, a unique clustered index on dbo.tblAdmission fkClassID and fkSessionID columns and a unique index on dbo.tblRegister fkStudentID, fkClassID, fkSessionID, and DayOfMonth).
CREATE PROC dbo.Example
#fkClassID int,
#fkSessionID int,
#Dated date
AS
INSERT INTO dbo.tblRegister
(
fkStudentID
, fkClassID
, fkSessionID
, DayOfMonth
, Dated
)
SELECT
a.fkStudentID
, a.fkClassID
, a.fkSessionID
, o.offset
, DATEADD(DAY, (o.offset - 1), DATEADD(MONTH, DATEDIFF(MONTH, '', GETDATE()), ''))
FROM dbo.tblAdmission AS a
CROSS JOIN (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)
,(11),(12),(13),(14),(15),(16),(17),(18),(19),(20)
,(21),(22),(23),(24),(25),(26),(27),(28),(29),(30),(31)) AS o(offset)
WHERE
a.fkClassID = #fkClassID
AND a.fkSessionID = #fkSessionID
AND o.offset <= DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,#Dated),0)))
AND NOT EXISTS(
SELECT 1
FROM dbo.tblRegister AS r
WHERE
r.fkStudentID = a.fkStudentID
AND r.fkClassID = a.fkClassID
AND r.fkSessionID = a.fkSessionID
AND [Dayofmonth] = o.offset
);

How to improve the performance of this sql script

The below script takes more than 10 hours to execute..
It contains three nested cursors and i think they are the main culprit.
I have searched a lot for replacing the cursors or improve the performance of the script.And found a lot of ways to remove the cursor. e.g. simple set join operations, Marge operation etc etc. But still I am unable to implement them in my script. Please take look on the script and give some opinion on
- with out affecting the output, is it possible to remove the inner cursors or not
- if possible then how ? please give some code if possible
DECLARE #Start_Date Date = '1990-01-01'
DECLARE #End_Date Date = '2012-12-12'
DECLARE #Company_ID int = 180
declare #BP_ID [int]
DECLARE All_Client_Bp_Id CURSOR STATIC FOR
SELECT TOP 50 Bp_id FROM Client --Take All Client's BPID
OPEN All_Client_Bp_Id
FETCH NEXT FROM All_Client_Bp_Id
INTO #BP_ID
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #acrdint MONEY
DECLARE #acrdSrv MONEY
DECLARE #MaxMargLimit MONEY
DECLARE #ForceLimit MONEY
DECLARE #WarningLimit MONEY
DECLARE #MarginLimit DECIMAL(5,2)
select #MaxMargLimit=Highest_Margin_Limit*100000,#ForceLimit=Force_Sell_Limit,#WarningLimit=Margin_Warning_Limit, #MarginLimit = Margin_Limit
from Client_Margin_Constraints c
inner join (select Bp_id, max(Update_Date) as updt
from Client_Margin_Constraints
where Update_Date <= #End_Date and Bp_id = #BP_ID and Company_ID = #Company_ID
group by Bp_id) b
on c.Bp_id = b.Bp_id and c.Update_Date = b.updt
DELETE FROM Temp_Portfolio
INSERT INTO Temp_Portfolio (Client_BP_ID, tran_date, Instrument_ID, Is_Buy, Quantity, Amount, Commission, Rate, Category,Tax_Amount)
SELECT t.Client_BP_ID, t.tran_date, t.Instrument_ID, t.Is_Buy, t.Quantity, t.Amount, t.Commission,
t.Rate, t.Category, t.Tax_Amount
FROM All_Share_Txn t
WHERE t.Client_BP_ID = #BP_ID
DECLARE #Instrument_Id int,
#bqty int,
#bamt MONEY,
#brate MONEY,
#srate MONEY,
#rprofit MONEY,
#mslbqty int,
#BCost MONEY,
#SCost MONEY,
#BCqty int,
#SCqty int,
#B_Or_S CHAR(1),
#CDBL_Type CHAR(1),
#Qty INT,
#MktPrice MONEY,
#Amount MONEY,
#Commission MONEY,
#TDATE SMALLDATETIME,
#DES CHAR(30),
#TotalProfit MONEY,
#Category CHAR(1)
SET #TotalProfit = 0
DECLARE CUR_SHARE CURSOR STATIC FOR
SELECT DISTINCT Instrument_Id
FROM Temp_Portfolio
OPEN CUR_SHARE
FETCH NEXT FROM CUR_SHARE
INTO #Instrument_Id
WHILE ##FETCH_STATUS = 0
BEGIN
SET #bqty = 0
SET #bamt = 0
SET #brate = 0
SET #srate = 0
SET #rprofit = 0
SET #mslbqty = 0
SET #BCost = 0
SET #SCost = 0
SET #BCqty = 0
SET #SCqty = 0
DECLARE CUR_COST CURSOR STATIC FOR
SELECT Is_buy,Quantity,rate,Amount,Commission,Tran_date
FROM Temp_Portfolio
WHERE Client_Bp_id=#BP_ID and Instrument_Id=#Instrument_Id
ORDER BY Tran_date,Is_buy desc,Category
OPEN CUR_COST
FETCH NEXT FROM CUR_COST
INTO #B_Or_S,#Qty,#MktPrice,#Amount,#Commission,#TDATE
WHILE ##FETCH_STATUS = 0
BEGIN
IF #B_Or_S='1'
BEGIN
SET #bqty = #bqty + #Qty
SET #bamt = #bamt + #Amount + #Commission
IF #bqty > 0
SET #brate = #bamt/#bqty
END
ELSE IF #B_Or_S='0'
BEGIN
SET #srate = #MktPrice
IF #TDATE > #Start_Date and #TDATE <= #End_Date
BEGIN
SET #rprofit = #rprofit + ((#srate - #brate) * #Qty) - #Commission
SET #BCqty = #BCqty + #Qty
SET #SCqty = #SCqty + #Qty
SET #BCost = #BCost + (#Brate * #Qty)
SET #SCost = #SCost + (#Srate * #Qty) - #Commission
END
SET #bamt = #bamt - (#brate * #Qty)
SET #bqty = #bqty - #Qty
END
FETCH NEXT FROM CUR_COST
INTO #B_Or_S,#Qty,#MktPrice,#Amount,#Commission,#TDATE
END
SET #TotalProfit=#TotalProfit+#rprofit
CLOSE CUR_COST
DEALLOCATE CUR_COST
FETCH NEXT FROM CUR_SHARE
INTO #Instrument_Id
END
CLOSE CUR_SHARE
DEALLOCATE CUR_SHARE
--Select #TotalProfit as Realised_Gain
-- Equity, Purchase Power Calculation
DECLARE #Equity_All MONEY
DECLARE #Equity_Margin MONEY
DECLARE #Current_Balance MONEY
DECLARE #temp_Purchase_Power_1 MONEY
DECLARE #temp_Purchase_Power_2 MONEY
DECLARE #Purchase_Power MONEY
--Balance
select #Current_Balance = sum((case when a.Is_Share_TXN='1' and a.Is_Debit='1' then -a.amount when a.Is_Share_TXN='1' and a.Is_Debit='0' then a.amount when a.Is_Share_TXN='0' and a.Is_Debit='0' then a.amount when a.Is_Share_TXN='0' and a.Is_Debit='1' then -a.amount end) -a.Commission)
from Client_Transaction a where a.Client_Bp_id = #BP_ID and a.Transaction_Date < #End_Date and a.Company_Id=#Company_Id
group by a.Client_Bp_id--dbo.get_Current_Balance(#BP_ID, #End_Date, #Company_ID)
--Equity Margin
SELECT #Equity_Margin = SUM(CASE WHEN t_Margin.Is_Marginable_Securities = 'True' Then t_Margin.Total_Quantity * t_Margin.Market_price END),
#Equity_All = SUM(t_Margin.Total_Quantity * t_Margin.Market_price)
FROM
(
select t2.Is_Marginable_Securities, --t3.Bp_Code as Client_Code,t3.Bp_Name as Client_Name,t4.Bo_Id_DSE,t1.Instrument_ID,
sum(case when Is_buy='True' then Quantity when Is_buy='False' then -quantity end) as Total_Quantity,
--sum(case when ISNULL(t1.Mature_Date_Share,t1.tran_date) <= #Transaction_Date then (case Is_buy when '1' then quantity when '0' then -quantity end) else 0 end) as Free_Quantity,
INDX.Closing_Price AS Market_price
from dbo.View_All_Share_Transactions_with_PledgeUnpledge t1 left outer join Instrument t2 on t1.Instrument_Id=t2.Instrument_ID
left outer join (
select Closing_Price from Index_Price ip
where ip.Txn_Date=(select MAX(Txn_Date) from Index_Price ip2 where ip2.Instrument_Id=ip.Instrument_Id)
) INDX
ON t1.Instrument_ID = INDX.Closing_Price
where Client_Bp_id = #BP_ID and t1.Instrument_ID is not null and tran_date <=#End_Date and t1.Is_Pledge_Unpledge = 'False'
group by t1.Instrument_ID,t2.Is_Marginable_Securities, INDX.Closing_Price
having sum(case when Is_buy='True' then Quantity when Is_buy='False' then -quantity end)<> 0
) t_Margin --dbo.get_Equity_Margin(#BP_ID, #End_Date, #Company_ID)
SET #Equity_Margin = #Equity_Margin + #Current_Balance
SET #Equity_All = #Equity_All + #Current_Balance
SET #temp_Purchase_Power_1 = (#Equity_Margin * (#MarginLimit / 100)) + #Current_Balance
SET #temp_Purchase_Power_2 = ISNULL(#MaxMargLimit,0) + ISNULL(#Current_Balance,0)
IF (#temp_Purchase_Power_1 < #temp_Purchase_Power_2)
BEGIN
SET #Purchase_Power = #temp_Purchase_Power_1
END
ELSE
BEGIN
SET #Purchase_Power = #temp_Purchase_Power_2
END
INSERT Client_Account_Balance (
BP_ID,
Equity_All,
Equity_Margin,
Purchase_Power,
Margin_Ratio,
Total_Deposit,
Withdraw,
Charges,
Current_Balance,
Aaccured_Charges,
Max_Margin_LImit,
Margin_Limit,
Realised_Gain,
Company_ID,
Created_By,
Updated_By
)
SELECT #BP_ID, #Equity_All,#Equity_Margin ,#Purchase_Power ,
CASE WHEN (#Current_Balance - ISNULL(#acrdSrv,0)) != 0 THEN (#Equity_Margin - #Current_Balance) * (-100)/(#Current_Balance - ISNULL(#acrdSrv,0)) ELSE 0 END,
TDEP,TWDRAW,TCHARGES,BALANCE,ACC_CHARGE,#MaxMargLimit ,#MarginLimit,
#TotalProfit,
180,1,1
FROM
(SELECT SUM(DEPOSITE) AS TDEP,SUM(WDRAW) AS TWDRAW,SUM(CHARGES) AS TCHARGES,SUM(DEBCRED-Commission) AS BALANCE,SUM(ISNULL(#acrdint,0)+ISNULL(#acrdSrv,0)) AS ACC_CHARGE
FROM
(SELECT (CASE
WHEN tran_date >= #Start_Date THEN
CASE Is_Share_TXN
WHEN '0' THEN
CASE Is_Debit
WHEN '1' THEN 0
ELSE AMOUNT END
ELSE 0 END
ELSE 0 END) AS Deposite,
(CASE
WHEN tran_date >= #Start_Date THEN
CASE Is_Share_TXN
WHEN '0' THEN
CASE Is_Debit
WHEN '1' THEN
CASE T_TYPE
WHEN '1' THEN AMOUNT
WHEN '3' THEN AMOUNT
WHEN 'T' THEN AMOUNT
ELSE 0 END
ELSE 0 END
ELSE 0 END
ELSE 0 END) AS WDRAW,
(CASE
WHEN tran_date >= #Start_Date THEN
CASE Is_Share_TXN
WHEN '0' THEN
CASE Is_Debit
WHEN '1' THEN
CASE T_TYPE
WHEN '1' THEN 0
WHEN '3' THEN 0
WHEN 'T' THEN 0
ELSE AMOUNT END
ELSE 0 END
ELSE 0 END
ELSE 0 END) AS CHARGES,
(CASE Is_Share_TXN
WHEN '1' THEN
CASE Is_Debit
WHEN '1' THEN -AMOUNT
ELSE AMOUNT END
When '0' THEN
CASE Is_Debit
WHEN '1' THEN -AMOUNT
ELSE AMOUNT END
END) AS DEBCRED,Commission
FROM View_All_Transaction
WHERE tran_date <= #End_Date
AND Client_Bp_id = #BP_ID ) AS A) AS B
FETCH NEXT FROM All_Client_Bp_Id
INTO #BP_ID
END
CLOSE All_Client_Bp_Id
DEALLOCATE All_Client_Bp_Id
Hey i had a look with your script and found ..you can improve your scripts performance by excluding DISTINCT clause and create non-cluster index against column which following ORDER BY CLAUSE as well.
These 2 point will definitly help you to improve the performance.
Please let me know if you have any query.

Need to create a function in sql to find a string

I am trying to write a function which can tell me whether there is something after second ; in the string or not.For example: the sample string is "2:00AM;3:00PM;". So the function in this case needs to return false.
Assuming that there'll always be a second ;, and no third one, this ought to work...
CREATE FUNCTION dbo.fn_Bob(#str VARCHAR(20)) RETURNS BIT
BEGIN
RETURN CASE WHEN #str LIKE '%;' THEN 0 ELSE 1 END
END
The CHARINDEX has an optional parameter to choose the start position, so find the first index of the ";" and add 1 that will start at the next character and then check for the next index and the length should be longer.
DECLARE #stringToTest nvarchar(100)
SET #stringToTest = '2:00AM;3:00PM;';
IF(LEN(#stringToTest) > CHARINDEX(';', #stringToTest, CHARINDEX(';', #stringToTest) + 1))
BEGIN
PRINT 'Yes'
END
ELSE
BEGIN
PRINT 'No'
END
create function [dbo].[udf_IsValidCheck](#Value varchar(64)) returns bit
as
begin
declare #IsValidCheck bit
select #IsValidCheck = (case when charindex( ';', #Value, charindex(';', #Value) + 1) > 0
and charindex( ';', #Value, charindex(';', #Value) + 1) < len(#Value) then 1
else 0 end)
return #IsValidCheck
end
test data:
'2:00AM;3:00PM;' --returns 0
'2:00AM;3:00PM' --returns 0
'2:00AM;3:00PM;3rdValue;4thValue;' --returns 1
'2:00AM;3:00PM;3rdValue;' --returns 1
'2:00AM;3:00PM;3rdValue' --returns 1
'2:00AM;' -- returns 0
'2:00AM;' -- returns 0

Resources