Showing posts with label SQL SERVER. Show all posts
Showing posts with label SQL SERVER. Show all posts

Common and Useful SQL Server Quries



-----------------Get List of All Databases (DB)--------------------
 EXEC sp_helpdb


-----------------Get procedure text ----------------------------------

exec sp_helptext @objname = 'BeneficiaryEnrolmentDataStatusSave'



---------------- Recompile stored procedure ---------------------

EXEC sp_recompile'BeneficiaryEnrolmentDataStatusSave';
 GO


----------------Recompile all stored procedure on table---------

 EXEC sp_recompile N'txncustomers';
GO


----------------Get all columns of a specific data type-----------

SELECT OBJECT_NAME(c.OBJECT_ID) as Table_Name, c.name as Column_Name FROM sys.columns AS c JOIN sys.types AS t ON c.user_type_id=t.user_type_id WHERE t.name = 'varchar'  --G



---------------Get all Nullable columns of a table----------------
SELECT OBJECT_NAME(c.OBJECT_ID) as Table_Name, c.name as Column_Name FROM sys.columns AS c JOIN sys.types AS t ON c.user_type_id=t.user_type_id WHERE c.is_nullable=0 AND OBJECT_NAME(c.OBJECT_ID)='txncustomers'


----------------Get All table that doesn’t have primary key--------------


SELECT name AS Table_Name FROM sys.tables WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasPrimaryKey') = 0 ORDER BY Table_Name;



---------------Get All table that don’t have foreign key------------------


SELECT name AS Table_Name FROM sys.tables WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasForeignKey') = 0 ORDER BY Table_Name;



----------------Get All table that don’t have identity column------------


SELECT name AS Table_Name FROM sys.tables WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasIdentity') = 0 ORDER BY Table_Name;



-----------------Get First Date of Current Month------------------------


SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE()))+1,GETDATE()),105) First_Date_Current_Month;



-----------------Get last date of previous month------------------------

SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE())),GETDATE()),105) Last_Date_Previous_Month;



-----------------Get last date of current month-------------------------

SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE())), DATEADD(MONTH,1,GETDATE())),105) Last_Date_Current_Month;




-----------------Get first date of next month----------------------------
SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE())), DATEADD(MONTH,1,GETDATE())+1),105) First_Date_Next_Month;




-- ---------------Get all tables that contain a view----------------------

SELECT * FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE





-----------------Get all columns of the table that using in views---------

SELECT * FROM INFORMATION_SCHEMA.VIEW_COLUMN_USAGE




 -----------------Get all stored procedure from Database----------------

SELECT DISTINCT o.name, o.xtype FROM syscomments c INNER JOIN sysobjects o ON c.id=o.id WHERE o.xtype='P'



 ---------------- Get all stored procedure from table---------------------

SELECT DISTINCT o.name, o.xtype FROM syscomments c INNER JOIN sysobjects o ON c.id=o.id WHERE c.TEXT LIKE '%txncustomers%' AND o.xtype='P'




 ---------------- View dependencies of stored procedure ----------------

;WITH stored_procedures AS ( SELECT oo.name AS table_name, ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
FROM sysdepends d INNER JOIN sysobjects o ON o.id=d.id INNER JOIN sysobjects oo ON oo.id=d.depid WHERE o.xtype = 'P' AND o.name LIKE '%BeneficiaryEnrolmentDataStatusSave%' ) SELECT Table_name FROM stored_procedures WHERE row = 1 



Generic Search procedure in SQL server

Create Procedure [dbo].[Proc_GenericSearch_CustomerOrders]

@CustomerId  int=null,  

@TransctionStatus int=null,

@FromDT datetime = null,

@ToDT datetime  = null,

@EmailID varchar(250)  = null,

@MobileNumber varchar(250)  = null

as

begin

select  a.CustomerID,a.CreatedDatetime,b.Insta_transaction_id,B.Insta_id,
b.Insta_payments_id,a.CreatedBy,a.EName,a.DateofBirth,a.MobileNo,
a.EmailID,b.CustomerOrderID,b.Insta_status,
c.OrderStatus,c.OrderDate,c.PaymentCategoryCode

from TxnCustomers a
inner join TxnPaymentOrderDetailsResponse b on a.CustomerID=b.CustomerID
LEFT join TxnCustomerOrders c on b.CustomerOrderID=c.CustomerOrderID

where
PaymentGateway='PAYTM' AND ReconciliationStatus not in(1)
AND
(ReconciliationStatus = @TransctionStatus OR @TransctionStatus IS NULL) --put every condition like this to handle Generic Search  where null parameter values are allowed
AND
(b.EntryDate >= @FromDT OR @FromDT IS NULL)

AND

(B.EntryDate<=@ToDT OR @ToDT IS NULL)

AND

(A.EmailID=@EmailID OR @EmailID IS NULL)

AND

(A.MobileNo=@MobileNumber OR @MobileNumber IS NULL)

end

Stored Procedure in SQL Server

A stored procedure is nothing more than prepared SQL Query that you save so you can reuse the Query over and over again. So if you think about a query that you write over and over again, instead of having to write that query each the time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure. Stored procedures are a batch of SQL statements that can be executed in a couple of ways. Most major DBMS support stored procedures; however, not all do. You will need to verify with your particular DBMS help documentation for specifics

A stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. A stored procedure will reduce network traffic and increase the performance

Advantages of stored procedures

  1. A stored procedure allows modular programming.
  2. A stored procedure allows for faster execution.
  3. A stored procedure can reduce network traffic.
  4. Stored procedures provide better security to your data

Example of the stored procedure :

Step 1-Create simple stored procedure in SQL server

create procedure proc_getAllData
as
begin
select * from temptable
end






Step 2-Execute stored procedure in SQL server


exec proc_getAllData



Note: If you want to delete the stored procedure then use drop command to drop the stored procedure


drop procedure proc_getAllData


Types of Stored Procedure

SQL Server we have different types of stored procedures:

  1. System stored procedures
  2. User-defined stored procedures
  3. Extended stored Procedures

System stored procedures

Stored procedures are stored in the master database and these start with a sp_ prefix. These procedures can be used to perform a variety of tasks to support SQL Server functions.

Example: sp_helptext [StoredProcedure_Name]
(To get the text of stored procedure )


User-defined stored procedures
User-defined stored procedures are usually stored in a user database and are typically designed to complete the tasks in the user database.



Extended stored Procedures

Extended stored procedures are the procedures that call functions from DLL files. Nowadays, extended stored procedures are depreciated for the reason it would be better to avoid using extended stored procedures.