I want to select a database table between the range of the date selected from the datepicker on my web, my sample database table names are:
output_11FEB2016
output_13FEB2016
output_15FEB2016
output_21FEB2016
I want to select tables to show and show their contents on my web, here is my current codes from what I understand on my research.
ALTER PROCEDURE [dbo].[gen048_mLIST]
-- Add the parameters for the stored procedure here
#gfromDate varchar(10),
#gtoDate varchar(10)
AS
SET NOCOUNT ON
declare #sql varchar(5000)
set #sql='select * output_'
if(#gfromDate<>'' and #gtoDate<>'')
begin
set #sql=#sql+'between '+convert(datetime,'''+#gfromDate+''')+' and '+convert(datetime,'''+#gtoDate+''')+' '
--print #sql
exec(#sql)
-- [dbo].[gen048_mLIST] '2-16-2016','2-18-2016'
END
Sorry for my messed up codes and explanation, I appreciate those who can help me figure out my problem.
You will have to select the rows from multiple tables,UNION it and display it in your application.I've used hardcoded dates to generate the SQL but you can modify/extend this to suit your requirements.
declare #gfromDate varchar(10) = '11/02/2016'
declare #gtoDate varchar(10) = '24/02/2016'
declare #fromDate datetime
declare #toDate datetime
declare #totaldays int
set #fromDate = (select convert (date, #gfromDate, 104))
set #toDate = (select convert (date, #gtoDate, 104))
-- get total number of days between from and to dates
set #totaldays = (select datediff(day,#fromdate,#toDate))
declare #sql varchar(max) = ''
declare #tablename varchar(20)
declare #counter int = 1
-- generate the sql to get data from the tables within a date range
while #counter < #totaldays
begin
set #tablename = (select convert(varchar(11), #fromDate, 106))
set #tablename = replace(#tablename,' ','')
-- check if table exists
--if object_id(#tablename, 'U') is not null
--begin
set #sql = #sql + 'select * from output_' + #tablename
if(#counter < #totaldays-1)
begin
set #sql = #sql + ' union '
end
set #fromDate = dateadd(day,1,#fromDate)
set #counter = #counter + 1
--end
end
print #sql
SQL Generated
select * from output_11Feb2016 union
select * from output_12Feb2016 union
select * from output_13Feb2016 union
select * from output_14Feb2016 union
select * from output_15Feb2016 union
select * from output_16Feb2016 union
select * from output_17Feb2016 union
select * from output_18Feb2016 union
select * from output_19Feb2016 union
select * from output_20Feb2016 union
select * from output_21Feb2016 union
select * from output_22Feb2016
Related
I need to dynamically create X tables. The X is calculated on the fly based on a series of other calculations that get passed in. I've written the following dynamic code in an effort to create a loop and generate a create statement each time.
I can't use global tables for this project.
DECLARE #cnt_v varchar(10)
DECLARE #SQL NVARCHAR(max) = ''
DECLARE #season_counter int = 5
SET #cnt = 1
SET #cnt_v = CONVERT(varchar(10), #cnt)
WHILE #cnt <= #season_counter
BEGIN
select #SQL = #SQL + 'create table #Season_year' + #cnt_v + ' (customer_no int, order_no int, order_dt datetime, season_no int)'
exec sp_executesql #SQL
set #sql = ''
select #SQL = #SQL + 'select * from #Season_year' + #cnt_v
exec sp_executesql #SQL
select #cnt = #cnt + 1
select #cnt_v = CONVERT(varchar(10), #cnt)
select #sql = ''
END
The output of the above code is the following errors
When manually create the tables, by typing
create table #Season_year1 (customer_no int, order_no int, order_dt datetime, season_no int)'
then use my dynamic loop to insert data, update records and ultimately drop the temp tables everything works without an issue. The problem is solely creating the tables dynamically.
If this approach isn't going to work, how else could I do this?
Thank you
Each one of your dynamic sql statements is run within its own scope, so in the SELECT * FROM #Season_year5 has no idea what #Season_year5 is. In the first dynamic SQL statement it's created and destroyed all with the execution of sp_executesql. If you combine them both into a single dynamic SQL statement then you will be able to access the temp table in other statements.
DECLARE #cnt INT = 1;
DECLARE #cnt_v varchar(10)
DECLARE #SQL NVARCHAR(max) = ''
DECLARE #season_counter int = 5
SET #cnt = 1
SET #cnt_v = CONVERT(varchar(10), #cnt)
WHILE #cnt <= #season_counter
BEGIN
select #SQL = #SQL + N'create table #Season_year' + #cnt_v + N' (customer_no int, order_no int, order_dt datetime, season_no int);
select * from #Season_year' + #cnt_v + N';'
exec sp_executesql #SQL
select #cnt = #cnt + 1
select #cnt_v = CONVERT(varchar(10), #cnt)
select #sql = ''
END
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.
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
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
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
I have seen a couple solutions to this SQL error(8115) but none seems to work for me. I think its because I am using dynamic SQL script. I dynamically pull data from multiple servers that have the same structure and insert into a central table. The issue I have having is that when using dynamic script as seen below I keep getting an error.
DECLARE #SQL NVARCHAR(4000);
DECLARE #counter int = 0;
DECLARE #scriptcnt int;
declare #startdate varchar(8) = '20180304';-- cast(#startdate as date)
declare #enddate varchar(8) = '20180305';--cast(#enddate as date)
select srv.name
INTO #ServerNames
from sys.servers srv
where name like 'Pulse%'
order by 1;
select name,right(name,5) store_no
into #locationCode
from #SERVERNAMES;
With ServerCTE AS (
SELECT Root=NAME + '.[POS].[dbo].'
FROM #SERVERNAMES)
Select
Root + '[Customer]' as Customer
INTO #Tables
from ServerCTE
Begin Transaction
delete from WFLCustomerMaster
--where Location_Code = '16450'--#storeNum
commit;
select
'
Begin TRY
Begin Transaction
Insert into WFLCustomerMaster(.....)
SELECT .....
FROM '+ Customer + '
where [Last_Order_Date] between '+ #startdate+ ' and '+ #enddate+ ' [This line is the issue]
commit;
END TRY
BEGIN CATCH
SELECT
ERROR_PROCEDURE() as nameofprocedure,
ERROR_NUMBER() AS errorcode,
error_line() as errorline,
ERROR_MESSAGE() as errormessage
END CATCH' as Customer into #query
from #Tables a, #locationCode b
where left(a.Customer,13) = b.name
select #scriptcnt = count(*) from #query
while #counter < #scriptcnt
begin
set #counter = #counter + 1
SET #SQL = (SELECT Customer FROM
(SELECT ROW_NUMBER() OVER (ORDER BY Customer) AS ID, Customer FROM #query) MySQL
WHERE ID=#Counter )
EXEC SP_EXECUTESQL #SQL
end
I tried converting #startdate and #enddate to date, datetime and datetime2 but nothing works.
I realize that when I hard code the date it works as per below:
...'where [Last_Order_Date] between ''20180306'' and ''20180306'''....
So I know that this part is the issue. Can someone assist?
Guru's please help me with this.
I have a master table called ABC, each month we create new table and suffix with month and year ABC_012010, ABC_022010.
I have to keep these tables for 7 years, and delete any table which are more than 7 years.
So the job would delete ABC_012010 in Feb 2017, ABC_022010 would be deleted in March 2017 and so on
The job runs every month to check and delete any table, which fits the criteria.
TRY THIS: You need dynamic query, loop and temporary tables to perform this operation and your table format must be in the same format as you have mentioned in your example. You can perform INSERT, UPDATE, DELETE, DROP, TRUNCATE in this way in multiple tables:
--Selecting table name in date format with `LEFT` `RIGHT` function
SELECT name,
CAST(CONCAT(LEFT(RIGHT(name, 6), 2), '-01-', RIGHT(RIGHT(name, 6), 4)) AS DATE) AS tableDate,
CAST(GETDATE() AS DATE) AS currentDate
INTO #tmp_date
FROM sys.objects
WHERE TYPE = 'u' AND NAME LIKE 'ABC[_]%'
--Storing table names that are older than 7 years from current date
SELECT id = IDENTITY(INT, 1, 1),
NAME
INTO #object_name FROM #tmp_date
WHERE (DATEDIFF(MM,tableDate, currentDate)-1) > = 84
DECLARE #i INT = 1, #j INT, #sql VARCHAR(500), #object_name VARCHAR(100)
SELECT #j = MAX(id) FROM #object_name
WHILE #i < = #j
BEGIN
SELECT #object_name = NAME FROM #object_name WHERE id = #i
SET #sql = 'DELETE FROM ' + #object_name --can use `DROP` to drop the table
EXEC (#sql)
SET #i = #i+1
END
try the following:
IF OBJECT_ID('TEMPDB.DBO.#TEMP_DEL', 'U') IS NOT NULL
DROP TABLE #TEMP_DEL
DECLARE #CYMO VARCHAR(8) = (SELECT '01' + RIGHT(REPLACE(CONVERT(CHAR(10), DATEADD(YY, -7, GETDATE()), 103), '/', ''), 6))
SELECT [NAME] TABLE_NAME INTO #TEMP_DEL FROM DBNAME.SYS.TABLES
WHERE [NAME] LIKE 'ABC%' AND '01'+RIGHT(NAME,6) < #CYMO
WHILE ((SELECT COUNT(1) FROM #TEMP_DEL) > 0)
BEGIN
DECLARE #TAB VARCHAR(100) = (SELECT TOP 1 TABLE_NAME FROM #TEMP_DEL)
DECLARE #CMD NVARCHAR(200) = 'DROP TABLE '+#TAB
EXEC SP_EXECUTESQL #CMD
DELETE #TEMP_DEL WHERE TABLE_NAME = #TAB
END
Replace DBNAME with your database name.
HTH!
Thanks.
You could use dynamic query, while and if conditionals to construct a stored procedure or scheduled job (as you like) to solve this issue. Try this.
CREATE PROCEDURE dbo.delete_abc #Date date, #years_diff int
AS
--- Declare variables to use
DECLARE #sqlCommand varchar(30)
DECLARE #table varchar(20)
DECLARE #month int
DECLARE #year int
--- Temporary table with 'ABC_'s table names
SELECT TABLE_NAME
INTO #Temp
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'ABC_%'
AND TABLE_TYPE='BASE TABLE' -- If you want only tables
---- While there are tables to compare
WHILE EXISTS(SELECT * FROM #Temp)
BEGIN
--- Extract Month and Year of the first row in 'ABC_'s table
SET #month = (SELECT TOP 1 SUBSTRING(TABLE_NAME,5,2) FROM #Temp)
SET #year = (SELECT TOP 1 SUBSTRING(TABLE_NAME,7,4) FROM #Temp)
--- Compare if date difference of the table is more than #years_diff years from #Date
IF DATEDIFF(YEAR, CAST(CAST(#year AS VARCHAR) + '-' + CAST(#month AS VARCHAR) + '-01' AS DATE), DATEADD(MONTH, DATEDIFF(MONTH, 0, #Date), 0)) > #years_diff
BEGIN
--- Construct and execute delete query
SET #table = (SELECT TOP 1 TABLE_NAME FROM #Temp)
SET #sqlCommand = 'DROP TABLE ' + #table --- or 'DELETE FROM ' if you only want to delete all rows from table
EXEC(#sqlCommand)
END
--- Delete first row of 'ABC_'s tables in temporary
DELETE TOP (1) FROM #Temp;
END
--- Drop temporary table
DROP TABLE #Temp
GO;
Once it's created, you can use this stored procedure like this or with the parameters you like:
DECLARE #Now date
SET #Now = GETDATE()
EXEC dbo.delete_abc #years_diff = 7, #Date = #Now
Wouldn't it be easy enough to make a delete query?
Delete From [Your_Table] Where [Date_Column] = 'ABC_012010'
Sometimes we need to debug with our client data and we dont have time to take a complete database backup so we convert manually a sql result to a combination of static 'select UNION select UNION' so we can use their data on the fly...
Example:
select * from items
Results:
Itemcode ItemName Price
Car1 FerrariX 1200.00
Car2 FerrariZ 3000.00
Car3 MustangR 2100.00
And we bring it back to our debuging enviroment like this:
select 'Car1' as Itemcode, 'FerrariX' as Itemname, 1200.00 as 'Price' UNION
select 'Car2', 'FerrariZ', 3000.00 UNION
select 'Car3', 'MustangR', 2100.00
Posible Stored Procedure Solution:
EXEC spQueryAsStaticData #Query = 'select * from items'
How can we do this transformation automatically? Some stored procedure?
i use something like this to print out text using data
DECLARE #i int
DECLARE #employee_id int
Declare #Hash nvarchar(max)
declare #Result nvarchar(max)
Declare #String nvarchar(MAX)
DECLARE #numrows int
DECLARE #employee_table TABLE (
idx smallint Primary Key IDENTITY(1,1)
, [ID] int , [Hash] nvarchar(50), Result nvarchar(50)
)
INSERT #employee_table
SELECT Top 5 * FROM [Hlist].[dbo].[MD5]
set #i =0
set #String = ''
SET #numrows = (SELECT COUNT(*) FROM #employee_table)
IF #numrows > 0
WHILE (#i <= (SELECT MAX(idx) FROM #employee_table))
BEGIN
-- get the next employee primary key
SET #employee_id = (SELECT ID FROM #employee_table WHERE idx = #i)
SET #Hash = (SELECT Hash FROM #employee_table WHERE idx = #i)
SET #Result = (SELECT Result FROM #employee_table WHERE idx = #i)
Set #String = coalesce(#String +'Select '+ convert(varchar,#employee_id) + ', ' +#Hash+ ', '+#Result +' Union ', '')
--
-- do something with this employee
--
-- increment counter for next employee
SET #i = #i + 1
END
Print #String
In the end we solved it developing a little C# app, not as useful as generating it directly from a SQL query but it works...
If someone gives the SQL solution we will grant the answer to him/her