SQL Server Backup Script
Hello all,
not sure if I'm on the right thread but if not please do point me to the correct one.
basically I have a script that run every end of the month to do a backup of a database (Detach, Mount a new, and move the database to a new
location) bu since this month this is coming back with an error when running it. as far as i know nothing has changed since two or three months ago but this is not longer working.
Assistance is really needed. here.
Here is my code but this is now coming back with
Msg 5105, Level 16, State 4, Server PRITL1, Line 1
Device activation error. The physical file name
'E:\SQL\MSSQL\Data\Syslogd.mdf' may be incorrect.
@echo off
rem ***************************************************
rem * This script automates the Syslog Backup process *
rem ***************************************************
echo 192.168.0.9 > report.txt
date /t >> report.txt
time /t >> report.txt
blat report.txt -to [email protected] -f [email protected] -subject "Queen - Starting Syslog DB Maintenance" -server 192.168.0.26
echo ******************************************* >> report.txt
echo * Stopping the Kiwi Syslog Daemon Service * >> report.txt
echo ******************************************* >> report.txt
net stop "Kiwi Syslog Daemon"
for /F "tokens=3 delims=: " %%A in ('sc query "Kiwi Syslog Daemon" ^| findstr " STATE"') do (
if /I "%%A" NEQ "RUNNING" (
echo Stopping the Kiwi Syslog Daemon Service succeeded >> report.txt
echo. >> report.txt
) else (
echo -----!!! Stopping the Kiwi Syslog Daemon Service failed !!!----- >> report.txt
blat report.txt -to [email protected] -f [email protected] -subject "Queen - Syslog DB Maintenance Report" -server 192.168.0.26
exit
echo ********************************** >> report.txt
echo * Detaching the Syslogd database * >> report.txt
echo ********************************** >> report.txt
ping 127.0.0.1
ping 127.0.0.1
osql -E -b -Q "master..sp_detach_db 'Syslogd'" >> report.txt
set ReturnCode=%errorlevel%
if %ReturnCode% equ 0 (
echo Detaching the Syslogd database succeeded >> report.txt
echo. >> report.txt
) else (
echo. >> report.txt
echo -----!!! Detaching the Syslogd database failed !!!----- >> report.txt
echo. >> report.txt
echo ********************************************* >> report.txt
echo * Restarting the Kiwi Syslog Daemon service * >> report.txt
echo ********************************************* >> report.txt
net start "Kiwi Syslog Daemon"
for /F "tokens=3 delims=: " %%A in ('sc query "Kiwi Syslog Daemon" ^| findstr " STATE"') do (
if /I "%%A" NEQ "STOPPED" (
echo Restarting the Kiwi Syslog Daemon Service succeeded >> report.txt
blat report.txt -to [email protected] -f [email protected] -subject "Queen - Syslog DB Maintenance Report" -server 192.168.0.26
exit
) else (
echo -----!!! Restarting the Kiwi Syslog Daemon Service failed !!!----- >> report.txt
blat report.txt -to [email protected] -f [email protected] -subject "Queen - Syslog DB Maintenance Report" -server 192.168.0.26
exit
echo *************************************************** >> report.txt
echo * Moving the Syslogd database to the _Burn folder * >> report.txt
echo *************************************************** >> report.txt
Move E:\SQL\MSSQL\Data\Syslogd*.* \\server\Syslogs2\_Burn\
set ReturnCode=%errorlevel%
if %ReturnCode% equ 0 (
echo Moving the Syslogd database to the _Burn folder succeeded >> report.txt
echo. >> report.txt
) else (
echo -----!!! Moving the Syslogd database to the _Burn folder failed !!!----- >> report.txt
echo ************************************ >> report.txt
echo * Reattaching the Syslogd database * >> report.txt
echo ************************************ >> report.txt
osql -E -b -Q "master..sp_attach_db 'Syslogd','E:\SQL\MSSQL\Data\Syslogd.mdf','E:\SQL\MSSQL\Data\Syslogd_log.ldf'" >> report.txt
echo. >> report.txt
echo ********************************************* >> report.txt
echo * Restarting the Kiwi Syslog Daemon service * >> report.txt
echo ********************************************* >> report.txt
net start "Kiwi Syslog Daemon"
for /F "tokens=3 delims=: " %%A in ('sc query "Kiwi Syslog Daemon" ^| findstr " STATE"') do (
if /I "%%A" NEQ "STOPPED" (
echo Restarting the Kiwi Syslog Daemon Service succeeded >> report.txt
blat report.txt -to [email protected] -f [email protected] -subject "Queen - Syslog DB Maintenance Report" -server 192.168.0.26
exit
) else (
echo -----!!! Restarting the Kiwi Syslog Daemon Service failed !!!----- >> report.txt
blat report.txt -to [email protected] -f [email protected] -subject "Queen - Syslog DB Maintenance Report" -server 192.168.0.26
exit
echo **************************************** >> report.txt
echo * Restoring the blank Syslogd database * >> report.txt
echo **************************************** >> report.txt
osql -E -b -Q "Restore Database Syslogd from disk = 'E:\SQL\MSSQL\Backup\SyslogD_Blank.bak'" >> report.txt
set ReturnCode=%errorlevel%
if %ReturnCode% equ 0 (
echo Restoring the blank Syslogd database succeeded >> report.txt
echo. >> report.txt
) else (
echo. >> report.txt
echo -----!!! Restoring the blank Syslogd database failed !!!----- >> report.txt
echo ************************************ >> report.txt
echo * Moving back the Syslogd database * >> report.txt
echo ************************************ >> report.txt
Move \\server\Syslogs2\_Burn\Syslogd*.* E:\SQL\MSSQL\Data
echo ************************************ >> report.txt
echo * Reattaching the Syslogd database * >> report.txt
echo ************************************ >> report.txt
osql -E -b -Q "master..sp_attach_db 'Syslogd','E:\SQL\MSSQL\Data\Syslogd.mdf','E:\SQL\MSSQL\Data\Syslogd_log.ldf'" >> report.txt
echo. >> report.txt
echo ********************************************* >> report.txt
echo * Restarting the Kiwi Syslog Daemon service * >> report.txt
echo ********************************************* >> report.txt
net start "Kiwi Syslog Daemon"
for /F "tokens=3 delims=: " %%A in ('sc query "Kiwi Syslog Daemon" ^| findstr " STATE"') do (
if /I "%%A" NEQ "STOPPED" (
echo Restarting the Kiwi Syslog Daemon Service succeeded >> report.txt
blat report.txt -to [email protected] -f [email protected] -subject "Queen - Syslog DB Maintenance Report" -server 192.168.0.26
exit
) else (
echo -----!!! Restarting the Kiwi Syslog Daemon Service failed !!!----- >> report.txt
blat report.txt -to [email protected] -f [email protected] -subject "Queen - Syslog DB Maintenance Report" -server 192.168.0.26
exit
echo ******************************************* >> report.txt
echo * Starting the Kiwi Syslog Daemon service * >> report.txt
echo ******************************************* >> report.txt
net start "Kiwi Syslog Daemon"
for /F "tokens=3 delims=: " %%A in ('sc query "Kiwi Syslog Daemon" ^| findstr " STATE"') do (
if /I "%%A" NEQ "STOPPED" (
echo Starting the Kiwi Syslog Daemon Service succeeded >> report.txt
) else (
echo -----!!! Starting the Kiwi Syslog Daemon Service failed !!!----- >> report.txt
blat report.txt -to [email protected] -f [email protected] -subject "Queen - Syslog DB Maintenance Report" -server 192.168.0.26
exit
echo ************************************** >> report.txt
echo * Compressing the Syslog backup file * >> report.txt
echo ************************************** >> report.txt
"C:\program files\winrar\rar.exe" M -df -ep -ag -m5 \\server\Syslogs2\_Burn\PR-Syslog \\server\Syslogs2\_Burn\syslogd*.* >> report.txt
echo. >> report.txt
set ReturnCode=%errorlevel%
if %ReturnCode% equ 0 (
echo Compressing the Syslog backup file succeeded >> report.txt
echo. >> report.txt
) else (
echo -----!!! Compressing the Syslog backup file failed !!!----- >> report.txt
blat report.txt -to [email protected] -f [email protected] -subject "Queen - Syslog DB Maintenance Report" -server 192.168.0.26
exit
echo **************************** >> report.txt
echo * Completed * >> report.txt
echo * Ready for burning! * >> report.txt
echo * Check Archived files on * >> report.txt
echo * \\\server\Syslogs2 * >> report.txt
echo *************************** >> report.txt
echo. >> report.txt
date /t >> report.txt
time /t >> report.txt
blat report.txt -to [email protected] -f [email protected] -subject "Queen - Syslog DB Maintenance Report - Ready to Burn" -server 192.168.0.26
Bill thanks for that,
this is actually an SQL express edition and not a full SQL server.
Environment:
Databases will be detached, copied to from E:\SQL\MSSQL\Data\ to a shared location and then mount black database foles .MDF
and .LDF files to the SQL express and then restart the kiwi syslog applications.
why not powershell? well I've inherited this and machine is a 2003 server and we do not install PS on all machines except
if they are needed.
SQLServer Express comes with tools to backup the database. Post is SQLServer forum to learn how to set up and use SQLExpress tools.
SQLExpress has support in PowerShell for managing the server.
Here si on emethod posted by Microsoft that is useful. Methods using the scheduler and other tools are available.
http://support.microsoft.com/kb/2019698
¯\_(ツ)_/¯
Similar Messages
-
How to find sql server backup was taken under compression mode
Hello,
How to find SQL server backup was taken under compression mode ? I have disabled the Compress Mode backup setting but I want to make sure the backup is taken without compression.
Is there a script for that?
Thanks
JKI have disabled the Compress Mode backup
That is only a default setting, in backup command you can always overwrite it to a different value.
Olaf Helper
[ Blog] [ Xing] [ MVP] -
I am a software developer using Windows 8.1, Visual Studio 2013, and SQL Server 2014. I have a number (30+) of SQL Server databases that I use in my development and support activities.
Every time I run a backup (full or incremental) all of the backup devices in my instance of SQL Server 2014 are being deleted. I can add them all back in (a time-consuming and irritating process after about the 5th time), and the very next time I run either
the Acronis Backup and Paragon Hard Drive Backup against the volume (D:) that contains all of the .mdf and .ldf files, all of the backup devices are again deleted.
I hope someone can give me some idea of how to get around this problem or how to eliminate it completely. Should I not be using these types of backup utilities to copy the .mdf's and .ldf's? I've just never seen backup devices be deleted from SQL
Server. I have dumped the contents of the backup devices data within SQL Server and the rows are definitely gone after the either of the backups run.
Thanks in advance for any light you can shed on this problem. It is very time-consuming and seems pretty silly to me -- but it's happening nonetheless.The last backup location you use is never stored in sys.backup_devices. That's an instance-wide table for registering shared backup locations, mosly for tape backups in the old days.
Per-database backup history is stored in msdb, and AFAIK the database backup dialog in SSMS is pre-populated with a location from msdb. It looks like it runs this query
exec sp_executesql N'SELECT
bkpmf.media_family_id AS [ID],
bkpmf.family_sequence_number AS [FamilySequenceNumber],
bkpmf.media_count AS [MediaCount],
bkpmf.logical_device_name AS [LogicalDeviceName],
bkpmf.physical_device_name AS [PhysicalDeviceName],
CASE WHEN bkpmf.device_type > 100 THEN bkpmf.device_type - 100 ELSE bkpmf.device_type END AS [BackupDeviceType],
CAST(CASE WHEN bkpmf.device_type > 100 THEN 1 ELSE 0 END AS bit) AS [IsBackupDevicePermanent],
bkpmf.physical_block_size AS [PhysicalBlockSize]
FROM
msdb.dbo.backupmediaset bkpms
INNER JOIN msdb.dbo.backupmediafamily bkpmf ON bkpmf.media_set_id=bkpms.media_set_id
WHERE
(bkpms.media_set_id=@_msparam_0)',N'@_msparam_0 nvarchar(4000)',@_msparam_0=N'3'
So it's possible that your backup software is purging that table, eg by runningmsdb.dbo.sp_delete_database_backuphistory.
Or perhaps more likely, your backup software is adding data to the SQL Server backup history that prevents SSMS from pre-populating the backup dialog with your last TSQL backup location.
In any case, you don't need to manually take the bakcups through SSMS every day. You can just save a script of your backup commands (by hitting the Script button on the backup dialog) and run that. Or create a SQL agent job to run the script
or use a database maintence plan.
David
David http://blogs.msdn.com/b/dbrowne/ -
Problem: VSS error with 'SQL Server Backup to Windows Azure Tool' installed
When 'SQL Server Backup to Windows Azure Tool' is installed, shadow copies cannot be enable and backups fail. When attempting to enable shadow copies, we get a "volsnap" error: "The shadow copies of volume X were aborted because
of a failed free space computation". After uninstalling the "Tool", VSS works. Reinstalling "Tool" causes the problem to return.
While the error suggests a space issue, there is plenty of space on the server's two volumes. Additionally, another 100GB volume was added and VSS storage was allocated to it; still received the error.
Issue seems to point to 'SQL Server Backup to Windows Azure Tool'.
Environment: Hyper-V guest: "Windows Server 2012 R2 Standard" with "SQL Server 2008 R2 Standard". Using "Azure Storage" for SQL backups.
Suggestions?Hello,
Yes, we have a confirmed interference between the tool and the VSS Framework. This was identified very recently and is under investigation by the product group. Since the issue is within the filter driver shipped by the tool, that unfortunately means that
you currently need to choose between the tool and a working VSS Framework. If the latter is more important, then uninstall the tool (that will require a restart).
We apolologize for the inconvenience. I'm going to try to get the home page of the tool updated to avoid other situations like yours. Hopefully we should see a new version of the tool soon.
As a side note, recent versions of SQL Server can directly use Azure Storage as backup target, see
http://msdn.microsoft.com/en-us/library/jj919148(v=sql.110).aspx.
Regards,
Guillaume Fourrat - Microsoft France -
SQL Server backup on disk from DB13 in 6.20
Hello,
is it possible to perform database backups on disk (remote and local) in transaction DB13? Is the Enterprise Manager the only way to perform backups on disks?
The only media type available in DB13 is 'Tape' and I can't change this option (maybe there is no option). SAP Library provides confusing information, as it states that bakcup on disk is possible in DB13, but also points to the documentation of MS SQL Server in order to achieve it.
We have WAS 6.20 in 4.7 ES 1.10 with MS SQL Server 2000.
Thank you.
Antonio Sánchez.I think there is something called as virtual devices in enterprise manager which can be configured as TAPE device.
This virtual TAPE could be a actual TAPE or a DISK.
Try configuring it and see if it is visible in DB13.
We had done this 2 years ago, don't remember it properly.
good luck.
regards,
siddhesh -
PeopleSoft - SQL Server clone script
I am working for a county government as a consultant for PeopleSoft using SQL Server. When they restore a DEV instance from PROD, they have to manually stop the web server, app server and batch server, then they do the restore. Afterward they have to change
all references to PROD in the cloned DEV instance. Everything is done manually and takes a couple of hours.
Can anyone point me to scripts for PeopleSoft restores that automate bringing down/up the web, app and batch servers and all the other tasks so they don't have to be done manually?
Life is hard, but it's harder when you're stupid! John 'Duke' Wayne
Life is hard, but it's harder when you're stupid! John 'Duke' WayneThis question should be posted on PeopleSoft support forum as you are asking scripts to bring down app, web and batch servers and proprietary tasks of cleaning
up the data within tables.
That being said, a quick search on the internet will provide helpful links like below: http://www.erpassociates.com/peoplesoft-corner-wiki/peoplesoft-administration/cloning-a-peoplesoft-database.html
Satish Kartan www.sqlfood.com -
Windows Server backup script won't do differential/incremental
What follows is a script that doesn't seem to do backups on an incremental basis so it is creating full backups each time.
++++++++++
param(
[string]$volLetter,
[string]$scriptStorageLocation
function prepare-disk($checkDiskCriteria,$diskOrVolume){
if($diskOrVolume -eq 'disk'){
$disks = Get-WBDisk
$selected = $disks|?{$_.DiskName -match $checkDiskCriteria}
elseif($diskOrVolume -eq 'volume' ){
$allVolumes = Get-WBVolume -AllVolumes
$selected = $allVolumes|?{$_.MountPath -match $checkDiskCriteria}
return $selected
function add-volumeMountPoint($policyAdd,$mountPoint){
$matchVolumes = Get-WBVolume -AllVolumes
$correctVolume = $matchVolumes | ?{ $_.MountPoint -eq $mountPoint}
Add-WBVolume -Policy $policyAdd -Volume $correctVolume;
return $policyAdd
function add-VMToWB($policyAdd,$vmName){
$vmObject = Get-WBVirtualMachine |?{ $_.VMName -eq $vmName}
$vmobject='PCLaw';'2012CORPEXCHANGE';'File Server';'DC1'
Add-WBVirtualMachine $policyAdd -VirtualMachine $vmObject
return $policyAdd
function remove-policy(){
$policy = get-wbpolicy -editable
$policy|export-clixml 'backup.xml'
remove-wbpolicy $policy -force
function restore-policy($wbBackupTarget){
$policyRestore = import-clixml 'backup.xml'
$global:newPolicy = new-wbpolicy
Set-WBSchedule -Policy $newPolicy -Schedule $policyRestore.Schedule
$VolumeBackupLocation = New-WBBackupTarget -Volume $wbBackupTarget
Add-WBBackupTarget -Policy $newPolicy -Target $VolumeBackupLocation
if($([string]$policyRestore.VssBackupOptions) -match 'VssFullBackup' ){Set-WBVssBackupOptions $global:newPolicy -VssFullBackup;write-host 'foundFull'}
else{Set-WBVssBackupOptions $global:newPolicy -VssFullBackup;write-host 'FoundCopy'}
$newPolicyBound = $policyRestore.VolumesToBackup|%{add-volumeMountPoint $global:newPolicy $_.MountPoint;}
$global:newPolicy = $newPolicyBound[-1]
if($policyRestore.BMR){Add-WBBareMetalRecovery $global:newPolicy}
if($policyRestore.SystemState){Add-WBSystemState $global:newPolicy}
$newPolicyBound = $policyRestore.ComponentsToBackup | %{ add-VMToWB $global:newPolicy $_.VMName}
$global:newPolicy = $newPolicyBound[-1]
write-host -fore cyan 'Final Policy'
$global:newPolicy
Set-WBPolicy $global:newPolicy
function rename-WIB($pathWIB,$dateOfBackup){
if(test-path $pathWIB){
$newName = "WIB_"+$dateOfBackup
rename-item $pathWIB -newName $newName
Add-WBBackupTarget -Policy $newPolicy
Set-WBPolicy $newPolicy
if(!($scriptStorageLocation)){
$scriptStorageLocation = 'C:\Techbase\WindowsBackupRecreationScript';}
$volCheck = $volLetter+":";
$pathNew = $volLetter+":\WindowsImageBackup";
$dateOfBackup = Get-Date -UFormat "%Y_%m_%d";
$volName = $volLetter+":";
if(!(test-path "$scriptStorageLocation\WBfile.txt")){
$diskOrVolumeInput = Read-host 'Are you using a disk or a volume (type d or v)?'
$diskOrVolumeInput = $diskOrVolumeInput.ToLower();
if(($diskOrVolumeInput -eq 'v') -or ($diskOrVolumeInput -eq 'd')){
New-Item "$scriptStorageLocation\WBfile.txt" -type file
Add-content "$scriptStorageLocation\WBfile.txt" $diskOrVolumeInput
if($diskOrVolumeInput -eq 'd'){
disk
$diskNum= Read-host 'Please select the disk number ?'
Add-content "$scriptStorageLocation\WBfile.txt" $diskNum
elseif($diskOrVolumeInput -eq 'v'){
$allVolumes = Get-WBVolume -AllVolumes;
$allVolumes|Select *;
$diskVol= Read-host 'Please type in the letter of the Mountpath you would like to use (Only type in the letter)?'
$diskVol = $diskVol.ToUpper();
Add-content "$scriptStorageLocation\WBfile.txt" $diskVol
else{
Write-host -fore red 'Sorry the input was not an available option.'
else{
write-host 'Your configuration file was ready when this script is executed.';
$info = gc "$scriptStorageLocation\WBfile.txt"
if($info[0]='v'){
write-host -fore cyan $info[1]
$WB_Volume = prepare-disk $info[1] 'volume'
$locationOfWIB = $info[1] +":\WindowsImageBackup";
rename-WIB $locationOfWIB $dateOfBackup
remove-policy
restore-policy $WB_Volume
elseif($info[0]='d'){
$WB_Disk = prepare-disk 'WD My Book 1230 USB Device' 'disk'
$WB_Disk;
+++++++++++
Also what follows is the most recent backup policy.
+++++++++++++++++++
- <Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
- <Obj RefId="0">
- <TN RefId="0">
<T>Microsoft.Windows.ServerBackup.Commands.WBPolicy</T>
<T>System.Object</T>
</TN>
<ToString>Microsoft.Windows.ServerBackup.Commands.WBPolicy</ToString>
- <Props>
- <Obj N="Schedule" RefId="1">
- <TN RefId="1">
<T>System.Collections.Generic.List`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</T>
<T>System.Object</T>
</TN>
- <LST>
<DT>2014-10-14T19:30:00</DT>
</LST>
</Obj>
- <Obj N="BackupTargets" RefId="2">
- <TN RefId="2">
<T>System.Collections.Generic.List`1[[Microsoft.Windows.ServerBackup.Commands.WBBackupTarget, wsbcmdlet, Version=6.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]</T>
<T>System.Object</T>
</TN>
- <LST>
- <Obj RefId="3">
- <TN RefId="3">
<T>Microsoft.Windows.ServerBackup.Commands.WBBackupTarget</T>
<T>System.Object</T>
</TN>
<ToString>F:</ToString>
- <Props>
<S N="Label">3TB USB</S>
<Nil N="WBDisk" />
<S N="WBVolume">3TB USB (F:)</S>
<S N="Path">\\?\Volume{7f5bcfe6-a050-44be-80c9-b056f0121819}</S>
<S N="TargetType">Volume</S>
<B N="InheritAcl">true</B>
<B N="PreserveExistingBackup">true</B>
</Props>
</Obj>
</LST>
</Obj>
- <Obj N="VolumesToBackup" RefId="4">
- <TN RefId="4">
<T>System.Collections.Generic.List`1[[Microsoft.Windows.ServerBackup.Commands.WBVolume, wsbcmdlet, Version=6.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]</T>
<T>System.Object</T>
</TN>
<LST />
</Obj>
- <Obj N="FilesSpecsToBackup" RefId="5">
- <TN RefId="5">
<T>System.Collections.Generic.List`1[[Microsoft.Windows.ServerBackup.Commands.WBFileSpec, wsbcmdlet, Version=6.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]</T>
<T>System.Object</T>
</TN>
<LST />
</Obj>
- <Obj N="FilesSpecsToExclude" RefId="6">
<TNRef RefId="5" />
<LST />
</Obj>
- <Obj N="ComponentsToBackup" RefId="7">
- <TN RefId="6">
<T>System.Collections.Generic.List`1[[Microsoft.Windows.ServerBackup.Commands.WBApplicationComponent, wsbcmdlet, Version=6.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]</T>
<T>System.Object</T>
</TN>
- <LST>
- <Obj RefId="8">
- <TN RefId="7">
<T>Microsoft.Windows.ServerBackup.Commands.WBVirtualMachine</T>
<T>Microsoft.Windows.ServerBackup.Commands.WBApplicationComponent</T>
<T>System.Object</T>
</TN>
<ToString>0E91F216-553D-4C7C-8178-A09E5D081020\</ToString>
- <Props>
<S N="VMName">PCLaw 2008 R2</S>
<S N="ComponentName">0E91F216-553D-4C7C-8178-A09E5D081020</S>
<S N="LogicalPath" />
<S N="Caption">Backup Using Saved State\PCLaw 2008 R2</S>
<G N="WriterId">66841cd4-6ded-4f4b-8f17-fd23f8ddc3de</G>
<G N="InstanceId">b0f4f239-bcc6-408f-9db6-b66d5de9458d</G>
</Props>
</Obj>
- <Obj RefId="9">
<TNRef RefId="7" />
<ToString>12DCBB00-87D9-4660-82E1-E01245A5E011\</ToString>
- <Props>
<S N="VMName">2012CORPEXCHANGE</S>
<S N="ComponentName">12DCBB00-87D9-4660-82E1-E01245A5E011</S>
<S N="LogicalPath" />
<S N="Caption">Backup Using Saved State\2012CORPEXCHANGE</S>
<G N="WriterId">66841cd4-6ded-4f4b-8f17-fd23f8ddc3de</G>
<G N="InstanceId">b0f4f239-bcc6-408f-9db6-b66d5de9458d</G>
</Props>
</Obj>
- <Obj RefId="10">
<TNRef RefId="7" />
<ToString>8A769D3A-4B21-419A-8BA2-584EC3168C51\</ToString>
- <Props>
<S N="VMName">File Server</S>
<S N="ComponentName">8A769D3A-4B21-419A-8BA2-584EC3168C51</S>
<S N="LogicalPath" />
<S N="Caption">Backup Using Saved State\File Server</S>
<G N="WriterId">66841cd4-6ded-4f4b-8f17-fd23f8ddc3de</G>
<G N="InstanceId">b0f4f239-bcc6-408f-9db6-b66d5de9458d</G>
</Props>
</Obj>
- <Obj RefId="11">
<TNRef RefId="7" />
<ToString>A912807A-04FE-4AB6-981B-01D6489865D6\</ToString>
- <Props>
<S N="VMName">DC1</S>
<S N="ComponentName">A912807A-04FE-4AB6-981B-01D6489865D6</S>
<S N="LogicalPath" />
<S N="Caption">Backup Using Saved State\DC1</S>
<G N="WriterId">66841cd4-6ded-4f4b-8f17-fd23f8ddc3de</G>
<G N="InstanceId">b0f4f239-bcc6-408f-9db6-b66d5de9458d</G>
</Props>
</Obj>
</LST>
</Obj>
<B N="BMR">false</B>
<B N="SystemState">false</B>
<B N="OverwriteOldFormatVhd">false</B>
- <Obj N="VssBackupOptions" RefId="12">
- <TN RefId="8">
<T>Microsoft.Windows.ServerBackup.Commands.VssBackupOptions</T>
<T>System.Enum</T>
<T>System.ValueType</T>
<T>System.Object</T>
</TN>
<ToString>VssFullBackup</ToString>
<I32>0</I32>
</Obj>
</Props>
</Obj>
</Objs>
++++++++
+++++++++++++++++++++++++
Script does everything perfect except for the backup not being incremental/differential - it just creates a different folder each iteration that it puts the backup into.
I would appreciate if someone could go through and let me know what we might be doing wrong - why we are not able to get this job to be incremental/differential.
Thanks in advance.Hre are all of the options for Windows Backup:
http://technet.microsoft.com/en-us/library/ee706670.aspx
If you can find an incremental backup naywhere in the options then I will admit I have missed something.
The old Windows Backup, pre-2008, could do incremental backups. The newer backup system is minimal and serves different purposes.
The question about how to use a subsystem of Windows is NOT a scripting question. It is a "how-to" for a Windows component.
If you do not understand the scrip tyou posted then I recommend finding someone with sufficient understanding of Windows and the new backup Cmdlets to help you top understand how they work.
Here is the Microsoft description of Windows Server Backup:
Windows Server Backup consists of a Microsoft Management Console (MMC) snap-in, command-line tools, and Windows PowerShell cmdlets that provide a complete solution for your day-to-day backup and recovery needs. You can use Windows Server Backup to back
up a full server (all volumes), selected volumes, the system state, or specific files or folders—and to create a backup that you can use for bare metal recovery. You can recover volumes, folders, files, certain applications, and the system state. And, in case
of disasters like hard disk failures, you can perform a bare metal recovery. (To do this, you will need a backup of the full server or just the volumes that contain operating system files, and the Windows Recovery Environment—this will restore your complete
system onto your old system or a new hard disk.)
You can use Windows Server Backup to create and manage backups for the local computer or a remote computer. And, you can schedule backups to run automatically.
Windows Server Backup is intended for use by everyone who needs a basic backup solution—from small business to large enterprises—but is even suited for smaller organizations or individuals who are not IT professionals.
It specifically states that only a full server or selected file,device backup is possible. There is no statement of incremental backup. Windows Server backup is intended for server recovery.
If you type "help Set-WBVssBackupOptions
-full" you will see that there are only two options "full" and "copy".
Please post your issues in the WS2008 or the WS2012 forum to get more information on how the Windows Server backup service works.
¯\_(ツ)_/¯ -
How to find the existing sql server backup plan/schedule is there a script for that?
Friends,
Is there a easy way to find out in SQLServer (for All DB's) what is the current backup plan/schedule ? is there a script for that?
Thanks,
Karthikeyan JothiTo check the database backup
Select
SERVERPROPERTY('ServerName'),
db.name,
CONVERT(VARCHAR(10), b.backup_start_date, 103) + + convert(VARCHAR(8), b.backup_start_date, 14) backup_start_date,
CONVERT(VARCHAR(10), b.backup_finish_date, 103) + + convert(VARCHAR(8), b.backup_finish_date, 14) backup_finish_date,
case
when (DATEDIFF(hour, b.backup_start_date, getdate())<24)then 'Success'
when (DATEDIFF(hour, b.backup_start_date, getdate())>=24)then 'Failed'
end Status,
DATEDIFF(hh, b.backup_finish_date, GETDATE())BackupAgeInHours,
(b.backup_size/1024/1024/1024 )BackupSize,
case b.[type]
WHEN 'D' THEN 'Full'
WHEN 'I' THEN 'Differential'
WHEN 'L' THEN 'Transaction Log'
END Type,
ISNULL(STR(ABS(DATEDIFF(day, GetDate(),(Backup_finish_date)))), 'NEVER')DaysSinceLastBackup
FROM sys.sysdatabases db
Left OUTER JOIN (SELECT * , ROW_NUMBER() OVER(PARTITION BY database_name ORDER BY backup_finish_date DESC) AS RNUM
FROM msdb.dbo.backupset) b ON b.database_name = db.name AND RNUM = 1
where dbid<>2
OR
SELECT
DISTINCT
a.Name AS DatabaseName ,
CONVERT(SYSNAME, DATABASEPROPERTYEX(a.name, 'Recovery')) RecoveryModel ,
COALESCE(( SELECT CONVERT(VARCHAR(12), MAX(backup_finish_date), 101)
FROM msdb.dbo.backupset
WHERE database_name = a.name
AND type = 'd'
AND is_copy_only = '0'
), 'No Full') AS 'Full' ,
COALESCE(( SELECT CONVERT(VARCHAR(12), MAX(backup_finish_date), 101)
FROM msdb.dbo.backupset
WHERE database_name = a.name
AND type = 'i'
AND is_copy_only = '0'
), 'No Diff') AS 'Diff' ,
COALESCE(( SELECT CONVERT(VARCHAR(20), MAX(backup_finish_date), 120)
FROM msdb.dbo.backupset
WHERE database_name = a.name
AND type = 'l'
), 'No Log') AS 'LastLog' ,
COALESCE(( SELECT CONVERT(VARCHAR(20), backup_finish_date, 120)
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY backup_finish_date DESC ) AS 'rownum' ,
backup_finish_date
FROM msdb.dbo.backupset
WHERE database_name = a.name
AND type = 'l'
) withrownum
WHERE rownum = 2
), 'No Log') AS 'LastLog2'
FROM sys.databases a
LEFT OUTER JOIN msdb.dbo.backupset b ON b.database_name = a.name
WHERE a.name <> 'tempdb'
AND a.state_desc = 'online'
GROUP BY a.Name ,
a.compatibility_level
ORDER BY a.name
To check the schedule you can try the below script
https://gallery.technet.microsoft.com/SQL-Jobs-Complete-eabe0050
--Prashanth -
Conversion of SQL Server 2005 script to PL/SQL
I want to conver the below script into PL/SQL
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AuditLog]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[AuditLog](
[GroupID] [int] NOT NULL,
[ID] [int] NOT NULL,
[TableName] [varchar](25) NOT NULL,
[FieldName] [varchar](25) NOT NULL,
[FieldType] [varchar](25) NULL,
[OldValue] [text] NOT NULL,
[NewValue] [text] NOT NULL,
[ChangedOn] [timestamp] NOT NULL,
[ChangedBy] [int] NOT NULL,
CONSTRAINT [PK_AuditLog_ID] UNIQUE NONCLUSTERED
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UserRights]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[UserRights](
[UserID] [int] NULL,
[MenuName] [varchar](25) NULL,
[IsEnabled] [int] NULL,
CONSTRAINT [PK_UserRights_UserID] UNIQUE NONCLUSTERED
[UserID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GradeMaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[GradeMaster](
[ID] [int] NULL,
[Name] [varchar](25) NULL,
[Description] [varchar](25) NULL,
[From] [float] NULL,
[To] [float] NULL,
CONSTRAINT [PK_GradeMaster_ID] UNIQUE NONCLUSTERED
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CostGroup]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[CostGroup](
[ID] [int] NOT NULL,
[Name] [varchar](25) NOT NULL,
CONSTRAINT [PK_CostGroup_ID] UNIQUE NONCLUSTERED
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ToIndex]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
** Function dbo.ToIndex
CREATE FUNCTION [dbo].[ToIndex](@string_to_index VARCHAR(1024))
RETURNS VARCHAR(1024)
AS
BEGIN
DECLARE @temp VARCHAR(1024)
DECLARE @ivar VARCHAR(1024)
DECLARE @tmps VARCHAR(1)
SET @temp = ''''
SET @ivar = UPPER(@string_to_index)
DECLARE @i INTEGER
SET @i = 1
WHILE (@i <= LEN(@string_to_index))
BEGIN
SET @tmps = SUBSTRING(@ivar, @i, 1)
IF (ASCII(@tmps) >= 48 AND ASCII(@tmps) <= 57) OR (ASCII(@tmps) >= 65 AND ASCII(@tmps) <= 90)
BEGIN
SET @temp = @temp + @tmps
END
SET @i = @i + 1
END
RETURN @temp
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterID]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[MasterID](
[TableID] [int] NOT NULL,
[TableName] [varchar](25) NOT NULL,
[NextID] [int] NULL DEFAULT ((1)),
CONSTRAINT [PK_MasterID_TableID] UNIQUE NONCLUSTERED
[TableID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UserList]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[UserList](
[ID] [int] NOT NULL,
[Name] [varchar](25) NOT NULL,
[Password] [varchar](25) NOT NULL,
[FullName] [varchar](25) NULL,
CONSTRAINT [PK_UserList_ID] UNIQUE NONCLUSTERED
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Product]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Product](
[GroupID] [int] NOT NULL,
[ID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL,
[GrossMargin] [float] NULL DEFAULT ((0)),
[RMC] [float] NULL DEFAULT ((0)),
[Packing] [float] NULL DEFAULT ((0)),
[Overhead] [float] NULL DEFAULT ((0)),
[Others] [float] NULL DEFAULT ((0)),
[TotalCost] [float] NULL DEFAULT ((0)),
[DPRate] [float] NULL DEFAULT ((0)),
[CreatedOn] [datetime] NULL DEFAULT (getdate()),
[CreatedBy] [int] NULL DEFAULT ((1)),
[UpdatedOn] [datetime] NULL DEFAULT (getdate()),
[UpdatedBy] [int] NULL DEFAULT ((1)),
CONSTRAINT [PK_Product_GroupID_ID] UNIQUE NONCLUSTERED
[GroupID] ASC,
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RawMaterial]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RawMaterial](
[GroupID] [int] NOT NULL,
[ID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL,
[CurPrice] [float] NULL,
[OldPrice] [float] NULL,
[CreatedOn] [datetime] NULL,
[CreatedBy] [int] NULL,
[UpdatedOn] [datetime] NULL,
[UpdatedBy] [int] NULL,
CONSTRAINT [PK_RawMaterial_GroupID_ID] UNIQUE NONCLUSTERED
[GroupID] ASC,
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Recipe]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Recipe](
[GroupID] [int] NOT NULL,
[ID] [int] NOT NULL,
[WEFDate] [datetime] NOT NULL,
[ProductID] [int] NOT NULL,
[RawMaterialID] [int] NOT NULL,
[Seq] [int] NOT NULL,
[Quantity] [float] NOT NULL,
[RMCost] [float] NOT NULL,
[CreatedOn] [datetime] NULL,
[CreatedBy] [int] NULL,
[UpdatedOn] [datetime] NULL,
[UpdatedBy] [int] NULL,
CONSTRAINT [PK_Recipe_GroupID_Seq_ProductID_RawMaterialID] UNIQUE NONCLUSTERED
[GroupID] ASC,
[Seq] ASC,
[ProductID] ASC,
[RawMaterialID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCalcGM]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author: Mohammed Haris
-- Create date: 24-12-2006
-- Description: RMC Calculator
-- =============================================
CREATE PROCEDURE [dbo].[spCalcGM]
-- Add the parameters for the function here
@GroupID int,
@ProductID int,
@RM_ID int,
@Price int = 0
AS
BEGIN
--SET NOCOUNT ON
-- Declare the return variable here
DECLARE @Result float
DECLARE @SumCurPrice0 float
DECLARE @SumCurPrice float
DECLARE @SumOldPrice float
DECLARE @SumQuantity float
DECLARE @SumRMC float
DECLARE @PTotalCost float
DECLARE @PDPRate float
-- Add the T-SQL statements to compute the return value here
SELECT @SumCurPrice0 = SUM(Recipe.Quantity * RawMaterial.CurPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID <> @RM_ID)
AND (Recipe.GroupID = @GroupID)
/*IF ISNULL(@SumCurPrice0)*/
SET @SumCurPrice = ISNULL(@SumCurPrice0, 0)
/*ELSE
SET @SumCurPrice = @SumCurPrice0*/
IF @Price = 0
SELECT @SumOldPrice = SUM(Recipe.Quantity * RawMaterial.CurPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID = @RM_ID)
AND (Recipe.GroupID = @GroupID)
ELSE
SELECT @SumOldPrice = SUM(Recipe.Quantity * RawMaterial.OldPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID = @RM_ID)
AND (Recipe.GroupID = @GroupID)
SELECT @SumQuantity = SUM(Recipe.Quantity)
FROM Recipe
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.GroupID = @GroupID)
SELECT @SumRMC = (@SumCurPrice + @SumOldPrice) / @SumQuantity
SELECT @PTotalCost = (Product.Packing + Product.Overhead + Product.Others),
@PDPRate = Product.DPRate
FROM Product
WHERE (Product.ID = @ProductID) AND (Product.GroupID = @GroupID)
SELECT @PTotalCost = @PTotalCost + @SumRMC
SELECT @Result = (@PDPRate - @PTotalCost) / @PDPRate
SELECT
@SumCurPrice0 AS SumCurPrice0,
@SumCurPrice AS SumCurPrice,
@SumOldPrice AS SumOldPrice,
@SumQuantity AS SumQuantity,
@SumRMC AS SumRMC
-- Return the result of the function
RETURN @Result
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_UpdateTotalCostAndGMForAllProducts]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE
[dbo].[sp_UpdateTotalCostAndGMForAllProducts]
AS
BEGIN
UPDATE Product
SET Product.TotalCost = Product.RMC + Product.Packing + Product.Overhead + Product.Others
UPDATE Product
SET Product.GrossMargin = (Product.DPRate - Product.TotalCost) / Product.DPRate
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_UpdateTotalCostAndGMForProduct]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE
[dbo].[sp_UpdateTotalCostAndGMForProduct] (@ProductID int)
AS
BEGIN
UPDATE Product
SET Product.TotalCost = Product.RMC + Product.Packing + Product.Overhead + Product.Others
WHERE Product.ID = @ProductID
UPDATE Product
SET Product.GrossMargin = (Product.DPRate - Product.TotalCost) / Product.TotalCost
WHERE Product.ID = @ProductID
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CalcGM]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author: Mohammed Haris
-- Create date: 24-12-2006
-- Description: RMC Calculator
-- =============================================
CREATE FUNCTION [dbo].[CalcGM]
-- Add the parameters for the function here
@GroupID int,
@ProductID int,
@RM_ID int,
@Price int = 0
RETURNS float
AS
BEGIN
--SET NOCOUNT ON
-- Declare the return variable here
DECLARE @Result float
DECLARE @SumCurPrice float
DECLARE @SumOldPrice float
DECLARE @SumQuantity float
DECLARE @SumRMC float
DECLARE @PTotalCost float
DECLARE @PDPRate float
-- Add the T-SQL statements to compute the return value here
SELECT @SumCurPrice = SUM(Recipe.Quantity * RawMaterial.CurPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID <> @RM_ID)
AND (Recipe.GroupID = @GroupID)
SET @SumCurPrice = ISNULL(@SumCurPrice, 0)
IF @Price = 0
SELECT @SumOldPrice = SUM(Recipe.Quantity * RawMaterial.CurPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID = @RM_ID)
AND (Recipe.GroupID = @GroupID)
ELSE
SELECT @SumOldPrice = SUM(Recipe.Quantity * RawMaterial.OldPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID = @RM_ID)
AND (Recipe.GroupID = @GroupID)
SELECT @SumQuantity = SUM(Recipe.Quantity)
FROM Recipe
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.GroupID = @GroupID)
SELECT @SumRMC = (@SumCurPrice + @SumOldPrice) / @SumQuantity
SELECT @PTotalCost = (Product.Packing + Product.Overhead + Product.Others),
@PDPRate = Product.DPRate
FROM Product
WHERE (Product.ID = @ProductID) AND (Product.GroupID = @GroupID)
SELECT @PTotalCost = @PTotalCost + @SumRMC
SELECT @Result = (@PDPRate - @PTotalCost) / @PDPRate
-- Return the result of the function
RETURN @Result
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_RMCostImplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_RMCostImplication]
@GroupID int = 1,
@RM_ID int = 1
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT Product.Name, Product.DPRate, RawMaterial.Name AS RMName,
RawMaterial.CurPrice,
dbo.CalcGM(@GroupID, Product.ID, @RM_ID, 0)*100 AS CurGM,
RawMaterial.OldPrice,
dbo.CalcGM(@GroupID, Product.ID, @RM_ID, 1)*100 AS OldGM
FROM Product INNER JOIN
Recipe ON Product.ID = Recipe.ProductID INNER JOIN
RawMaterial ON Recipe.RawMaterialID = RawMaterial.ID
WHERE (Product.GroupID = @GroupID) AND (RawMaterial.ID = @RM_ID)
ORDER BY Product.Name
END
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Product_GroupID]') AND parent_object_id = OBJECT_ID(N'[dbo].[Product]'))
ALTER TABLE [dbo].[Product] WITH CHECK ADD CONSTRAINT [FK_Product_GroupID] FOREIGN KEY([GroupID])
REFERENCES [dbo].[CostGroup] ([ID])
GO
ALTER TABLE [dbo].[Product] CHECK CONSTRAINT [FK_Product_GroupID]
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_RawMaterial_GroupID]') AND parent_object_id = OBJECT_ID(N'[dbo].[RawMaterial]'))
ALTER TABLE [dbo].[RawMaterial] WITH CHECK ADD CONSTRAINT [FK_RawMaterial_GroupID] FOREIGN KEY([GroupID])
REFERENCES [dbo].[CostGroup] ([ID])
GO
ALTER TABLE [dbo].[RawMaterial] CHECK CONSTRAINT [FK_RawMaterial_GroupID]
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Recipe_GroupID_ProductID]') AND parent_object_id = OBJECT_ID(N'[dbo].[Recipe]'))
ALTER TABLE [dbo].[Recipe] WITH CHECK ADD CONSTRAINT [FK_Recipe_GroupID_ProductID] FOREIGN KEY([GroupID], [ProductID])
REFERENCES [dbo].[Product] ([GroupID], [ID])
GO
ALTER TABLE [dbo].[Recipe] CHECK CONSTRAINT [FK_Recipe_GroupID_ProductID]
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Recipe_GroupID_RawMaterialID]') AND parent_object_id = OBJECT_ID(N'[dbo].[Recipe]'))
ALTER TABLE [dbo].[Recipe] WITH CHECK ADD CONSTRAINT [FK_Recipe_GroupID_RawMaterialID] FOREIGN KEY([GroupID], [RawMaterialID])
REFERENCES [dbo].[RawMaterial] ([GroupID], [ID])
GO
ALTER TABLE [dbo].[Recipe] CHECK CONSTRAINT [FK_Recipe_GroupID_RawMaterialID]
Edited by: yogeshyl on Jul 28, 2009 4:50 PMDear yogeshyl!
OK, Let's try this step by step. I assume that you want to use Oracle in a version above 9i R2.
-- Please change the size x to a value that fits your needs. Every tablespace needs a datafile.
-- Please change <path_and_filename>.dbf to something like C:\oracle\oradata\ORCL\primary01.dbf.
CREATE TABLESPACE primary
DATAFILE '<path_and_filename>.dbf' SIZE x M;
CREATE USER object_owner
IDENTIFIED BY password
DEFAULT TABLESPACE primary
TEMPORARY TABLESPACE temp
QUOTA unlimited ON primary;
DROP TABLE object_owner.auditlog;
CREATE TABLE object_owner.auditlog
GroupID NUMBER NOT NULL,
ID NUMBER NOT NULL CONSTRAINT pk_auditlog_id PRIMARY KEY,
table_name VARCHAR2(25) NOT NULL,
field_name VARCHAR2(25) NOT NULL,
field_type VARCHAR2(25) NULL,
old_value VARCHAR2(4000) NOT NULL,
new_value VARCHAR2(4000) NOT NULL,
changed_on TIMESTAMP NOT NULL,
changed_by NUMBER NOT NULL
DROP TABLE object_owner.userrights;
CREATE TABLE object_owner.userrights
UserID NUMBER NULL CONSTRAINT pk_userrights_userid PRIMARY KEY,
MenuName VARCHAR2(25),
IsEnabled NUMBER
DROP TABLE object_owner.grademaster;
CREATE TABLE object_owner.grademaster
ID NUMBER NULL CONSTRAINT pk_grademaster_id PRIMARY KEY,
Name VARCHAR2(25),
Description VARCHAR2(25),
source NUMBER,
destination NUMBER
DROP TABLE object_owner.costgroup;
CREATE TABLE object_owner.costgroup(
ID NUMBER NOT NULL CONSTRAINT pk_costgroup_id PRIMARY KEY,
Name VARCHAR2(25) NOT NULL
DROP TABLE object_owner.masterid;
CREATE TABLE object_owner.masterid
TableID NUMBER NOT NULL CONSTRAINT pk_masterid_table_id PRIMARY KEY,
TableName VARCHAR2(25) NOT NULL,
NextID NUMBER DEFAULT ((1))
DROP TABLE object_owner.user_list;
CREATE TABLE object_owner.userlist
ID NUMBER NOT NULL CONSTRAINT pk_userlist_id PRIMARY KEY,
Name VARCHAR2(25) NOT NULL,
Password VARCHAR2(25) NOT NULL,
FullName VARCHAR2(25)
DROP TABLE object_owner.product;
CREATE TABLE dbo.Product
GroupID NUMBER NOT NULL,
ID NUMBER NOT NULL,
Name VARCHAR2(50) NOT NULL,
GrossMargin NUMBER DEFAULT ((0)),
RMC NUMBER DEFAULT ((0)),
Packing NUMBER DEFAULT ((0)),
Overhead NUMBER DEFAULT ((0)),
Others NUMBER DEFAULT ((0)),
TotalCost NUMBER DEFAULT ((0)),
DPRate NUMBER DEFAULT ((0)),
CreatedOn DATE DEFAULT SYSDATE,
CreatedBy NUMBER DEFAULT ((1)),
UpdatedOn DATE DEFAULT SYSDATE,
UpdatedBy NUMBER DEFAULT ((1)),
CONSTRAINT pk_product_groupid_id PRIMARY KEY (id, groupid);
DROP TABLE object_owner.rawmaterial;
CREATE TABLE object_owner.rawmaterial(
GroupID NUMBER NOT NULL,
ID NUMBER NOT NULL,
Name VARCHAR2(50) NOT NULL,
CurPrice NUMBER,
OldPrice NUMBER,
CreatedOn DATE,
CreatedBy NUMBER,
UpdatedOn DATE,
UpdatedBy NUMBER,
CONSTRAINT pk_rawmaterial_groupid_id PRIMARY KEY (groupid, id)
DROP TABLE object_owner.recipe;
CREATE TABLE object_owner.recipe
GroupID NUMBER NOT NULL,
ID NUMBER NOT NULL,
WEFDate DATE NOT NULL,
ProductID NUMBER NOT NULL,
RawMaterialID NUMBER NOT NULL,
Seq NUMBER NOT NULL,
Quantity NUMBER NOT NULL,
RMCost NUMBER NOT NULL,
CreatedOn DATE,
CreatedBy NUMBER,
UpdatedOn DATE,
UpdatedBy NUMBER,
CONSTRAINT pk_r_gid_pid_rawmaterial_id PRIMARY KEY (GroupID, Seq, productid, rawmaterialID)
CREATE OR REPLACE FUNCTION object_owner.to_index(p_string_to_index IN VARCHAR2) RETURN VARCHAR2
IS
l_temp VARCHAR2(1024);
l_ivar VARCHAR2(1024);
l_tmps VARCHAR2(1);
BEGIN
l_ivar := UPPER(p_string_to_index);
FOR i IN 1..LENGTH(p_string_to_index) LOOP
l_tmps := SUBSTR(l_ivar, i, 1);
IF ((ASCII(l_tmps) BETWEEN 48 AND 57) OR (ASCII(l_tmps) BETWEEN 65 AND 90)) THEN
l_temp := l_temp || l_tmps;
END IF;
END LOOP;
RETURN l_temp;
END;
ALTER TABLE object_owner.product
DROP CONSTRAINT fk_product_groupid;
ALTER TABLE object_owner.product
ADD CONSTRAINT fk_product_groupid FOREIGN KEY (groupid)
REFERENCES object_owner.costgroup(id);
ALTER TABLE object_owner.rawmaterial
DROP CONSTRAINT fk_rawmaterial_groupid;
ALTER TABLE object_owner.rawmaterial
ADD CONSTRAINT fk_rawmaterial_groupid FOREIGN KEY (groupid)
REFERENCES object_owner.costgroup(id);
ALTER TABLE object_owner.recipe
DROP CONSTRAINT fk_recipe_groupid_productid ;
ALTER TABLE object_owner.recipe
ADD CONSTRAINT fk_recipe_groupid_productid FOREIGN KEY (groupid, productid)
REFERENCES object_owner.product(groupid, id);
ALTER TABLE object_owner.recipe
DROP CONSTRAINT fk_recipe_groupid_rmatid;
ALTER TABLE object_owner.recipe
ADD CONSTRAINT fk_recipe_groupid_rmatid FOREIGN KEY (groupid, rawmaterialid)
REFERENCES object_owner.rawmaterial (groupid, id);Yours sincerely
Florian W.
Edited by: Florian W. on 28.07.2009 13:22
Edited by: Florian W. on 28.07.2009 13:29
Edited by: Florian W. on 28.07.2009 13:40
Edited by: Florian W. on 28.07.2009 13:58
Edited by: Florian W. on 28.07.2009 14:10
Edited by: Florian W. on 28.07.2009 14:21 -
Powershell to get SQL Server backup information
Could you please share powershell script to get below information.
T The Server and databases
W-
Whether they are being backed up or not
a-
And when they are being backed up.
It will be great to get all the above 3 details.
MMHi,
Just checking in to see if the suggestion was helpful. Please let us know if you would like further assistance.
TechNet Subscriber Support
If you are
TechNet Subscription
user and have any feedback on our support quality, please send your feedback
here.
Regards, Yan Li -
How to connect to SQL Server through Script Task?
Experts,
I want to do bulk copy from one database to another database (which is on another different box).
I was trying to follow below link,
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.bulkcopytimeout(v=vs.110).aspx
but cannot connect to the source neither to target database.
Can somebody help me with the sample connection string example and also via using existing connection manager?
Thank You
Regards,
gk1393
Please do let us know your feedback. Thank You - KG, MCTSI even tried with your VB code but still package is failing, here is the error message:-
Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'.
Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
at ST_635f3bd1504c4d4c89a902eff277e13c.vbproj.ScriptMain.Main()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
Please do let us know your feedback. Thank You - KG, MCTS -
Backup Failed in SQL server 2008
Backup is failing for only one database on the server.
Msg 3201, Level 16, State 1, Line 1
Cannot open backup device 'F:\databasename_backup_2014_07_29.bak'.
Operating system error 5(failed to retrieve text for this error. Reason: 15105).
Msg 3013, Level 16, State 1, Line 1
BACKUP DATABASE is terminating abnormally.
** SAME DATABASE BACKUP IS COMPLETED SUCCESSFULLY ON OTHER DRIVE **
we have tried the below steps but still it is failed.
Microsoft SQL Server 2008 R2 (SP2) - 10.50.3720.0 (X64) Apr 27 2012 13:51:37 Copyright (c) Microsoft Corporation
Standard Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (Hypervisor)
1.checked for any spaces is th database name --No space
2.added service account to administrator .
3.provided full access to backup folder.
4.Compatibilty is 80 .
5.created backup devide to same location and tried still it got failed.
10 percent processed.
20 percent processed.
30 percent processed.
40 percent processed.
50 percent processed.
60 percent processed.
70 percent processed.
Msg 3202, Level 16, State 1, Line 1
Write on "F:\Data\Backup\New_Backup_databasename.bak" failed: 665(failed to retrieve text for this error. Reason: 15105)
Msg 3013, Level 16, State 1, Line 1
BACKUP DATABASE is terminating abnormally.
6.Changed the database ower to service account,NO luckHi,
How big is database ? Does F drive has enough space on it. Issue does not seems with SQL Server backup it is with F drive or network connecting Server to drives.
Can you give more information about F drive is it a SAN, Local disk ?
If SQL server backup would have been issue it would have not processed uptill 70 % ( unles its bug). First error message with OS error 5 means access denied. Ater then you gave necessary rights and now backup issue is not due to SQL Server but while writing
to F drive some unusual thing is happeing which is causing backup to fail.Can you also involve SAN team as well.
** SAME DATABASE BACKUP IS COMPLETED SUCCESSFULLY ON OTHER DRIVE **
Does this mean backup of same database completes successfully on other drive if so it is a SAN issue or connection issue between SAN and server
Is SQL server 2008 updated to latest service pack ? Why do you use 80 compatibility mode. Although these questions are not realted to backup
Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it.
My TechNet Wiki Articles -
C# application to execute both oracle and sql server script files.
Hi All,
I am suppose to develop an application using c# which can execute oracle script files as well as sql server script files based on some user's choice.
Both the script files(oracle/sql server) contains scripts to create tables, create views and create functions.
What is the best way to do this and which existing c# functions should is use.
Thanks in advance.I am suppose to develop an application using c# which can execute oracle script files as well as sql server script files based on some user's choice.
You can use SQL Plus for Oracle. You can have a C# program that issues commands for scripts for table, views, triggers creation and the whole 10 yards to SQL Plus,
http://docs.oracle.com/cd/B19306_01/server.102/b14357/qstart.htm
https://www.google.com/#q=sql+plus
I started writing a program to use SQL Plus to run the scripts, but cI ame to the conclusion that it was a waste of my time.
A tool called OSM, an Oracle, tool gives a list of script files that need to be run do to a change in a script file based on file timestamp. You can copy the list doing a copy/past operation and drop it into SQL Plus's Command line, and SQL Plus runs the
scripts.
For MS SQL Server, you have this, which you can run from a C# program too.
http://www.webfactory-world.de/wfknowledgebase/wfknowledgebase_wf3.3/Content/AdditionalWindowsSettings/Tutorials/UpdatingSQLDBFromCommandLine.htm
I would consider using the above from a C# program a waste of time too.
I look at it this way. If the user doesn't have database admin experience and know how to use DB admin tools, then they have no business doing anything with a database - period.
BTW, the Invoke statement in VB or C# will run SQL Plus or SQL Server command line tool. -
Why to use SQL Server's native backup facilities, not other backup solution?
I've been asked in my company: why to use SQL Server’s native backup facilities? Instead, they currently rely on other backup software, like Backup Exec, BrightStor, or even Microsoft System Center Data Protection Manager. Those solutions let the
company manage all of its backups—including SQL Server—in a single place, whereas SQL Server’s native backup abilities only apply to SQL Server.
So what does SQL Server native backup facility give us more to be forced to use it?Satish and Pawan ... thanks but, a backup solution is just there. they don't need to pay anything. even though, having a backup solution that backup everything on the server, like files, software.. etc is needed regardless if you have SQL Server databases
or not, and if it does database backup it would be even better and more complete as a backup solution. So sorry your answer is not an enough reason that will force me to leave that complete backup solution and use the SQL Server backup tools specifically to
backup databases.
Olaf ... thanks as well. But I was just counting a number of solutions that i think they are related to backup things. yet I believe that Symantec backup exec does backup for SQL Server database, ain't?! what I understood from the link that you gave me,
that some backup applications (if not all) use SQL Server backup facilities to do database backup, is what I understood correct? if yes then the question will be, is there any situation or reasons that force me to use SQL Server backup tools even if I have
those backup solution (that some of them in the backgroud they are using SQL Server backup facilities)? does SQL Server backup tool give me more capabilities in backing up databases than what I find in backup solutions?
The answer is NO, as of now you get all these features in 3rd party native backups...
So in nutshell Microsoft never forces you to use SQL Servers Native backup -----The only reason why you get native backup featues is since SQL Server is an Enterprise Solution MS provide you all features in-built within the bundle so that you don't have
to purchase any other license (incase you\your company doesn't have one already)
Sarabpreet Singh Anand
SQL Server MVP Blog ,
Personal website
This posting is provided , "AS IS" with no warranties, and confers no rights.
Please remember to click "Mark as Answer" and "Vote as Helpful" on posts that help you. This can be beneficial to other community members reading the thread. -
How to attach .mdf file to sql server 2008 EXPRESS
I have .mdf files created using SQL SERVER management studio 2012 in another computer and wish to attach the same to SQL SERVER 2008 EXPRESS in another computer. How should I do so? I tried this method :How
to: Attach a Database File to SQL Server Express but then it shows an error that the database cannot be created due to compatibility issues.
Msg 948: The database xyz cannot be opened because it is version 706. This server supports version 655 and earlier. A downward path is not supported..
Any help??I have .mdf files created using SQL SERVER management studio 2012 in another computer and wish to attach the same to SQL SERVER 2008 EXPRESS in another computer. How should I do so? I tried this method :How
to: Attach a Database File to SQL Server Express but then it shows an error that the database cannot be created due to compatibility issues.
Msg 948: The database xyz cannot be opened because it is version 706. This server supports version 655 and earlier. A downward path is not supported..
Any help??
You are trying to attach SQL Server 2012 database files to SQL Server 2008 R2 which is not allowed, you either need to upgrade your SQL Server 2008 to 2012 or alternatively you can generate all scripts from SQL Server 2012 and execute it in SQL Server
2008 R2.
You can refer below link to how to generate script.
http://blog.sqlauthority.com/2012/07/18/sql-server-generate-script-for-schema-and-data-sql-in-sixty-seconds-021-video/
Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
Praveen Dsa | MCITP - Database Administrator 2008 |
My Blog | My Page
Maybe you are looking for
-
VGA output on G4 ibook.
Hi, I have had the well documented problem with broken solder joints on the video chip so that the screen does not display properly. http://discussions.apple.com/thread.jspa?threadID=1506226&tstart=0 I have it working and can use it by clamping it to
-
Receiver file adapter NFS - Access directory of other server
HI, I need access from an file adapter type NFS to a shared folder on the SAP ECC server. This is possible?. Users who are connecting to assign permissions on the folder. The 2 servers are on the network and the server is not enabled SAP ECC FTP. All
-
Calling AdvancedDataGridSortItemRenderer with custom header
HI, I have searched for a few hours now no luck... I have an advanced datagrid, with a lot of columns showing small check mark icon for boolean value. To make the columns smaller, I made a simple headerRenderer that rotates the labels 90 degrees, so
-
Ok ive got one of each of the above cameras, I want to be able to view all of them in linksys viewer and recorder utiity, however I can only view the WVC64GA and the WVC54G, it wont let me view the newer camera the "WVC54GCA" -thats with the old link
-
Any way I can stop 9,000 eMails from downloading?
I did not know if this was an iMac desktop question or an iCloud question. I'm quite the oldster amateur. Please advise if there is a better Community for this to be in, and I will try to move it (if that can be done). I have an iCloud account. But h