Range defined by SQL user

Asked

Viewed 229 times

0

In sql there is some way to define the range of a query according to the user’s past ?

Example

Number of days the user enters for 7, and set as registration date day 07/01/2018, the bank return the registration made on 07/01/2018 a 13/01/2018, ?

  • first you have to inform which bank you are using, and yes, it is possible to do this

1 answer

0


Yes, there are many ways! How you attached the SQL tag, deduce that you are using T-SQL to write your queries.

Then analyzing the question with proposed example I came to...

SELECT nomeDaColuna(s)
FROM nomeDaTabela
WHERE ColunaQueContemData 
BETWEEN DataInicial AND CAST(DATEADD(day, 7, DataInicial) AS DATE)
GO 

I even made sure to elaborate an example similar to yours to show that it works: inserir a descrição da imagem aqui

Script Used:

CREATE TABLE [dbo].[Vendas](
    [ID] INT IDENTITY PRIMARY KEY NOT NULL,
    [Data] DATE DEFAULT GETDATE(),
    [Valor] MONEY
)
GO


INSERT INTO [dbo].[Vendas]([Valor]) VALUES(12.55)
GO
INSERT INTO [dbo].[Vendas]([Data], [Valor]) VALUES(DATEADD(day, 2, GETDATE()), 15.99)
GO
INSERT INTO [dbo].[Vendas]([Data], [Valor]) VALUES(DATEADD(day, 4, GETDATE()), 21.15)
GO
INSERT INTO [dbo].[Vendas]([Data], [Valor]) VALUES(DATEADD(day, 6, GETDATE()), 85.00)
GO
INSERT INTO [dbo].[Vendas]([Data], [Valor]) VALUES(DATEADD(day, 7, GETDATE()), 17.99)
GO
INSERT INTO [dbo].[Vendas]([Data], [Valor]) VALUES(DATEADD(day, 8, GETDATE()), 20)
GO


SELECT * FROM [dbo].[Vendas]
GO


SELECT * FROM [dbo].[Vendas] 
WHERE [Data]
BETWEEN GETDATE()
AND CAST(DATEADD(day, 6, GETDATE()) AS DATE)
GO

I used the native T-SQL function:

  • GETDATE() - Returns the current date.
  • DATAADD(intervalo da data, quantidade, data que sofre operação) - Returns a date after undergoing an operation. The date range represents which part of the date will undergo the operation (day, Month, year - for date). The quantity attribute represents the amount of day, month or year you want to ADD (Positive Numbers) and Subtract (Negative Numbers).
  • CAST() - used to convert DATETIME to DATE. I hope I helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.