/* ------------------------ My Meta Content Here SEO ------------------------ */

Pages

Main Menu

Sunday, September 29, 2019

GIT Commands

Important GIT Commands:

npm config --global set proxy http://yogesh.upreti@gmail.com@23.90.64.10:8080
npm config --global set proxy http://yogesh.upreti@gmail.com:10080

git config --global http.proxy http://yogesh.upreti@gmail.com@proxy.domain.com:10080
git config --global http.proxy http://yogesh.upreti@gmail.com@23.90.64.10:8080

http://dev.azure.com/YOUR_PROJECT_PATH
Step 1: Pull the updated data before commit
git pull

Step 2: Add the changes made by you
git add .

Step 3: Commit the changes with the detailed comment whatever you have done if single file then use "-m"
while if you have made changes in multiple files then use -F
git commit -m "Changes comment"

For multiple comment first create a text file where you want
git commit -F "Changes comment" 

To log your commit changes comments. Like this given below
git commit -F "../CommitDetails.txt"

Step 4: Finally push the changes that are made by you using:
git push

Check Status: Like 'Your branch is up to date with 'origin/master'.'
git status 

Check log: Checking log of the commit changes
git log

Changing the git remote origin url:

D:\Yogesh\Project\MY_PROJECT_PATH>git remote set-url origin https://dev.azure.com/YOUR_PROJECT_PATH/_git/YOUR_PROJECT_PATH.Web
Check the Remote Origin URL
git remote get-url --all origin

D:\Yogesh\Project\MY_PROJECT_PATH> git remote set-url origin https://dev.azure.com/MY_PROJECT_PATH_API/_git/MY_PROJECT_PATH_API.API


D:\Yogesh\Project\MY_PROJECT_PATH> git remote get-url origin https://dev.azure.com/MY_PROJECT_PATH_API/_git/MY_PROJECT_PATH_API.API
git push 

git stash

git reset --hard

Git Clone: Creating clone of project.
git clone -b DEV https://dev.azure.com/MY_PROJECT_PATH_API/_git/MY_PROJECT_PATH_API.API
Read More »

Using SQL Server Logging Exception in SQL table

Writing logs in SQL Server:

First create a table to log the system exceptions occurred:

CREATE TABLE [dbo].[tblExceptionLog]( 
[Id] [int] IDENTITY(1, 1) NOT NULL, 
[ErrorLine] [int] NULL, 
[ErrorMessage] [nvarchar](4000) NULL, 
[ErrorNumber] [int] NULL, 
[ErrorProcedure] [nvarchar](128) NULL, 
[ErrorSeverity] [int] NULL, 
[ErrorState] [int] NULL, 
[DateErrorRaised] [datetime] NULL 


Create a stored procedure: This procedure will insert the exception log in case of error will come

Create PROC [dbo].[uspGetErrorInfo]
AS
BEGIN
INSERT INTO tblExceptionLog( 
ErrorLine,
ErrorMessage,
ErrorNumber, 
ErrorProcedure,
ErrorSeverity,
ErrorState, 
DateErrorRaised 

SELECT 
ERROR_LINE () AS ErrorLine, 
Error_Message() AS ErrorMessage, 
Error_Number() AS ErrorNumber, 
Error_Procedure() AS 'Proc', 
Error_Severity() AS ErrorSeverity, 
Error_State() AS ErrorState, 
GETDATE () AS DateErrorRaised
END 
GO

Use the following approach to log the exception:

BEGIN TRY
BEGIN TRAN
--SQL Statements
COMMIT TRAN
END TRY
BEGIN CATCH
--Print 'Catching Exceptio Here'
IF @@TRANCOUNT > 0
ROLLBACK TRAN

EXEC dbo.uspGetErrorInfo  
END CATCH
Read More »

Using SQL Server list all the tables that are not in used since a long time Unused tables list

Create CTE for the unused tables: 

Which are the tables from the sys.all_objects and not in the sys.dm_db_index_usage_stats table.

WITH UnUsedTables (TableName , TotalRowCount, CreatedDate , LastModifiedDate )
AS (
  SELECT DBTable.name AS TableName
     ,PS.row_count AS TotalRowCount
     ,DBTable.create_date AS CreatedDate
     ,DBTable.modify_date AS LastModifiedDate
  FROM sys.all_objects  DBTable
     JOIN sys.dm_db_partition_stats PS ON OBJECT_NAME(PS.object_id)=DBTable.name
  WHERE DBTable.type ='U'
     AND NOT EXISTS (SELECT OBJECT_ID 
                     FROM sys.dm_db_index_usage_stats
                     WHERE OBJECT_ID = DBTable.object_id )
)
-- Select data from the CTE
SELECT TableName , TotalRowCount, CreatedDate , LastModifiedDate
FROM UnUsedTables
ORDER BY TotalRowCount ASC
Read More »

Using SQL Server Temporarily disabled all check constraints

Temporarily disabled all check constraints:

Classification for disable:

DECLARE @sql NVARCHAR(MAX) = N'';

;WITH x AS
(
  SELECT DISTINCT obj =
      QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.'
    + QUOTENAME(OBJECT_NAME(parent_object_id))
  FROM sys.foreign_keys
)
SELECT @sql += N'ALTER TABLE ' + obj + ' NOCHECK CONSTRAINT ALL;
' FROM x;

EXEC sp_executesql @sql;

For enabling again:

DECLARE @sql NVARCHAR(MAX) = N'';

;WITH x AS
(
  SELECT DISTINCT obj =
      QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.'
    + QUOTENAME(OBJECT_NAME(parent_object_id))
  FROM sys.foreign_keys
)
SELECT @sql += N'ALTER TABLE ' + obj + ' WITH CHECK CHECK CONSTRAINT ALL;
' FROM x;


EXEC sp_executesql @sql;
Read More »

Using SQL Server Validate Email ID OR Email Address

Different kind of input validation at SQL server level:

Check For Valid Email Id in SQL Server:

Declare @Email NVARCHAR(MAX) = 'yogesh.upreti14@yahoo.co.in'
IF @Email LIKE '%_@__%.__%' AND PATINDEX('%[^a-z,0-9,@,.,_,\-]%', @Email) = 0
BEGIN
----- Execute you Data manipulation operation here.
END


Read More »

Using SQL Server Remove Duplicate From A Table

Different strategies for removing duplicate records in SQL Server

Delete duplicate rows from a table example using temporary table:
BEGIN TRAN

--Pull distinct records in the temporary table

SELECT DISTINCT * INTO #T_TEMP FROM TableName

--Truncate the target table

TRUNCATE TABLE TableName

--Insert the distinct records from temporary table back to target table

INSERT INTO TableName SELECT * FROM #T_TEMP

--Drop the temporary table

IF OBJECT_ID('tempdb..#T_TEMP') IS NOT NULL
  DROP TABLE #T_TEMP
COMMIT TRAN

GO

SELECT * FROM TableName

Delete duplicate rows from a table example using CTE:

WITH cte AS (
    SELECT 
        contact_id, 
        first_name, 
        last_name, 
        email, 
        ROW_NUMBER() OVER (
            PARTITION BY 
                first_name, 
                last_name, 
                email
            ORDER BY 
                first_name, 
                last_name, 
                email
        ) row_num
     FROM 
        sales.contacts
)
DELETE FROM cte
WHERE row_num > 1;

Delete duplicate rows from a table Using correlated sub query:

--With correlated subquery

CREATE TABLE Employee
[ID] INT IDENTITY, 
[FirstName] Varchar(100), 
[LastName] Varchar(100), 
[Address] Varchar(100), 
GO 
INSERT INTO Employee([FirstName], [LastName], [Address]) 
VALUES ('Linda', 'Mitchel', 'America') 
INSERT INTO Employee([FirstName], [LastName], [Address]) 
VALUES ('Linda', 'Mitchel', 'America') 
INSERT INTO Employee([FirstName], [LastName], [Address]) 
VALUES ('John', 'Albert', 'Australia') 
INSERT INTO Employee([FirstName], [LastName], [Address]) 
VALUES ('John', 'Albert', 'Australia') 
INSERT INTO Employee([FirstName], [LastName], [Address]) 
VALUES ('John', 'Albert', 'Australia') 
INSERT INTO Employee([FirstName], [LastName], [Address]) 
VALUES ('Arshad', 'Ali', 'India') 
INSERT INTO Employee([FirstName], [LastName], [Address]) 
VALUES ('Arshad', 'Ali', 'India') 
INSERT INTO Employee([FirstName], [LastName], [Address]) 
VALUES ('Arshad', 'Ali', 'India') 
INSERT INTO Employee([FirstName], [LastName], [Address]) 
VALUES ('Arshad', 'Ali', 'India') 
GO 
SELECT * FROM Employee 
GO 
--Selecting distinct records 
SELECT * FROM Employee E1 
WHERE E1.ID = ( SELECT MAX(ID) FROM Employee E2 
WHERE E2.FirstName = E1.FirstName AND E1.LastName = E2.LastName 
AND E1.Address = E2.Address) 
GO 
--Deleting duplicates 
DELETE Employee 
WHERE ID < ( SELECT MAX(ID) FROM Employee E2 
WHERE E2.FirstName = Employee.FirstName AND E2.LastName = Employee.LastName 
AND E2.Address = Employee.Address) 
GO 
SELECT * FROM Employee 
GO    

Creating new table with distinct records and renaming it
New table with distinct only

BEGIN TRAN
-- Pull distinct records in a new table 
SELECT DISTINCT * INTO EmployeeNew 
FROM Employee 
--Drop the old target table 
DROP TABLE Employee 
--rename the new table 
EXEC sp_rename 'EmployeeNew', 'Employee' 
COMMIT TRAN
GO 
SELECT * FROM Employee 
GO

Using MERGE Statement

Beginning with SQL Server 2008, now you can use MERGE SQL COMMAND to perform INSERT/UPDATE/DELETE operations in a single statement. This new command is similar to the UPSERT (fusion of the words UPDATE and INSERT.) command of Oracle. It inserts rows that don't exist and updates the rows that do exist. With the introduction of the MERGE SQL command, developers can more effectively handle common data warehousing scenarios, like checking whether a row exists and then executing an insert or update or delete.

The MERGE statement basically merges data from a source result set to a target table based on a condition that you specify and if the data from the source already exists in the target or not. The new SQL command combines the sequence of conditional INSERT, UPDATE and DELETE commands in a single atomic statement, depending on the existence of a record. With this you can make sure no duplicate records are being inserted into the target table, but rather updated if there is any change and only new records are inserted which do not already exist in the target.
Read More »

Saturday, September 28, 2019

SQL important Hierarchy Queries

Common type expression for employee organisation hierarchy             

  ,OrgHierarchyLevel             
  As             
  (             
   SELECT Id, [Name], ParentID, LevelId FROM T_Organisation WHERE Id = @OrgId             
   UNION All             
   SELECT O.Id, O.[Name], O.ParentID, O.LevelId FROM T_Organisation O             
   INNER JOIN OrgHierarchyLevel OHL ON O.Id = OHL.ParentID             
  )           

Common type expression for employee organisation hierarchy sequence within one row using PIVOT Query:

DECLARE @OrgId INT = 100
;WITH OrgHierarchyLvl
As
(
SELECT
Id, Name, ParentID, LevelId
FROM
Organisation WHERE Id = @OrgId
UNION All
SELECT
ic.Id, ic.Name, ic.ParentID, ic.LevelId
FROM Organisation ic
INNER JOIN OrgHierarchyLvl cte ON ic.Id = cte.ParentID
)
,OrgSequence AS
(
SELECT @OrgId as OrgId,* FROM
(
SELECT LevelId,Name from OrgHierarchyLvl
) AS SourceTable
PIVOT(Max(Name) FOR [LevelId] IN ([1],[2],[3],[4],[5],[6],[7],[8])
) AS PivotTable
)
SELECT OrgId,[1] AS [Level 1 Org], [2] AS [Level 2 Org], [3] AS [Level 3 Org], [4] AS [Level 4 Org],
[5] AS [Level 5 Org], [6] AS [Level 6 Org], [7] AS [Level 7 Org], [8] AS [Level 8 Org]  FROM OrgSequence
Read More »

Using JSON in SQL server

Selecting data using JSON in sql server:

SELECT gid, email  FROM tempEmails FOR json auto 

Selecting Column Values From JSON Format in sql server:

For Example the below is the JSON format:

[{"gid":"0000036285","email":"tetsuya.ono@gmail.com,tetsuya.ono@gmail.com"},{"gid":"0000047244","email":"Miyuki.Yamamoto@gmail.com"}]
select JSON_Value(JSON_F52E2B61-18A1-11d1-B105-00805F49916B,'$.gid') as gid
JSON_Value(JSON_F52E2B61-18A1-11d1-B105-00805F49916B,'$.email') as email

;WITH CTE ([JSON_F52E2B61-18A1-11d1-B105-00805F49916B])
as
(
SELECT TOP 2 gid, email  FROM tempEmails FOR json auto
)
,CTE1 (JSONValue) AS
(
select [JSON_F52E2B61-18A1-11d1-B105-00805F49916B] JSONValue from cte
)
SELECT JSON_Value(JSONValue,'$[0].gid') as gid,
JSON_Value(JSONValue,'$[0].email') as email FROM CTE1
Read More »

Using SQL query Insert Data From CSV File in to the SQL server database

drop table #test1
CREATE TABLE #test1(
[GID] [nvarchar](MAX) NULL,
[Staff_Name] [nvarchar](MAX) NULL,
[E_mail_Address] [nvarchar](MAX) NULL,
[OrgLevel1] [nvarchar](MAX) NULL,
[OrgLevel2] [nvarchar](MAX) NULL,
[OrgLevel3] [nvarchar](MAX) NULL,
[OrgLevel4] [nvarchar](MAX) NULL,
[OrgLevel5] [nvarchar](MAX) NULL,
[OrgLevel6] [nvarchar](MAX) NULL,
[HeaOrDeputy] [nvarchar](MAX) NULL,
[RoleType] [nvarchar](MAX) NULL,
[OrgLevelId] [nvarchar] (MAX) NULL
)

--BULK INSERT #test1

--   FROM 'D:\Master.csv'

--BULK INSERT #test1
--FROM 'D:\Master.csv'
--WITH
--(
--    FIELDTERMINATOR = ' '           -- add this
--);


--BULK INSERT #test1
--FROM 'D:\Master.csv'
--WITH (
--FIELDTERMINATOR = ',',
--ROWTERMINATOR = '\n',
--ERRORFILE = 'D:\myRubbishData.log'
--);

--BULK
--INSERT #test1
-- FROM 'D:\tempApproverMst.txt'
--WITH
--(
-- FIRSTROW = 1,
-- FIELDTERMINATOR = ' ',
-- ROWTERMINATOR = '\n', --0x0a
-- Lastrow = 30000003
--)
--GO

INSERT INTO #test1 ([GID], [Staff_Name], [E_mail_Address], [PhoneN],OrgLevel1,OrgLevel2,OrgLevel3,OrgLevel4,OrgLevel5,OrgLevel6,HeaOrDeputy,OrgLevelId)
SELECT A.[GID], A.[Staff_Name], A.[E_mail_Address], A.[PhoneN],A.OrgLevel1,A.OrgLevel2,A.OrgLevel3,A.OrgLevel4,A.OrgLevel5,A.OrgLevel6,A.HeaOrDeputy,A.OrgLevelId
FROM OPENROWSET ('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0; Database=D:\Master.csv', 'select * from [TableName]') AS A;

SELECT * FROM #test1
Read More »

Friday, September 27, 2019

Capitalize only the first letter of each word of each sentence in SQL Server

BEGIN TRAN UPDATE T_MST_Skills SET Name =  stuff((select ' '+upper(left(T3.V, 1))+lower(stuff(T3.V, 1, 1, ''))
       from (select cast(replace((select Name as '*' for xml path('')), ' ', '') as xml).query('.')) as T1(X)
         cross apply T1.X.nodes('text()') as T2(X)
         cross apply (select T2.X.value('.', 'varchar(1000)')) as T3(V)
       for xml path(''), type
       ).value('text()[1]', 'varchar(1000)'), 1, 1, '') from T_MST_Skills where [Name] not like '%(%' and [Name] not like '%.%';

Rollback:

select Name,stuff((
       select ' '+upper(left(T3.V, 1))+lower(stuff(T3.V, 1, 1, ''))
       from (select cast(replace((select Name as '*' for xml path('')), ' ', '') as xml).query('.')) as T1(X)
         cross apply T1.X.nodes('text()') as T2(X)
         cross apply (select T2.X.value('.', 'varchar(1000)')) as T3(V)
       for xml path(''), type
       ).value('text()[1]', 'varchar(1000)'), 1, 1, '') as [Capitalize first letter only] from T_MST_Skills where [Name] not like '%(%' and [Name] not like '%.%';
Read More »

My Blog List