Tuesday, March 14, 2023

sql server query to json

 sql server query result to json object

      
	SELECT [SettingKey]
		   ,[SettingValue]
	FROM Config.ServiceSettings
	WHERE ServiceID =15
	FOR JSON PATH 
       
 

Tuesday, March 7, 2023

sql server JSON_MODIFY and OpenJson Tips

 Json Modify Mulitple json properties at the same time

       
declare @OrderBody nvarchar(max) = (select  sme.fnOrderBodyGet(@OrderID))
declare @OrderBodyNew nvarchar(max) 
set @OrderBodyNew =JSON_MODIFY(
		               JSON_MODIFY(JSON_MODIFY(@OrderBody, 'strict$.Details.TransactionNumber', cast(@paymentID as varchar))
								,'strict$.Details.PaymentReferenceNo',@PaymentReferenceNo )
					 ,'strict$.Details.PaymentMethodID',cast(@paymentMethodID as varchar))
       
 
Select Json Array as Table

       
 DECLARE @JSONINPUT nvarchar(4000) =
    '{
        "OUTER": [{
                    "ABC":"TEST_WB_New","XYZ":"9085"
                 },
                 {
                    "ABC":"TEST_WB1_New","XYZ":"9086"
                 },
                 {
                    "ABC":"TEST_WB2_New","XYZ":"9087"
                 }]
    }';

    SELECT ABC, XYZ 
    FROM OPENJSON(@JSONINPUT,'$.OUTER') 
    WITH (ABC NVARCHAR(50), XYZ NVARCHAR(50))
       
 

Select Single Property from json field
       
DECLARE @result nvarchar(max)
	declare @paymentResponse nvarchar(500)
select @paymentResponse = sme.fnPaymentResponseBodySTDGet(@PaymentID) 
	SELECT @result=PaymentProviderReferenceNo
FROM OPENJSON ( @paymentResponse )  
WITH (   
              PaymentProviderReferenceNo   VARCHAR(200)   '$.PaymentProviderReferenceNo' 
 )
       
 

Sunday, February 19, 2023

automapper map destination object to two sources objects

 problem:

i Have two models for child Components in blazor hosted app,

i need to bind two models to parent component model after validation for each one.


solution:

create map for two models with destination one

       
public class AutoMapper : Profile

    {

        public AutoMapper()

        {

  CreateMap();

        CreateMap();

} 

parent component declarations
       
[Inject] public IMapper? _mapper { get; set; }

 [Inject] protected IJSRuntime JS { get; set; }

[Inject] protected IWebAssemblyHostEnvironment host { get; set; }

 public ReceiptFormModel? FormModel { get; set; } = new();

  public VATTaxNumberModel? VATTaxNumberModel { get; set; }=new();

   public PolicyOwnerModel? PolicyOwnerModel { get; set; } =new();



 private async Task prepareModel()

        {

            var MapFirstModel = _mapper.Map(VATTaxNumberModel);

            FormModel= _mapper.Map(PolicyOwnerModel, MapFirstModel);



            LogToConsole($"FormModel=={JsonSerializer.Serialize(FormModel)}");

        }

protected void LogToConsole(string message)

    {

        if (host.IsDevelopment())

            JS.InvokeAsync("console.log", message);

    }

       
 

 

Monday, January 23, 2023

sql server update column to primary key in another table to prepare data for insert

Problem:

i have excel file need to export it in more than table into sql server database .

so after import data for temp table i need to select every primary table data and insert it.

so i need to create mapping columns for primary keys for master table to be able to insert detail table data with primary key for table.


example : i have this excel file data 



i have two tables :

RegionsTable

CityTable

i need after export to create insert into these two tables .

Region Table


City Table


solution:

1- select distinct regions from temp table and insert into Region Table:

         INSERT INTO [Lookups].[Regions]

           ([RegionId]

           ,[RegionNameAR]

           ,[RegionNameEN]

           ,[RegionPostalCode]

           ,[GeoRegionId])

    select distinct

          [RegionId]

           ,[RegionNameAR]

           ,[RegionNameEN]

           ,[RegionPostalCode]

           ,[GeoRegionId]

from dbo.Cities$      
 

2- create new column in temp table to save RegionId into .

ALTER TABLE dbo.Cities$ ADD
RegionRefID tinyint NULL
GO 
     
 


update dbo.Cities$

update dbo.Cities$  
set RegionRefID = r.RegionId
from dbo.Cities$ c
inner join  Lookups.Regions r
on
r.RegionId=c.RegionId
and r.RegionNameAR=c.RegionNameAR
and r.RegionNameEn=c.RegionNameEn
and r.RegionPostalCode=c.RegionPostalCode
and r.GeoRegionId =c.GeoRegionId
       
 

3-update city Table with city and mapp new regionid with query to keep reference to Region Table.

	INSERT INTO [Lookups].[City]

			   ([CityId]

			   ,[CityNameAR]

			   ,[CityNameEN]

			   ,[RegionId])

			 select Id,

	CityNameAr

	,CityNameEn

	,RegionIdNew

			 from dbo.Cities$

	GO

done.

 

Thursday, January 19, 2023

Wednesday, December 28, 2022

Blazor Export Excel based on template excel file C#

 Target:

i have mudtable contains data from model object.

i need when user press on export excel button to load object data for mudtable to ready excel file template and write data for this template then download it for end user on the browser.


Used Nuget: NPOI version 2.6.0

Create custom component for export excel ExportExcel.razor

@inherits BaseComponentCustom

<a href="" @onclick="Export" class="btn btn-white btn-sm  shadow-sm fw-bold" data-bs-toggle="modal" data-bs-target="#kt_share">

    @trans["ExportData"]

    <!--begin:: Icon-->

    <img src="assets/media/svg/icon/share-qoute.svg" class="h-25px">

    <!--end:: Icon-->

</a>

*-------------------------------------------------------------------------------

using NPOI.SS.UserModel;

using NPOI.XSSF.UserModel;

namespace YourNameSpace;

public partial class ExportExcel

{

    private FileStream _file;

    [Parameter] public ExcelDataObject? ExcelDataObject{ get; set; }

    private async void Export()

    {

        if (ExcelDataObject!= null)

        {

            string rootpath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot/assets/Templates/");

            string name = "TemplateFile.xlsx";

            string FileName = Path.Combine(rootpath, name);

            IWorkbook _workbook;

            var memoryStream = new MemoryStream();

            ISheet excelSheet;

            _file?.Close();

            var bytes = new byte[0];

            _file = new FileStream(FileName, FileMode.Open, FileAccess.Read);

            {

                    _workbook = new XSSFWorkbook(_file);

                    _workbook.MissingCellPolicy = MissingCellPolicy.RETURN_NULL_AND_BLANK;

                _file.Close();

            }

            excelSheet = _workbook.GetSheetAt(0);

            IWorkbook workbook = excelSheet.Workbook;

            int i = 1;

            foreach (var member in ExcelDataObject.ListToGetColumnsData)

            {

                IRow row = excelSheet.CreateRow(i);

                row.CreateCell(0).SetCellValue(member.cell0Value);

                row.CreateCell(1).SetCellValue(member.cell2Value);

                row.CreateCell(2).SetCellValue(member.cell3Value);

               );

                i++;

            }

            using (var ms = new MemoryStream())

            {

                workbook.Write(ms, false);

                bytes = ms.ToArray();

            }



            await SaveAs(JS, FileName + ".xlsx", bytes);

        }


        async Task SaveAs(IJSRuntime js, string fileName, byte[] data)

        {

            await js.InvokeAsync<object>(

                "BlazorDownloadFile",

                fileName,

                Convert.ToBase64String(data)

            );

        }

    }

}

---------------------------------------------------------------------------------------------
Javascript Function

function BlazorDownloadFile(filename, bytesBase64) {
    var link = document.createElement('a');
    link.download = filename;
    link.href = "data:application/octet-stream;base64," + bytesBase64;
    document.body.appendChild(link); // Needed for Firefox
    link.click();
    document.body.removeChild(link);
}



Wednesday, November 9, 2022

C# linq Queries Tips and Tricks

 update multiple columns inside complex object

-------------------------------------------

  _policies = SharedFunctions.PoliciesFilterForTenant(policyTenants, _policies, _selectedTenant);

                foreach (TPolicy item in _policies)

                {

                    item.Roles = item.Roles.Select(r => { r.IsChecked = false; r.AssignmentId = 0; return r; }).ToList();

                }


---------------------------------------------------------------------

join two lists with multiple on condition

join table with custom list and get result using linq query.

 public bool UserTenantDelete(int TenantId, int GovId)

        {

            //get custom list to compare later

            List<UserTenant> TenantsToDelete = _ctx.UserTenants.Where(d => d.TenantId == TenantId && d.GovId == GovId).ToList();

            if (TenantsToDelete.Any())

            {

               List<SubjectAssignment> subjectAssignment = (from sa in _ctxPolicyServerDbContext.SubjectAssignments.ToList()

                                                             join ut in TenantsToDelete

                                                             on new {A=sa.TenantId, B=sa.SubjectId } equals new {A=ut.TenantId,B=ut.UserId.ToString()}

                                                             select  sa).ToList();

             //   _ctxPolicyServerDbContext.SubjectAssignments.RemoveRange(subjectAssignment);

               // _ctxPolicyServerDbContext.SaveChanges();

               // _ctx.SaveChanges();

                return true;

            }

            return false;


        }

-------------------------------------------------------------------------------------

Filter List using another List

   List<int> GovsNotAuthorized = _ctx.GovAgencyTenants.Where(a => a.TenantId != TenantId).Select(a=>a.GovId).ToList();
                List<int> GovsAuthorized = _ctx.GovAgencyTenants.Where(a => a.TenantId == TenantId).Select(a => a.GovId).ToList();
                List<int> result = GovsNotAuthorized.Where(x => !GovsAuthorized.Any(a => a == x)).Distinct().ToList(); 

-------------------------------------------------------------------------------------------------


Wednesday, November 2, 2022

.netCore Global Filter with injected services inside.

 problem:

when using global filter to authorize user with custom service function inside the IActionFilter

i have object reference Error for  for the service instance.

    public class GlobalActionFilter : IActionFilter

    {

        private readonly IUserAuthorizationService userAuthorizationService;


        public GlobalActionFilter(IUserAuthorizationService userAuthorizationService)

        {

            this.userAuthorizationService = userAuthorizationService;

        }

       

        public void OnActionExecuted(ActionExecutedContext context)

        {

        }

        public void OnActionExecuting(ActionExecutingContext context)

        {

            // our code before action executes

            try

            {

                string user = context.HttpContext.User?.Claims?.FirstOrDefault(i => i.Type == "name")?.Value;

                string tenantId = context.HttpContext.User?.Claims?.FirstOrDefault(i => i.Type == "tid")?.Value;

                tenantId ??= context.HttpContext.User?.Claims?.FirstOrDefault(i => i.Type == "http://schemas.microsoft.com/identity/claims/tenantid")?.Value;

                string subjectId = context.HttpContext.User.Claims?.FirstOrDefault(i => i.Type == "sub").Value;

                Audit.Core.IAuditScope auditScope = context.HttpContext.GetCurrentAuditScope();

                auditScope.SetCustomField("Username", user);

                auditScope.SetCustomField("TenantName", tenantId);

                var param = context.ActionArguments.SingleOrDefault(p => p.Key.ToLower()=="tenantid");

                context.ActionArguments.TryGetValue("TenantId", out object actionTenantId);

                if (actionTenantId != null)

                {

                    if(int.TryParse(tenantId, out int loggedInUserTenantId))

                    {

                        if (!userAuthorizationService.CheckTenantAdminPolicyForLoggedInUser(subjectId, loggedInUserTenantId, (int)actionTenantId))

                            context.Result = new UnauthorizedObjectResult("user is unauthorized");

                    }

                    

                }

            }

            catch (System.Exception)

            {

            }

        }

    }

Startup configuration for MyGlobal Custom filter.

 services.AddControllers(configure =>

            {

                AuditConfiguration.ConfigureAudit(services, Configuration);

                AuditConfiguration.AddAudit(configure);


                configure.Filters.Add(new GlobalActionFilter());

            });

---------------------------------------------------------------------------

solution:

implement new class inherits from IFilterFactory and inject service for my global action filter inside.

public class AuthorizationFilterFactory : IFilterFactory

    {

        public bool IsReusable => false;


        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)

        {

            // manually find and inject necessary dependencies.

            var context = (IUserAuthorizationService)serviceProvider.GetService(typeof(IUserAuthorizationService));

            return new GlobalActionFilter(context);

        }

    }

}

then Edit startup configuration for as follow

  services.AddControllers(configure =>

            {

                AuditConfiguration.ConfigureAudit(services, Configuration);

                AuditConfiguration.AddAudit(configure);


                //configure.Filters.Add(new GlobalActionFilter());

                configure.Filters.Add(new AuthorizationFilterFactory());

            });


Tuesday, November 1, 2022

check sql server database for bulk data exist or not

 problem:

i have role with multiple policies and every policy have multiple permissions relates.

so i need to validate end user to insert new role with restriction to prevent repeate roles with the same policies and permissions.

solution:

create stored procedure for sql database to check if role (policies and related permissions) exists befor 

if exist the procedure will return the name for rule and application will show error message that the role is with the same permissions exists before you can use it.


1- create user defined type to pass to procedure which will be passed from application and checked by procedure.

Create Type RolePermissionType 

as Table (

policyid int,

TenantId int,

PermissionId int

)

------------------------------------------------------------------------------------------------------------------- 

2-create the procedure based on input with type RolePermissionType.

 

Create Procedure [dbo].[sp_Check_RoleExist](@Mypermission RolePermissionType readonly  , @RoleNameOut nvarchar(200) OUTPUT) as 

begin

declare @itemsCount int =(select count(*) from @Mypermission);

declare @QueryCount int ;

declare @RoleId int;

declare @RoleName nvarchar(200)

PRINT '@itemsCount = ' + CONVERT(varchar(10), @itemsCount)


DECLARE db_cursor CURSOR FOR 

SELECT roleId ,a.Name

FROM [PolicyServerDb].[dbo].[PermissionAssignments] ps

inner join [PolicyServerDb].dbo.Roles a on a.id  =ps.RoleId and a.PolicyId=32

group by RoleId ,Name

having count(roleId) =@itemsCount


OPEN db_cursor  

FETCH NEXT FROM db_cursor INTO @RoleId ,@RoleName


WHILE @@FETCH_STATUS = 0  

BEGIN

set @QueryCount =(

select count(*) from

(

     select  PolicyId,TenantId,PermissionId from [PolicyServerDb].[dbo].[PermissionAssignments]

where RoleId=@RoleId

  intersect select PolicyId,TenantId,PermissionId from @Mypermission

)as x )

if(@QueryCount = @itemsCount)

set @RoleNameOut = @RoleName

else

set @RoleNameOut=''


FETCH NEXT FROM db_cursor INTO @RoleId ,@RoleName

END 

CLOSE db_cursor  

DEALLOCATE db_cursor 

end

-------------------------------------------------------------------

3-C# function which returns rule name in case roleExists

   public string GetRoleNameByPermissionAssignments(PackageViewModel model)

        {

            string rolenameout = string.Empty;

            DataTable dt = new();

            dt.Clear();

            _ = dt.Columns.Add("policyid");

            _ = dt.Columns.Add("TenantId");

            _ = dt.Columns.Add("PermissionId");

            foreach (PolicyPermissions item in model.PolicyPermissions)

            {

                foreach (SimplePermission permission in item.permissions)

                {

                    _ = dt.Rows.Add(item.PolicyId, model.TenantId, permission.PermissionId);

                }

            }

            using (PolicyServerDbContext context = new())

            {

                SqlParameter Par1 = new("@Mypermission", dt)

                {

                    TypeName = "dbo.RolePermissionType",

                    Direction = ParameterDirection.Input

                };

                SqlParameter Par2 = new("@RoleNameOut", rolenameout)

                {

                    SqlDbType = SqlDbType.NVarChar,

                    Size = 200,

                    Direction = ParameterDirection.Output

                };

                _ = context.Database.ExecuteSqlRaw("exec dbo.sp_Check_RoleExist @Mypermission={0}, @RoleNameOut={1} out", Par1, Par2);

                if (Par2.Value != DBNull.Value)

                {

                    rolenameout = (string)Par2.Value;

                }

            }

            return rolenameout;

        }

if return empty string this meaning that role with passed permissions not exists.

DTO Passed To Function:

 public class PackageViewModel

    {

            public int RoleId { get; set; }

            public string RoleName { get; set; }

            public string PolicyId { get; set; }

            public string Tenant { get; set; }

            public string TenantId { get; set; }

            public string TenantProtected { get; set; }

            public string Description { get; set; }

            public bool AssignForChildTenant { get; set; }

            public int SelectedPolicyId { get; set; }

            public List<PolicyPermissions> PolicyPermissions { get; set; }

    }

 public class PolicyPermissions

    {

        public int PolicyId { get; set; }

        public int ParentId { get; set; }

        public string PolicyName { get; set; }

        public List<SimplePermission> permissions { get; set; }

    }

    public class SimplePermission {

        public int PermissionId { get; set; }

        public string PermissionName { get; set; }

    } 


Git Update Local Repositories.bat get remote branches to visual studio

  to update local repositories for Git Branches

create batch file in solution root folder then run the following command.

git remote update origin --prune

Tuesday, September 18, 2018

PLSQL CONCAT multiple rows in one string


     
       select CONCAT(REPLACE(listagg( ENTITY_NAME, chr(300)||'(') within group( order by NAME_TYPE_FLG DESC),',',' ')  ,')')AS X
 FROM  CISADM.CI_PER_NAME PN
            WHERE PN.PER_ID ='2252300000'
           AND  PN.NAME_TYPE_FLG IN(   'ALT' , 'PRIM')


output

another solution

SELECT wm_concat('('||ENTITY_NAME||')') 
 FROM
        (   SELECT PER_ID, PN.ENTITY_NAME
            FROM  CISADM.CI_PER_NAME PN
            WHERE PN.PER_ID ='2252300000'
           AND  PN.NAME_TYPE_FLG IN(   'ALT' , 'PRIM')
           ORDER BY PN.NAME_TYPE_FLG DESC
       )
       GROUP BY PER_ID ;


Tuesday, September 4, 2018

Oracle case when based on numeric check for varchar2 column and select based on range of integers

SELECT
 case
        when SUBSTR( CAST(PGEO.GEO_VAL AS NUMBER) , 1,3) <=199 then  'شرق المدينة'
        when  SUBSTR( CAST(PGEO.GEO_VAL AS NUMBER), 1,3) <=299 THEN   'شمال المدينة'
        when  SUBSTR( CAST(PGEO.GEO_VAL AS NUMBER), 1,3) <=399 then   'غرب المدينة'
        when  SUBSTR( CAST(PGEO.GEO_VAL AS NUMBER), 1,3) <= 499 then  'جنوب المدينة'
        when  SUBSTR( CAST(PGEO.GEO_VAL AS NUMBER), 1,3) <= 599 then 'وسط المدينة'
        else 'other'
     end AS GEO_VAL  ,COUNT(SA.SA_ID) AS ACCT_CNT
 FROM CISADM.CI_SA SA
INNER JOIN  CISADM.CI_PREM PREM ON PREM.PREM_ID = SA.CHAR_PREM_ID
INNER  JOIN CISADM.CI_PREM_GEO PGEO ON PGEO.PREM_ID = PREM.PREM_ID AND PGEO.GEO_TYPE_CD ='9405'--'9401'
 WHERE SA.CIS_DIVISION ='4501'
 AND SA.SA_STATUS_FLG  IN ('20')
 AND SA.SA_TYPE_CD IN ('184015','184012','184013')
 group by case
        when  SUBSTR( CAST(GEO_VAL AS NUMBER), 1,3) <=199 then  'شرق المدينة'
        when  SUBSTR( CAST(GEO_VAL AS NUMBER), 1,3)<= 299 then 'شمال المدينة'
        when  SUBSTR( CAST(GEO_VAL AS NUMBER), 1,3)<= 399 then   'غرب المدينة'
        when  SUBSTR( CAST(GEO_VAL AS NUMBER), 1,3) <= 499 then 'جنوب المدينة'
        when  SUBSTR( CAST(GEO_VAL AS NUMBER), 1,3) <= 599 then 'وسط المدينة'
        else 'other'
        end
        order by geo_val asc;
-------------------------------------------
result

 

Sunday, February 4, 2018

close bootstrap modal from iframe page when click on button

 

 Problem: i have button in Modal Page (using iframe to load another page inside)
i need to click on close button in child page to close the modal and refresh data in parent page
1- button code

     <asp:Button CssClass="btn btn-info m-bot15 closeStyle" runat="server" ID="btnReturnToMyTasks" Text="اغلاق الشاشة"  
         Width="150px" CausesValidation="False" meta:resourcekey="btnReturnToMyTasksResource1" OnClientClick='window.parent.$("#modal").modal("hide"); parent.refreshData(true);'/>  
------------------------------------
2- parent page script to refresh data when click on X button or when press on previous button from child page inside iframe

 
//////////////////////////////////////////////////////////////////////////////////// refresh data after modal close  
       $(window).bind("load", function () {  
         $(".closeStyle").click(function () {  
           refreshData(true);  
         });  
       });  
       function refreshData(args) {  
         try {  
           if (args) {  
             var masterTable = $find("<%= RadGrid1.ClientID %>").get_masterTableView();  
          masterTable.fireCommand("RebindGrid", "0");  
        }  
         else  
          return false;  
      }  
      catch (e) {  
        //do nothing  
      }  
       }  
       ////////////////////////////////////////////////////////////////////////////////////////////////////////////////


----------------------------------------------------------------------------------
Modal Html (inside master or parent page)

<!-- Modal -->  
     <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel2" aria-hidden="true">  
       <div class="modal-dialog">  
         <div class="modal-content">  
           <div class="modal-header">  
             <!--onclick="alert('now in close'); window.location.reload();"-->  
             <button type="button" class="close closeStyle" data-dismiss="modal" aria-hidden="true" id="btnclose">&times;</button>  
             <h4 class="modal-title" id="myModalLabel2"></h4>  
           </div>  
           <div class="modal-body">  
             <iframe src="#" id="iframepopup" style="background-color: white;"></iframe>  
           </div>  
           <div class="modal-footer">  
             <button type="button" class="btn btn-primary closeStyle" data-dismiss="modal" id="Button1">اغلاق الشاشة</button>  
           </div>  
         </div>  
       </div>  
     </div>  
       
     -----------------------------------------------------------------------------------------
script to create modal height according to screen height

<script type="text/javascript">  
      $(document).ready(function () {  
        $('#modal').on('show.bs.modal', function () {  
          $('.modal-content').css('height', $(window).height() * 0.9);  
          $('.modal-body iframe').css('height', $(window).height() * 0.75);  
        });  
      });  
     </script>  

                    

Sunday, January 7, 2018

linked server Sql server OpenQuery by parameter example


DECLARE @SUBNAME NVARCHAR(100) ='محبوبه محمد  الشنقيطي'
DECLARE @SUBNO AS VARCHAR(100)='61319056000'

EXEC ('SELECT *  from CISWEB.CM_PER_NATIONAL_IQAMA_VW
WHERE  subnum = ?',  @SUBNO) AT [SAFALS];


---------------------------------------------------------------------------------------------------

COMPLETE EXAMPLE

ALTER PROCEDURE [dbo].[SAFA_GET_ACC_ID_BY_FILENO]
(
-- Add the parameters for the function here
@FILENO VARCHAR(10) ,
@ACCT_ID BIGint Output
)
AS

BEGIN
DECLARE @tmptable table (ACCT_ID VARCHAR(15))
--DECLARE @ACCT_ID VARCHAR(15) = '0'

insert into @tmptable
EXEC ('SELECT ACCT_ID  from CISADM.CI_ACCT_CHAR
WHERE  CHAR_TYPE_CD=''43036'' AND  ADHOC_CHAR_VAL = ?',  @FILENO) AT [SAFALS];

select @ACCT_ID = ACCT_ID from @tmptable
RETURN 

END



-------------------------------------------------------
CALL PROCEDURE


DECLARE @ACCT_ID bigint

EXEC [dbo].[SAFA_GET_ACC_ID_BY_FILENO]
@FILENO = N'80387',
@ACCT_ID = @ACCT_ID OUTPUT

SELECT @ACCT_ID as N'@ACCT_ID'

--SELECT 'Return Value' = @return_value

GO

Monday, August 21, 2017

sql server get time if the field contains today date else select date with out time format in datetime field

Problem :

i need to get time for message if it sent today else i  need to get the date of message with out time.

query :
select case when cast([CreateDate] as date) = cast(GETDATE() as date)
            then CONVERT(varchar(15),CAST([CreateDate] AS TIME),100)
            else CONVERT(varchar(15),CAST([CreateDate] AS date),100)
      end
from [MOAKPIS].[dbo].[Notifications];


output

Wednesday, August 9, 2017

SQL server Functions Library to execute general Purpose functions

-- Compute average value to two decimal values and avoid divide by zero error

Create FUNCTION [dbo].[getPercent]
(
       -- Add the parameters for the function here
       @valueToCompute decimal,
       @TotalValue  decimal
)
RETURNS  numeric(10,2)
AS
BEGIN
Declare @result numeric(10,2);
if (@valueToCompute =0 or @TotalValue = 0)
begin
set @result = 0.00
end
else
begin
set @result =CAST(@valueToCompute *100 /@TotalValue AS numeric(10,2))
end

 return @result
       END

-----------------------------------------------------------------------------------------------------------------------------------------------------------
--Function to convert comma separated list to integer table values to select from it
-- call example SELECT * FROM fnNTextToIntTable ('150,220,560,950')
Create FUNCTION [dbo].[fnNTextToIntTable] (@Data NTEXT)
RETURNS
    @IntTable TABLE ([Value] INT NULL)
AS
BEGIN
    DECLARE @Ptr int, @Length int, @v nchar, @vv nvarchar(10)

    SELECT @Length = (DATALENGTH(@Data) / 2) + 1, @Ptr = 1

    WHILE (@Ptr < @Length)
    BEGIN
        SET @v = SUBSTRING(@Data, @Ptr, 1)

        IF @v = ','
        BEGIN
            INSERT INTO @IntTable (Value) VALUES (CAST(@vv AS int))
            SET @vv = NULL
        END
        ELSE
        BEGIN
            SET @vv = ISNULL(@vv, '') + @v
        END

        SET @Ptr = @Ptr + 1
    END

    -- If the last number was not followed by a comma, add it to the result set
    IF @vv IS NOT NULL
        INSERT INTO @IntTable (Value) VALUES (CAST(@vv AS int))

    RETURN
END
---------------------------------------------------------------------------------------------------------------------------------------
-- =============================================
-- the function get weed end days count for period between start date and end date ( friday and saturday are days of weekend in my case )
/*Call Example

SELECT [dbo].[weekEndDaysCount] (
   '2016-01-01'
  ,'2016-01-30')
GO
*/
-- =============================================
CREATE FUNCTION [dbo].[weekEndDaysCount]
(
       -- Add the parameters for the function here
       @StartDate date,
       @EndDate date
)
RETURNS int
AS

BEGIN
DECLARE @WDCount int      
;WITH cteSequence (SeqNo) as
(
      SELECT 1  UNION ALL SELECT SeqNo + 1
      FROM cteSequence
      WHERE SeqNo < DATEDIFF(DD, @StartDate, @EndDate)+1
)

SELECT @WDCount = count(* )
FROM   (SELECT TOP ( datediff(DAY,@StartDate,@EndDate) + 1 )
                        [Date] = dateadd(DAY,ROW_NUMBER()
                  OVER(ORDER BY c1.SeqNo),
                  DATEADD(DD,-1,@StartDate))
        FROM   cteSequence c1 ) x
WHERE  datepart(dw,[Date]) in(5,6)
OPTION ( MAXRECURSION 0);
       RETURN @WDCount

END

GO
----------------------------------------------------------------------------------------------------------------------------------------------------------------------

-- =============================================
-- the function used to get working days count in period passed to the function start and end dates ( weekend days in my case is Friday and saturday)
/*
calling example :
SELECT [dbo].[WorkingDaysGetCount] (
   '2016-01-01'
  ,'2016-01-30')
GO
*/
-- =============================================
CREATE FUNCTION [dbo].[WorkingDaysGetCount]
(
       -- Add the parameters for the function here
       @StartDate date,
       @EndDate date
)
RETURNS int
AS

BEGIN
DECLARE @WDCount int      

SELECT @WDCount=
   (DATEDIFF(dd, @StartDate, @EndDate) + 1)
  -(DATEDIFF(wk, @StartDate, @EndDate) * 2)
  -(CASE WHEN DATENAME(dw, @StartDate) = 'Saturday' THEN 1 ELSE 0 END)
  -(CASE WHEN DATENAME(dw, @EndDate) = 'Friday' THEN 1 ELSE 0 END)
      
      
       RETURN @WDCount

END
---------------------------------------------------------------------------------------------------------------------------------------------------
-- =============================================
-- Author:           احتساب وقت ارسال التنبيهات بالدقائق والساعات والأيام لإظهارها للمستخدم
-- Create date:
-- Description:     
-- =============================================
Create FUNCTION [dbo].[ElapsedTimeCalculate]
(
       -- Add the parameters for the function here
       @ToConvetDateTime DateTime
)
RETURNS nvarchar(50)
AS

BEGIN
Declare
@ReturnElapsedTime nvarchar(50),
  @CurrDate datetime = getdate() ,
@tempHours int,
@tempMinutes int,
@tempDays int


       select
        @tempDays= DATEDIFF(DD, @ToConvetDateTime, @CurrDate) ,
        @tempHours= DATEDIFF(hh, @ToConvetDateTime, @CurrDate) ,
   @tempMinutes= DATEDIFF(mi,DATEADD(hh,DATEDIFF(hh, @ToConvetDateTime, @CurrDate),@ToConvetDateTime),@CurrDate)
   
       if(@tempDays>0)
 set @ReturnElapsedTime= N'منذ '+ convert(nvarchar,@tempDays)+N' يوم سابق '   
 else
 if(@tempHours>1)
 set @ReturnElapsedTime= N'منذ '+ convert(nvarchar,@tempHours)+N' ساعة سابقة ' 
 else
 if(@tempMinutes >2)
 set @ReturnElapsedTime= N'منذ '+ convert(nvarchar,@tempMinutes)+N' دقيقة سابقة '
 else
 begin
 set @ReturnElapsedTime= N'مرسل الآن  '   
 end

 return  @ReturnElapsedTime 
       END



 -------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------