Monday, July 1, 2019

How to get duplicate records




;WITH cte 
AS
(
SELECT DISTINCT d.company_fk, d.id,  d.name 
--, ROW_NUMBER() OVER(PARTITION by t.FName, t.LName ORDER BY t.FName, t.LName,  t.Sex DESC) AS duplicateRecCount
,COUNT(d.id) OVER (PARTITION BY  d.name, d.company_fk, d.[status] ) AS [max_count]
FROM tbl_department d
WHERE [status] =  'A'
) 

SELECT * FROM cte WHERE max_count > 1 
ORDER BY name

Few more commands and queries


---// This is to add new ndf file for any database in any particular location

ALTER DATABASE [TestDB]
ADD FILE
(
      NAME = TestDB_3,
      FILENAME = 'C:\Database\Data\TestDB_3.ndf'
)
TO FILEGROUP [SecondaryFG]
GO 

---//To make database clone with new database.

dbcc clonedatabase('Client_Dev',Client_Dev_Clone')
DBCC CLONEDATABASE (Client_Dev, Client_Dev_Clone) WITH NO_STATISTICS

---// How to check fragmentation percent to do indexing on DB tables. 

SELECT OBJECT_NAME(ips.OBJECT_ID)
 ,i.NAME
 ,ips.index_id
 ,index_type_desc
 ,avg_fragmentation_in_percent
 ,avg_page_space_used_in_percent
 ,page_count
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'SAMPLED') ips
INNER JOIN sys.indexes i ON (ips.object_id = i.object_id)
 AND (ips.index_id = i.index_id)
ORDER BY avg_fragmentation_in_percent DESC


---// After deleteing records from the table, to reseed the identity column value..

SELECT IDENT_CURRENT('TABLE_NAME')


DBCC CHECKIDENT ('TABLE_NAME', RESEED, 14);

---// Database Connection count 

select  db_name(dbid) , count(*) 'connections count'
from master..sysprocesses
where spid > 50 and spid != @@spid
group by  db_name(dbid)
order by count(*) desc

select  loginame , nt_username, count(*) 'Connections count'
from master..sysprocesses
where spid > 50 and spid != @@spid
group by  loginame , nt_username

order by count(*) desc

---// Find Table column level dependencies 

SELECT DISTINCT so.name FROM sysobjects so
INNER JOIN syscomments sc ON sc.id = so.id
WHERE  so.[type] = 'P'GetAgentPublisherSettings
AND so.[name] LIKE 'st_%'
AND sc.[text] LIKE '%tbl_company_basic%'
AND sc.[text] LIKE '%service_opted%'
ORDER BY so.name


SELECT DISTINCT object_name(so.id) TableName, sc.name ColumnName, OBJECT_NAME(sd.id) DependentObjectName,
(SELECT xtype FROM sysobjects so WHERE so.id = sd.id) Object_Type
FROM sysobjects so 
INNER JOIN syscolumns sc ON so.id = sc.id
INNER JOIN sysdepends sd ON so.id = sd.depid and sc.colid = sd.depnumber
WHERE object_name(so.id) = 'tbl_company_basic'
AND sc.name = 'service_opted'

order by object_name(so.id), Object_Type

Command line operations for SQL



1. Write this command in SSMS to fetch data from table and insert into the testing.xlsx in a given location.

insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=E:\testing.xlsx;', 'SELECT * FROM [Sheet1$]') select * from tbl_student

2. Write this command in command line to exporting data from table/view/query and insert into the any  file in a given location, it also called as  Bulk copy command.

Firstly you need to go to the below path to run BCP.exe command.


BCP Location for SQL Server 2012 – C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn
BCP Location for SQL Server 2014 – C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\120\Tools\Binn
BCP Location for SQL Server 2015 – C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn
BCP Location for SQL Server 2019 – C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn



Then RUN below BCP Command to Bulk copy.

bcp "SELECT id, name, description FROM tbl_student" queryout  E:\DBA\StudentTest.xls -S OMS-MEL-TEST -T -d db_student_Test -U on.user -P on.user -c

3. Write this command in command line to delete the unwanted files and folders from given path table and insert into the testing.xlsx i given location.

forfiles /p "E:\Data2\A1Files\V2" /s /d -872 /c "cmd /c del /s /q @file" 

4. Copy file from common folder to particular path by the help of batch file..

xcopy "\\10.100.0.707\scan\studentupdate\update\*.dll" "D:\Data\One\Enterprise\" /y

How to check uncommitted transaction in SQL Server

This is to see the uncommitted transaction and kill that transaction.

SELECT OBJECT_NAME(P.object_id) AS TableName, Resource_type, request_session_id 
FROM sys.dm_tran_locks L
INNER JOIN sys.partitions P ON L.resource_associated_entity_id = p.hobt_id

OR

DBCC OPENTRAN

commit transaction process_commission_upsert

kill 60

Tuesday, March 27, 2018

New features of SQL Server 2016 - Developers


New Features of SQL Server 2016

SQL Server 2016 – Part 1
Getting Started with Stretch Database Functionality in SQL Server 2016 - Part 2
Row Level Security with SQL Server 2016: Part 1 – Allow Access to Only a Subset of Rows Using Row Level Security
Row Level Security with SQL Server 2016: Part 2 - Blocking Updates at the Row Level
Altering an Existing Table to Support Temporal Data
Getting Started with JSON Support in SQL Server 2016 – Part 2
Getting Started with Temporal Table in SQL Server 2016 – Part 2
Getting Started with Temporal Table in SQL Server 2016 – Part 1
SQL Server 2016 internally creates a history table with the same schema as your current table when you don’t specify a name for the specific history table. 
If you already have an existing table that you want to use it as history table, you can specify its name during table creation or modification, 
however you need to ensure it has the same schema as the current table and it meets other requirements as discussed earlier.



CREATE TABLE Employee
(  
    [EmployeeID]   int NOT NULL PRIMARY KEY CLUSTERED 
  , [Name]    nvarchar(100) NOT NULL
  , [Position]     varchar(100) NOT NULL 
  , [Department]   varchar(100) NOT NULL
  , [AnnualSalary] decimal (10,2) NOT NULL
  , [ValidFrom] datetime2 (2) GENERATED ALWAYS AS ROW START
  , [ValidTo] datetime2 (2) GENERATED ALWAYS AS ROW END
  , PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
 )  
 WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmployeeHistory));

 INSERT INTO Employee ([EmployeeID], [Name], [Position], [Department], [AnnualSalary])
 VALUES 
  (8,'Hari','TA', 'IT', 45000)
 ,(2,'Manpreet','SE', 'IT', 25000)
 ,(3,'Sandy','SE', 'IT', 43000)
 ,(4,'Mandeep','TA', 'IT', 53000)
 ,(5,'Sandeep','TL', 'IT', 66000)
 ,(6,'Marlon','PM', 'IT', 79000)

 SELECT * FROM Employee
 SELECT * FROM EmployeeHistory

 UPDATE Employee
SET [AnnualSalary] = 53000
WHERE EmployeeID = 2
GO
UPDATE Employee
SET [Department] = 'TESTING'
WHERE EmployeeID = 8
DELETE FROM Employee WHERE EmployeeID = 3
GO


SELECT * FROM Employee
GO
SELECT * FROM EmployeeHistory
GO



/*
---//  If you wish to Drop newly created temporal table 

--// First disable the system versioning
ALTER TABLE dbo.Employee SET (SYSTEM_VERSIONING = OFF)
GO

--// Drop Period definition.
--// This will allow manipulations on the PERIOD columns

ALTER TABLE dbo.Employee
DROP PERIOD FOR SYSTEM_TIME
GO

--Now drop Employee and EmployeeHistory tables
--(To drop these tables, dropping PERIOD definition is optional)

DROP TABLE Employee
DROP TABLE EmployeeHistory
GO

*/

DECLARE @st AS VARCHAR(500) = '24,47,944,44,,99'
SELECT [value] FROM STRING_SPLIT ( @st , ',' )  

DECLARE @str1 VARCHAR(35) = 'ABCDEFGH'    
SELECT @str1, STUFF(@str1,4,5,'_STUFF')  

DECLARE @str VARCHAR(35) = 'ABCDEFGH'    
SELECT @str, REPLACE(@str,'DEFGH','_REPLACE') 

Monday, March 26, 2018

How to change datetime into time with AM/PM



How to change date time into time with AM/PM..

SELECT  LEFT(CONVERT(VARCHAR(20), CAST(CONVERT(VARCHAR,GETUTCDATE(),108) AS TIME)), 5) + ' '
+ RIGHT(CONVERT(VARCHAR(20), CAST(CONVERT(VARCHAR,GETUTCDATE(),108) AS TIME), 109), 2)

SELECT LEFT(CONVERT(VARCHAR(5), CAST(CONVERT(VARCHAR,GETUTCDATE(),108) AS TIME), 108),5) + ' '
+ RIGHT(CONVERT(VARCHAR(30),CAST(CONVERT(VARCHAR,GETUTCDATE(),108) AS TIME), 9),2)

you can use below FORMAT() in for higer version on SQL server.

DECLARE @dt AS DATETIME = GETDATE()
SELECT FORMAT(@dt, 'hh:mm tt')

DECLARE @t AS DATETIME = GETDATE()
SELECT FORMAT(CAST(@t AS DATETIME), 'hh:mm tt') 

Tuesday, September 22, 2015

How to get schema change history

SELECT s.name AS schema_name, o.name AS OBJECT_NAME, o.type_desc, o.create_date, o.modify_date
FROM   sys.all_objects o
LEFT OUTER JOIN sys.schemas s ON ( o.schema_id = s.schema_id)
WHERE create_date > ( GETDATE() - 7) 
AND o.name = 'st_school_admin_data_select'
ORDER BY o.name 


you can use in this way

DECLARE @dt AS DATETIME = GETDATE()
SELECT FORMAT(@dt, 'hh:mm tt')

DECLARE @t AS DATETIME = GETDATE()
SELECT FORMAT(CAST(@t AS DATETIME), 'hh:mm tt')