I have a batch/sql script pair used to back databases up. I recently went into the folder to get a db back and I saw that it wasn't working. I checked out my batch script and it's not giing me the day or month but the year is showing up as 'on'! My SQL script is working fine, and I want to add that my batch script used to work.
Here's my batch script
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%dd%-%mm%-%yyyy%
rem day month year check
echo %dd%
echo %mm%
echo %yyyy%
echo %date%
mkdir %date%
sqlcmd -S .\SQLEXPRESS -i backupQuery.sql
and here's 'backupQuery.sql'
DECLARE #BackupLocation AS NVARCHAR(255) = 'C:\SQL\backups\'
/* Set #CurrentDate to a timestamp in mmddyyyy form */
DECLARE #CurrentDate AS NVARCHAR(255)
SET #CurrentDate = REPLICATE('0', 2 - LEN(CAST(DAY(GETDATE()) AS NVARCHAR))) /*day number 1*/
+
CAST(DAY(GETDATE()) AS NVARCHAR) /*day number 2*/
+ '-' +
REPLICATE('0', 2 - LEN(CAST(MONTH(GETDATE()) AS NVARCHAR))) /*month number 1*/
+
CAST(MONTH(GETDATE()) AS NVARCHAR) /*month number 1*/
+ '-' +
CAST(YEAR(GETDATE()) AS NVARCHAR) /*year*/
DECLARE #DatabaseName AS NVARCHAR(255)
/* Get all databases except for the temporary database */
DECLARE Databases CURSOR FOR
SELECT name
FROM sys.databases
WHERE name
NOT IN
('tempdb',
'master',
'model',
'msdb')
OPEN Databases
FETCH NEXT FROM Databases
INTO #DatabaseName
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #Command AS NVARCHAR(MAX)
SET #Command = 'BACKUP DATABASE ' + QUOTENAME(#DatabaseName) + ' TO DISK = ''' +
#BackupLocation + #CurrentDate + '\' + #DatabaseName + '.BAK'''
EXEC(#Command)
FETCH NEXT FROM Databases
INTO #DatabaseName
END
CLOSE Databases
DEALLOCATE Databases
They're meant to backup to a directory named after the current date, but it's coming through as --on?!
Myself and #aschipfl managed to solve it, the reason it was breaking I believe was due to the fact that I was reassigning a system variable. All I had to do was use the DATE CONVERT format 6 in my SQL and the %date% variable in cmd. That solved it and I now have a format of dd-MMM-yy.
Related
I need to copy certain file from a folder A to a folder B, but I need to copy only file based on a condition. The name of the file must start with the same value as a variable I have in my stored procedure.
Here is what I've got at the moment:
DECLARE #SQLFile VARCHAR(1024)
DECLARE #MessageId INT = 3 --copy all the files from the source folder that start with this variable
DECLARE #SourceFolderPath VARCHAR(1024)
DECLARE #DestinationFolderPath VARCHAR(1024)
SET #DestinationFolderPath = '\\mydestination'
SET #SourceFolderPath = '\\mysource'
SET #SQLFile = ' COPY /Y ' + #SourceFolderPath + ' /B ' + #DestinationFolderPath
EXEC master..xp_cmdshell #SQLFile
With this code I copy all the files but I don't know if there is a way to integrate the condition of beginning of name.
Thanks
I'm guessing a simple file glob will do what you want. But as people said in the comments using xp_cmdshell can create all kinds of security issues if used where untrusted data is kicking about. For this reason it is also often blocked by SQL Server security policy.
DECLARE #SQLFile VARCHAR(1024)
DECLARE #MessageId INT = 3 --copy all the files from the source folder that start with this variable
DECLARE #SourceFolderPath VARCHAR(1024)
DECLARE #DestinationFolderPath VARCHAR(1024)
SET #DestinationFolderPath = '\\mydestination'
SET #SourceFolderPath = '\\mysource'
SET #SQLFile = ' COPY /Y ' + #SourceFolderPath + '\' + CAST(#MessageID AS varchar(max)) + '* /B ' + #DestinationFolderPath
EXEC master..xp_cmdshell #SQLFile
Begin
Declare #registration_no int = 101
declare #bcp varchar(8000)
set #bcp = 'sqlcmd -s, -W -Q "set nocount on; SELECT * FROM [Student_Management].[dbo].[Student] WHERE registration_no= '+ cast(#registration_no as nvarchar(10))+' " | findstr /v /c:"-" /b > "d:\student.csv"'
EXEC master..xp_cmdshell #bcp
end
The above statements export the table data as CSV correctly, but instead of comma-separated values, I want pipe(|) separated output. Where can I mention a custom delimiter(|)
Edit:
Begin
Declare #registration_no int = 101
declare #bcp varchar(8000)
set #bcp ='sqlcmd -s"|"-W -Q "set nocount on; SELECT * FROM [Student_Management].[dbo].[Student] WHERE registration_no= '+ cast(#registration_no as nvarchar(10))+' " | findstr /v /c:"-" /b > "d:\student.csv"'
EXEC master..xp_cmdshell #bcp
END
Begin
Declare #registration_no int = 101
declare #cmd varchar(8000)
set #cmd='sqlcmd -W -s"|", -Q "set nocount on; SELECT * FROM [Student_Management].[dbo].[Student] WHERE registration_no= '+ cast(#registration_no as nvarchar(10))+' " | findstr /v /c:"-" /b > "d:\student.csv"'
EXEC master..xp_cmdshell #bcp
END
BATCH FILE:
ECHO OFF
SET /P colu= Enter column name:
SET /P sn= Enter ID (split by commas):
rem Grab filenames in an array
set n=0
for %%a in (%SN%) do (
set /A n+=1
set "id[!n!]=%%~a"
)
rem For example, to process the filenames:
for /L %%i in (1,1,%n%) do (
echo %%i- !id[%%i]!
)
sqlcmd -U USER-P PASSW -S SERVER -d DB -i sqlFILE.sql -o LOGS.txt -v delete=colu d_id=snode
I want to delete several ids from the database. This batch file asks the user what they want to be deleted and it is suppose to put the entered values in an array.
These entered values are entered into this SQL script:
declare #columnName nvarchar(255)
declare #intValue int
set #columnName = '$(colu)' --COLUMN NAME WHERE VALUE IS LOCATED
set #intValue = '$(sn)' --VALUE TO BE DELETED
declare #DeleteValue varchar(10)
set #DeleteValue = convert(varchar(10), #intValue)
declare #sql nvarchar(max) = ''
select #sql = #sql + 'delete ' + object_name(c.object_id) + ' where ' + #columnName + ' IN ' + #DeleteValue + ';'
from sys.columns c
where c.name = #columnName
select #sql
exec sp_executesql #sql
The problem is that the program is still looking at the values entered as one whole value and not separate values.
I have a query to move files from one folder(Source) to another(Destination)
I have given permission on both source and destination to network services and local services, I get an error
The system cannot find the file specified
I have tested the folders to see if I am able to to access the files and I was able to, it seems when I get the files it works. It is when I try to move the files to the Destination folder, I get this error.
My query below is as follow, I create a temp table to link to my source folder and insert its contents into it, I then filter it out into another temp table, where I then get the files I want to move and then use a cursor to iterate through it and move the files.
I hope this can assist.
Create Table #tmpDir
(
ID int IDENTITY(1,1),
fName varchar(400)
)
Declare #dir varchar(100)
Declare #folderPath varchar(500)
set #folderPath = '\\Server1\Documents\Ocs\Inbox\'
set #dir = 'DIR ' + '"' + #folderPath + '"'
print #dir
INSERT #tmpDir EXECUTE master.dbo.xp_cmdshell #dir
DELETE FROM #tmpDir where ID < 6
SELECT SUBSTRING(FName,40,100) fileName2
into #THIS
FROM #tmpDir
WHERE FName not like '%<DIR>%'
and FName not like '%bytes%' and FName is not null
Delete #THIS Where fileName2 Not Like '%_MyFiles%'
Declare #FileMove varchar(100)
Declare cur cursor for
Select fileName2 From #THIS
Open cur
Fetch next from cur into #FileMove
WHILE ##FETCH_STATUS = 0
BEGIN
Declare #cmd varchar(1000)
set #cmd = 'Move /y "\\Server1\Documents\Ocs\Inbox\' + #FileMove + ' "\\Server1\ImportMac\Inbox"'
EXECUTE master.dbo.xp_cmdshell #cmd
Fetch next from cur into #FileMove
END
Close cur
Deallocate cur
Drop Table #tmpDir, #THIS
You need to put a double quote at the end of the source file name for your move command:
set #cmd = 'Move /y "\\Server1\Documents\Ocs\Inbox\' + #FileMove + '" "\\Server1\ImportMac\Inbox"'
I'm a SQL Newbie and I'm trying to figure out how to use a Parameter with SQL Thru Command-Line
For my boss/staff I have written Batch Files to run SQL Code for them to export data and the like. In Access all I have to do is [Paramerter] and it prompts for data to be entered.
The #State Variable I'd like to be able to be set dynamically. I'd like the batch file to ask for State and Query use that information. I have no idea how to do it.
Batch File
sqlcmd -E -S ServerName -i C:\Lead$\SQL\MakeSTPhoeLists.sql
pause
The SQL File
Use LeadsDb
Go
Declare #State VarChar(2)
Set #State = 'DE'
DELETE FROM tblzExportPhone
INSERT INTO tblzExportPhone ( Phone )
SELECT tblLeads.Phone
FROM tblLeads
WHERE tblLeads.ST = #State
Declare #FileName VarChar(100)
Set #FileName = 'H:\Leads\Storage\STLists\' + #State +'StatePhoneList.csv'
DECLARE #bcp_cmd4 VARCHAR(400) = ' BCP.EXE LeadsDb..tblzExportPhone out '
SET #bcp_cmd4 = #bcp_cmd4 + 'H:\Leads\SQL\Formats\PhoneTmp.csv' + ' -T -f H:\Leads\SQL\Formats\tblzExportPhone.fmt'
SET #bcp_cmd4 = #bcp_cmd4 + ' & Copy /b H:\Leads\SQL\Formats\ExPhone.csv+H:\Leads\SQL\Formats\PhoneTmp.csv ' + #FileName + ' /y'
Set #bcp_cmd4 = #bcp_cmd4 + ' & Del H:\Leads\SQL\Formats\PhoneTmp.csv'
Thank You.
In your sql file use this notation $(statename)
Add this to your command file -v statename = %1
And execute it passing the parameter mycommanfile.cmd DE
Also read this for a full example.
Essentially what I found out is you have to make a Stored Procedure and Call a query to run it. I'm going to leave an example. BTW SQL Query Creates CSV File from table Using bcp and then Zips it up using RAR Dos Command.
BTW Stored procedure is used due to every which other way I try to do it withoutI failed, but once I added it I was golden. Can use Dos prompt insead of bat file but I'm setting up bat files for 'Semi-Computer Smart people'
Hope this helps a newbie like me out^^
BAT File (cmd prompt)
Echo phone numbers in the State to send to Paramount.
Echo Then after the file is made converts it to Zip.
Echo '
Set /p State=Enter Initials of the State? :
sqlcmd -E -S Titania -i H:\Lead$\SQL\STPhones.sql -v StateName=%State%
SQL Command #1
Use dbNameHere
go
Declare #State NVarChar(2)
EXECUTE [dbo].[STPhoneListB] #State=$(StateName)
SQLCommand #2
Use dbNameHere
Go
CREATE PROCEDURE [dbo].[STPhoneListB]
#State NVarChar(2) = 'DE',
#Folder VarChar(100) = 'H:\Lead$'
AS
BEGIN
Declare #FileName VarChar(150)
Set #FileName = #Folder + '\STPhones_'+ #State +'.csv'
Declare #DosCMD VarChar(150) = 'Del ' + #Folder +'\STPhones'+ #State
+'.Zip /q'
EXEC master..xp_cmdshell #DosCMD
DECLARE #bcp_cmd4 VARCHAR(400)
DELETE FROM tblzExportPhone
INSERT INTO tblzExportPhone ( Phone )
SELECT tblLeads.Phone
FROM tblLeads
WHERE tblLeads.ST = #State
Set #bcp_cmd4 = 'BCP.EXE LeadsDb..tblzExportPhone out '
SET #bcp_cmd4 = #bcp_cmd4 + 'H:\SQL\PhoneTmp.csv' +
' -T -f H:\SQL\tblzExportPhone.fmt'
SET #bcp_cmd4 = #bcp_cmd4
+ ' & Copy /b H:\SQL\ExPhone.csv+H:\SQL\PhoneTmp.csv '
+ #FileName + ' /y'
Set #bcp_cmd4 = #bcp_cmd4 + ' & Del H:\SQL\PhoneTmp.csv'
EXEC master..xp_cmdshell #bcp_cmd4
Set #bcp_cmd4 = 'cd '+ #Folder +
' & "C:\Program Files\WinRAR\rar.exe" m STPhones_'+ #State +'.Zip ' +
'STPhones_'+ #State +'.csv'
EXEC master..xp_cmdshell #bcp_cmd4
DELETE FROM tblzExportPhone
END