Requirement :
Due to some space issue our scheduled jobs are failing so to avoid this I have developed if FreeSpace is >50 GB then backup to F drive , If FreeSpace is < 50 then backup to G drive .. it has to check the all the drives and change the path automatically. Some how the below code is not working.Help on this highly appriciated.
create table #Space(Drive varchar(4),SpaceAvailable varchar(15))
insert into #Space(Drive,SpaceAvailable)
exec xp_fixeddrives
Alter table #Space add FinalSpace as spaceavailable/1024
select * from #Space
Declare #FreeSpace varchar(10)
select #FreeSpace=(select top 1 FinalSpace from #Space)
print #FreeSpace
if (#FreeSpace <50)
begin
backup database PerfDB to disk='G:\PerfDB.bak'
end
if (#FreeSpace >50 )
begin
backup database PerfDB to disk='F:\PerfDB.bak'
end
The below code worked for me.
create table #Space(Drive varchar(4),SpaceAvailable varchar(15))
insert into #Space(Drive,SpaceAvailable)
exec xp_fixeddrives
Alter table #Space add FinalSpace as spaceavailable/1024
select * from #Space
Declare #FreeSpace int=0
select #FreeSpace=51 --(select top 1 FinalSpace from #Space)
print #FreeSpace
if (#FreeSpace between 0 and 50)
begin
print 'No Space Available'
end
if (#FreeSpace between 51 and 124 )
begin
backup database PerfDB to disk='E:\PerfDB.bak'
Print 'Loop Entered to E'
end
if (#FreeSpace between 125 and 150 )
begin
backup database PerfDB to disk='F:\PerfDB.bak'
Print 'Loop Entered to F'
end
Related
Hi Can any one please help me with a procedure for inserting 7 million records for 7 years (million records each year) in loop in MYSQL,
I need to insert in a batch of 500,000 for each batch .
Data is there in table "Archive_data", need to insert in "Stg_table"
Archive data has yearly sales, i want to write a loop in MYSQL looping on Year and insert in a batch of 500K each
i tried
insert into SDL_Stg_Bill_Details
select SDL_Id, Rec_Is_Processed, concat(Bill_Header_Key,'_',Row_Num), Bill_Header_Key,Row_Num from (
SELECT SDL_Id, Rec_Is_Processed, Bill_Details_Key, Bill_Header_Key,
ROW_NUMBER() OVER(partition by Bill_Header_Key order by SDL_Id ) Row_Num
FROM PANTALOONS_SOLUS_PROD.SDL_Stg_Bill_Details_Archive
where EXTRACT(YEAR_MONTH FROM Bill_Date) in ('201406',
'201407',
'201408',
'201409',
'201410') ff
i am getting lock wait time out exceeded error if i am trying 7 M records
at once
Thanks in advance
Not sure if this is what you want, but I hope with some tweaks it might help you:
DELIMITER $
CREATE PROCEDURE CopyDataInBatch()
BEGIN
DECLARE x INT;
DECLARE y INT;
SET x = 1;
SET y = x + 10000;
the_loop : LOOP
IF x > 1000000 THEN /* Use the number of rows you wanted to copy*/
LEAVE the_loop;
END IF;
INSERT INTO table_in_which_copying (col_name_1, col_name_2)
SELECT (col_name_1, col_name_2) FROM table_from_which_copying
ORDER BY (col_name_1)
LIMIT x, y;
SET x = x + 10000;
SET y = y + 10000;
SELECT "Copied 10000 rows"; /* Only for testing... better remove it(?)*/
END LOOP;
END $
DELIMITER ;
This is driving me bananas. I'm not a mysql guru by any stretch. My goal is to add a large number of columns to a table. I've tried this several ways and the procedure chokes on the DECLARE #FooA NVARCHAR(MAX);. No clue as to why.
I appreciate any pointers...
USE mydatabase;
DELIMITER $$
DROP PROCEDURE IF EXISTS RepeatLoopProc$$
CREATE PROCEDURE RepeatLoopProc()
BEGIN
DECLARE x INT;
DECLARE sn VARCHAR(30);
DECLARE dr VARCHAR(48);
DECLARE #FooA NVARCHAR(MAX);
SET x = 0;
WHILE (x <= 150) DO
SET sn = CONCAT('drivesn_', x);
SET dr = CONCAT('driveinf_', x);
SET x = x + 1;
SET #FooA = 'ALTER TABLE DRIVE_MASTER ADD ' + sn + ' VARCHAR(30), ADD ' + dr + ' VARCHAR(48)';
EXEC sp_executesql #FooA;
END WHILE;
END$$
DELIMITER ;
When I do this I get:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#FooA NVARCHAR(MAX);
My forehead is getting flat from slamming it into my desk.
The ultimate goal is adding columns drivesn_0, driveinf_0, drivesn_1, driveinf_1, etc all the way out to drivesn_150 and driveinf_150. Type VARCHAR(30) and VARCHAR(48) for each respectively.
#variables are not DECLAREd and declared variables' identifiers do not start with #.
Also, ALTER statements typically recreate a table behind the scenes (equivalent to something like CREATE TABLE newversion... INSERT INTO newversion SELECT * FROM oldversion ... DROP TABLE oldversion ... RENAME newversion). So you'd be much better off building up a single ALTER statement within the loop, and executing it only once.
Example:
...
SET #FooA = 'ALTER TABLE DRIVE_MASTER';
SET x = 0;
WHILE (x <= 150) DO
SET sn = CONCAT('drivesn_', x);
SET dr = CONCAT('driveinf_', x);
SET #FooA = CONCAT(#FooA
, CASE WHEN x != 0 THEN ', ' ELSE '' END
, 'ADD ', sn, ' VARCHAR(30), ADD ', dr, ' VARCHAR(48)'
);
SET x = x + 1;
END WHILE;
EXEC sp_executesql #FooA;
...
... but what Barmar said in comments is good advice, you should probably just have another table, something like DRIVE_MASTER_DETAILS(x int, sn VARCHAR(30), dr VARCHAR(48))
I already have multiple tables. Basically I am using this to catalog drive serial numbers in hosts. Host can have up to 150 drives. Other tables contain network interface information (macaddrs, etc). All tied together by a common index value. For a system with 150 disk drives I cannot see another way other than 150 columns. Either that or I am missing a fundamental concept.
I have one shared database and multiple client databases. The data is stored in the client database. We want to create a master set of stored procedures in the shared database and execute them from the client database. Given the following:
use shared;
go
create procedure GetInvoices as
print db_name() ' <- current database'
select * from invoices
go
use client1;
create table invoices(...columns...)
exec shared.dbo.GetInvoices
This returns the following error:
shared <- current database
Msg 208, Level 16, State 1, Procedure GetInvoices, Line 3
Invalid object name 'invoices'.
Without using dynamic SQL, how can I run the stored procedure in shared from client1 so that it executes in client1 and thus has access to all of the tables in client1?
You can run a stored procedure defined in master database in context of client1 database and see all client1 database tables, without dynamic SQL, but it uses undocumented stored procedure sp_ms_marksystemobject.
Your stored procedure name must start with sp_, for example sp_GetInvoices. Create it in master database, then call exec sp_ms_marksystemobject sp_GetInvoices to make it see the tables of the current database.
USE master
GO
CREATE OR ALTER PROCEDURE sp_GetInvoices
AS
BEGIN
SELECT ClientName from Invoice
END
GO
exec sp_ms_marksystemobject sp_GetInvoices
USE client1
GO
create table Invoice (ClientName varchar(100))
insert Invoice select 'Acme Client'
exec sp_GetInvoices
Result (running on SQL Server version 13.0.5081.1):
ClientName
------------
Acme Client
Try this on your "Master" database:
CREATE PROCEDURE [dbo].[GetDataFromClient]
#DB VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #STMT VARCHAR( 300 );
DECLARE #SP VARCHAR( 500 );
SET #SP = 'dbo.GetData';
SET #STMT = 'EXEC(''' + #SP + ''')';
EXEC('USE '+ #db + ';' + #STMT)
END
Now on the "Client" database:
CREATE TABLE [dbo].[TestClient](
[ID] [int] NOT NULL,
[Description] [varchar](10) NULL,
CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED
(
[ID] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY].
Create the stored procedure to retrieve data from table TestClient
CREATE PROCEDURE [dbo].[GetData]
AS
BEGIN
SELECT *
FROM TestClient;
END
Now you can retrieve the columns from the TestClient Database using:
USE [TestMaster]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[GetDataFromClient]
#DB = N'TESTCLIENT'
SELECT 'Return Value' = #return_value
GO
You can call stored procedure using four part name after creating link server.
Or it can be called by openquery option.
LinkSerevr:
EXEC [ServerName] .dbname.scheme.StoredProcedureName
openquery : SELECT * FROM
OPENQUERY( [ServerName] .dbname.scheme.StoredProcedureName)
I have inherited maintenance of a SQL Server (2008), and I want to modify some of the system stored procedures. These are user-defined system stored procedures (for example: sys.sp_customproc). I can only assume they were created as system procedures so they could be shared across multiple databases? But regardless, I need to modify them.
Here is an example of one of them.
USE [msdb]
GO
/****** Object: StoredProcedure [sys].[sp_dbmmonitorhelpmonitoring] Script Date: 06/12/2013 13:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [sys].[sp_dbmmonitorhelpmonitoring]
as
begin
set nocount on
if (is_srvrolemember(N'sysadmin') <> 1 )
begin
raiserror(21089, 16, 1)
return (1)
end
declare #freq_type int, -- 4 = daily
#freq_interval int, -- Every 1 days
#freq_subday_type int, -- 4 = based on Minutes
#freq_subday_interval int, -- interval
#job_id uniqueidentifier,
#schedule_id int,
#retention_period int,
#jobname nvarchar( 256 )
select #jobname = isnull( formatmessage( 32047 ), N'Database Mirroring Monitor Job' )
select #job_id = job_id from msdb.dbo.sysjobs where name = #jobname
if (#job_id is null) -- if the job does not exist, error out
begin
raiserror( 32049, 16, 1 )
return 1
end
select #schedule_id = schedule_id from msdb.dbo.sysjobschedules where job_id = #job_id
select #freq_type = freq_type,
#freq_interval = freq_interval,
#freq_subday_type = freq_subday_type,
#freq_subday_interval = freq_subday_interval
from msdb.dbo.sysschedules where schedule_id = #schedule_id
-- If the frequency parameters are not what we expect then return an error
-- Someone has changed the job schedule on us
if (#freq_type <> 4) or (#freq_interval <> 1) or (#freq_subday_type <> 4)
begin
raiserror( 32037, 16, 1)
return 1
end
select #freq_subday_interval update_period
return 0
end
When I try to execute it, I get the error:
Msg 208, Level 16, State 6, Procedure sp_dbmmonitorhelpmonitoring, Line 46
Invalid object name 'sys.sp_dbmmonitorhelpmonitoring'.
My login is 'sa', I am mapped to the user 'dbo' in the [msdb] database. How do I modify this stored procedure?
You cannot alter a SP once you have marked it as a "system stored procedure". Instead, you have to drop it, recreate it and mark it as a system stored procedure again (using sp_ms_marksystemobject).
I'm sure you already realize how very dangerous it is to mess with anything that has been marked as "system". I feel obliged to strongly recommend that you make plenty of backups before you attempt any of this. Namely, back up: master, model and MSDB.
I want to make propotion codes for my product.
I have created an appropriate SQL statement which basically uses the current timestamp and runs SHA1 on it.
I tried a while ago to create an iterative loop over my INSERT command but failed
anyone know how?
Do 50 times
INSERT INTO ......
end
Also, I cannot have two of the same promotion code so the timestamp needs to be different for each iteration (If it is at all possible that the timestamp might be the same between iterations).
write the code in python or some other scripting language.
Use a GUID for the promotion code rather than a hash of the timestamp.
http://dev.mysql.com/doc/refman/5.0/en/flow-control-constructs.html
Your approach with using the PROCEDURE is the best I guess. I would first set another delimiter, because you are using the ';' already:
delimiter //
After that define your procedure. The INSERT INTO ...... is your INSERT code, what you wrote in your question.
CREATE PROCEDURE createPromotions(p1 INT)
BEGIN
SET #x = 0;
REPEAT
SET #x = #x + 1;
INSERT INTO ......
UNTIL #x > p1
END REPEAT;
END
//
After entering the '//' the procedure is ready to CALL. And if you want to execute it 50 times, just call it 50 times:
CALL createPromotions(50)
This is pretty dirty, but if you have any table on your system which you know has more than 50 rows, you can do the following:
create table promotion_code ( pc varchar(100) );
set #c = 1;
insert into promotion_code
select sha1( now() + (#c := #c + 1 ) )
from mysql.help_relation limit 50;
CREATE PROCEDURE createPromotions(p1 INT)
BEGIN
SET #x = 0;
REPEAT SET #x = #x + 1; UNTIL #x > p1 END REPEAT;
END
Some sort of proceedure like this would be nice but I don't know how to get it into the format I need. which is to repeat an SQL statement 50 times