0

I have a SQL Server database with date representation name like below & each database contains table A (table A having column like id, datetime, value, value1 etc).

  • Jan2018
  • Feb2018
  • Mar2018 and so on..

My search condition is user selected date (eg. from 01-Jan-2018 to 01-Jun-2018) which I am passing to a stored procedure (max range 6 month). I want to generate dynamic query to get data from these database based on datetime passed.

How to achieve this functionality as I found difficult to implement.

3
  • Do you need also to check the Max Range (6 months)? Commented Dec 26, 2018 at 12:09
  • No. my input to store proc will take care. I will pass max 6 month range to SP. Commented Dec 26, 2018 at 12:10
  • If I didn't get this wrong, you should point out, that you have databases named like date representations. Not a column in table a with dates. Commented Dec 26, 2018 at 12:14

3 Answers 3

1

Can you try this query

CREATE PROCEDURE Myproc @FromDate DATE, 
                        @ToDate   DATE 
AS 
  BEGIN 
      DECLARE @SQL      NVARCHAR(max)='', 
              @unionall VARCHAR(10)='' 

      WITH cte 
           AS (SELECT @FromDate dt, 
                      1         mont 
               UNION ALL 
               SELECT Dateadd(month, 1, dt) dt, 
                      mont + 1              mont 
               FROM   cte 
               WHERE  mont < Datediff(month, @FromDate, @ToDate) 

              ) 
      SELECT @SQL += @unionall + '
                         select * from [' 
                     + LEFT (CONVERT(VARCHAR, Datename (month, dt )), 3) 
                     + CONVERT (VARCHAR, Year (dt)) 
                     + '].[dbo].[tablename]', 
             @unionall = ' union all ' 
      FROM   cte 

      PRINT @SQL 

      EXECUTE( @SQL) 
  END 
Sign up to request clarification or add additional context in comments.

1 Comment

with slide modification it's working. Great work @Anson
0

You should query sys.databases to find a database you need. Then, as you can only use static declarations of databases, you should create a textual select statement and execute it.

I tried it on my dbs and it worked. This is my code:

declare  @date varchar(20) = '2018'

declare @dbName varchar(20)
declare @sSql varchar(200)
declare @sConditions varchar(20) = ''

Set @dbName = (SELECT name FROM master.sys.databases
where name like '%' + @date + '%')

print @dbName

Select @sSql = 'Select * From ' + @dbName + '.dbo.MyDB '
--+ ' Where ' + @sConditions

Execute (@sSql)

if you need to query all that fit year. do like this:

declare  @date varchar(20) = 'a' 
SELECT name Into #dbnames
FROM master.sys.databases
where name like '%' + @date + '%'  

this brings a table of all sutable dbs. then query each one of them using loop. like cursor

4 Comments

I am getting error Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.. I run it on sql server 2008 on 'master' database. This is error at set @dbName = line
i guess you just should give more conditions for db name. you said its like feb2018 or sep2018. try search for month as well
SELECT @dbName= name FROM master.sys.databases where name like '%' + @date + '%' is working now. But its only retrieving 1 records. If I have multiple database with name 2018 its only retrieving single records.
i thought you need to query one specific db.
0

Are you looking for

CREATE PROCEDURE MyProc
  @FromDate DATE,
  @ToDate DATE,
  @Target SysName
AS
BEGIN
  DECLARE @SQL NVARCHAR(MAX)= N'SELECT * FROM [' +
    @Target +
    '] WHERE [Dates] >= @FromDate AND [Dates] <= @ToDate';

  EXECUTE sp_executesql @SQL,
                        N'@FromDate DATE, @ToDate DATE',
                        @FromDate,
                        @ToDate;

END

Demo

As I now understand what you are trying to do, you can

CREATE PROCEDURE ProcName
  @FromDate DATE,
  @ToDate DATE
AS
BEGIN
  --Declare a variable to hold the Dynamic SQL
  DECLARE @SQL NVARCHAR(MAX) = N'';
  --Generate the databases names
  WITH CTE AS
  (
    SELECT @FromDate D,
           1 N
    UNION ALL
    SELECT DATEADD(Month, N, @FromDate),
           N + 1
    FROM CTE
    WHERE N <= DATEDIFF(Month, @FromDate, @ToDate)
  )
  --Build the SELECT statement
  SELECT @SQL = @SQL+
                N'SELECT * FROM ['+
                CONVERT(VARCHAR(3), D, 100)+
                CAST(YEAR(D) AS VARCHAR(4))+
                '].dbo.TableName UNION ALL ' --Or UNION as you want
  FROM CTE;
  --Remove the last UNION ALL
  SET @SQL = LEFT(@SQL, LEN(@SQL) - 10); --If UNION then just -6
  --Execute the statement
  EXECUTE sp_executesql @SQL;
END

2 Comments

Thanks for your effort @sami. What should be pass to Target param ? can you please show it with example.
@JSushil Check the demo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.