Monday, September 23, 2013

SQL Server: Passing range of date in where condition

I am answering the question asked by sudhanshu mishra here on MSDN SQL forum.


Question-
i want to get the detail of all the transaction performed on an particular account of a bank. now i want to give the range of dates for which i can view the transactions on account?how can i achieve this task... please show me an example?
thanks!!

Answer:
I have placed the sample script for your query on my blog as I was unable to post on forum may be due to some security issue in my network or my browser was behaving correctly.
I assume below script will work for you.

Create Table #tempAccountTransDetail
(AccountNum INT, TransDate DATETIME, TransAmmount Decimal(11,2), TransType CHAR(1))

INSERT into #tempAccountTransDetail (AccountNum, TransDate, TransAmmount, TransType) VALUES (1001, '2013-08-23 19:22:07.923', 500.00, 'D')
INSERT into #tempAccountTransDetail (AccountNum, TransDate, TransAmmount, TransType) VALUES (1001, '2013-08-30 19:22:07.923', 25.00, 'C')
INSERT into #tempAccountTransDetail (AccountNum, TransDate, TransAmmount, TransType) VALUES (1001, '2013-09-10 19:22:07.923', 2500.00, 'D')
INSERT into #tempAccountTransDetail (AccountNum, TransDate, TransAmmount, TransType) VALUES (1001, '2013-09-20 19:22:07.923', 1500.00, 'C')
INSERT into #tempAccountTransDetail (AccountNum, TransDate, TransAmmount, TransType) VALUES (1001, '2013-09-23 19:22:07.923', 100.00, 'D')

INSERT into #tempAccountTransDetail (AccountNum, TransDate, TransAmmount, TransType) VALUES (1002, '2013-08-23 19:22:07.923', 1500.00, 'D')
INSERT into #tempAccountTransDetail (AccountNum, TransDate, TransAmmount, TransType) VALUES (1002, '2013-08-30 19:22:07.923', 700.00, 'C')
INSERT into #tempAccountTransDetail (AccountNum, TransDate, TransAmmount, TransType) VALUES (1002, '2013-09-10 19:22:07.923', 250.00, 'C')
INSERT into #tempAccountTransDetail (AccountNum, TransDate, TransAmmount, TransType) VALUES (1002, '2013-09-20 19:22:07.923', 500.00, 'D')
INSERT into #tempAccountTransDetail (AccountNum, TransDate, TransAmmount, TransType) VALUES (1002, '2013-09-23 19:22:07.923', 100.00, 'C')


DECLARE @AccountNum INT
SET @AccountNum = 1001
select * from #tempAccountTransDetail WHERE AccountNum = @AccountNum
      AND (TransDate between '2013-08-01' AND '2013-08-10' ) OR (TransDate between '2013-08-20' AND '2013-08-25' ) OR (TransDate between '2013-09-01' AND '2013-08-15' )

DROP TABLE #tempAccountTransDetail


Ashish. 


No comments:

Post a Comment