Create SQL Job with Invoke-Sqlcmd
I'm trying to run a set of .sql files, i didn't know how to pass a common variable to all, so i've started running the statements directly in ps. One of these creates a job but i'm running into all of the errors due to the special characters and the
variables, can someone help?
$Client = "C0212"
$Instance = "SQL03\"+$Client
$sqlscript3 = "
--NEED TO CHANGE THE LOG LOCATION BELOW
USE [msdb]
GO
/****** Object: Job [DatabaseBackup - USER_DATABASES - FULL] Script Date: 11/15/2013 8:40:20 AM ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object: JobCategory [Database Maintenance] Script Date: 11/15/2013 8:40:20 AM ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N''Database Maintenance'' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N''JOB'', @type=N''LOCAL'', @name=N''Database Maintenance''
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
END
DECLARE @jobId BINARY(16)
EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N''DatabaseBackup - USER_DATABASES - FULL'',
@enabled=1,
@notify_level_eventlog=2,
@notify_level_email=0,
@notify_level_netsend=0,
@notify_level_page=0,
@delete_level=0,
@description=N''Source: http://ola.hallengren.com'',
@category_name=N''Database Maintenance'',
@owner_login_name=N''sa'', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object: Step [DatabaseBackup - USER_DATABASES - FULL] Script Date: 11/15/2013 8:40:20 AM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N''DatabaseBackup - USER_DATABASES - FULL'',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N''CmdExec'',
@command=N''sqlcmd -E -S `$(ESCAPE_SQUOTE(SRVR)) -d DBA -Q `"EXECUTE [dbo].[DatabaseBackup] @Databases = ''''USER_DATABASES'''', @Directory = N''''T:\SQLsafe Backups\SQL Native Backup'''', @BackupType = ''''FULL'''',
@Verify = ''''Y'''', @CleanupTime = 170, @CheckSum = ''''Y'''', @LogToTable = ''''Y''''`" -b'',
--NEED TO CHANGE THE LOG LOCATION BELOW
@output_file_name=N''C:\Program Files\Microsoft SQL Server\MSSQL11.$Client\MSSQL\LOG\DatabaseBackup_`$(ESCAPE_SQUOTE(JOBID))_`$(ESCAPE_SQUOTE(STEPID))_`$(ESCAPE_SQUOTE(STRTDT))_`$(ESCAPE_SQUOTE(STRTTM)).txt'',
@flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N''Saturday 4am'',
@enabled=1,
@freq_type=8,
@freq_interval=64,
@freq_subday_type=1,
@freq_subday_interval=0,
@freq_relative_interval=0,
@freq_recurrence_factor=1,
@active_start_date=20131109,
@active_end_date=99991231,
@active_start_time=40000,
@active_end_time=235959,
@schedule_uid=N''5b3c3fcf-28dc-4f4c-95ce-a624667ee378''
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N''(local)''
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:
GO"
Invoke-Sqlcmd –ServerInstance $Instance –Database msdb –Query $sqlscript3 -QueryTimeout 300
So, if I try this:
$Client = "C0212"
Invoke-Sqlcmd -InputFile "C:\NewInstanceScripts\PSNI -3 - Create Full Backup job for ALL User Databases.sql" -Variable $Client
and in my .sql file that line that contains the variable looks like this:
@output_file_name=N'C:\Program Files\Microsoft SQL Server\MSSQL11.`$(Client)\MSSQL\LOG\DatabaseBackup_$(ESCAPE_SQUOTE(JOBID))_$(ESCAPE_SQUOTE(STEPID))_$(ESCAPE_SQUOTE(STRTDT))_$(ESCAPE_SQUOTE(STRTTM)).txt',
I get the error:
Invoke-Sqlcmd : The format used to define the new variable for Invoke-Sqlcmd cmdlet is invalid. Please use the 'var=value' format for defining a new variable.
If i try like this:
Set @Client = "C0212"
Invoke-Sqlcmd -InputFile "C:\NewInstanceScripts\PSNI -3 - Create Full Backup job for ALL User Databases.sql" -Variable @Client
Line in .sql file like this:
@output_file_name=N'C:\Program Files\Microsoft SQL Server\MSSQL11.@Client\MSSQL\LOG\DatabaseBackup_$(ESCAPE_SQUOTE(JOBID))_$(ESCAPE_SQUOTE(STEPID))_$(ESCAPE_SQUOTE(STRTDT))_$(ESCAPE_SQUOTE(STRTTM)).txt',
I get the error: Set-Variable : A positional parameter cannot be found that accepts argument '2'.
Similar Messages
-
Hi,
This might sound really remedial, but can someone explain to me how I go about creating a job with arguments with programs. It errors out when I try to use DEFINE_PROGRAM_ARGUMENTS and when I try to use SET_JOB_ARGUMENTS_VALUE. Maybe it's the order I do it in. Any directions would be much appreciated. Thanks!
TonyHi Tony,
Almost any internal error is an Oracle bug and you should report this to support.
This is definitely not supposed to happen and I haven't seen this error before, do you have a test case throwing the error ?
Using program arguments should be fairly straightforward. Here's a simple example with two varchar2 arguments
-- create a stored procedure with two arguments
create or replace procedure myproc (arg1 in varchar2, arg2 in varchar2)
is BEGIN null; END;
-- create a program with two arguments and define both
begin
dbms_scheduler.create_program
program_name=>'myprog',
program_action=>'myproc',
program_type=>'STORED_PROCEDURE',
number_of_arguments=>2, enabled=>FALSE
dbms_scheduler.DEFINE_PROGRAM_ARGUMENT(
program_name=>'myprog',
argument_position=>1,
argument_type=>'VARCHAR2',
DEFAULT_VALUE=>'13');
dbms_scheduler.DEFINE_PROGRAM_ARGUMENT(
program_name=>'myprog',
argument_position=>2,
argument_type=>'VARCHAR2');
dbms_scheduler.enable('myprog');
end;
-- create a job pointing to a program and set both argument values
begin
dbms_scheduler.create_job('myjob',program_name=>'myprog');
dbms_scheduler.set_job_argument_value('myjob',1,'first arg');
dbms_scheduler.set_job_argument_value('myjob',2,'second arg');
dbms_scheduler.enable('myjob');
end;
Hope this helps,
Ravi.
-Ravi -
Creating backup Job with DBMS_SCHEDULER
Hello,
Can someone please help me out here:
I'm using Oracle10g release 1 on windowsXP
I'm trying to create a backup job with dbms_scheduler and it's not working.
This is what I did:
I created a job as follows:
BEGIN
dbms_scheduler.create_job (
job_name => 'RMAN_FULL',
job_type => 'EXCUTABLE',
job_action => 'E:\wkdir\rman_bkp',
enabled => TRUE,
start_date => '24-NOV-2007 2:10:00 PM',
repeat_interval => 'FREQ=WEEKLY',
comments => 'Full Database Backup');
END;
While rman_bkp is an RMAN command but it wasn't working.
Please where do I get it wrong?
Kindly put me through the EXECUTABLE or should I use PL/SQL_BLOCK and how?
Thanks.
Regards,
CherishHi,
There is a guide to running external jobs using the Scheduler here
Guide to External Jobs on 10g with dbms_scheduler e.g. scripts,batch files
You need to use the full path to a real Windows executable and the arguments to it e.g. for a batch script you would have to do something like
c:\windows\cmd.exe /q /c c:\myscript.bat
There is a forum dedicated to the Scheduler here
Scheduler
Hope this helps,
Ravi. -
Could not create a Job with BI Scheduler
Hi all, we are attempting to create a job but when it runs we receive the following error:
+++ ThreadID: 564 : 2007-06-11 10:10:08.000
Global Error: [nQSError: 77006] Oracle BI Presentation Server Error: Authentication failed.
Error Codes: WKY9UVRD:
Authentication Failure.
Error Codes: IHVF6OM7:OPR4ONWY:U9IM8TAC
Odbc driver returned an error (SQLDriverConnectW).
State: 08004. Code: 10018. [NQODBC] [SQL_STATE: 08004] [nQSError: 10018] Access for the requested connection is refused.
[nQSError: 43001] Authentication failed for Administrator in repository Star: invalid user/password. (08004)
+++ ThreadID: 564 : 2007-06-11 10:10:08.000
...Trying main loop again.
+++ ThreadID: 564 : 2007-06-11 10:10:08.000
... Sleeping for 9 seconds.
+++ ThreadID: 564 : 2007-06-11 10:10:17.000
Global Error: [nQSError: 77006] Oracle BI Presentation Server Error: Authentication failed.
Error Codes: WKY9UVRD:
Authentication Failure.
Error Codes: IHVF6OM7:OPR4ONWY:U9IM8TAC
Odbc driver returned an error (SQLDriverConnectW).
State: 08004. Code: 10018. [NQODBC] [SQL_STATE: 08004] [nQSError: 10018] Access for the requested connection is refused.
[nQSError: 43001] Authentication failed for Administrator in repository Star: invalid user/password. (08004)
+++ ThreadID: 564 : 2007-06-11 10:10:17.000
Terminal Error: Exceeded number of retries.
+++ ThreadID: 564 : 2007-06-11 10:10:08.000
Global Error: [nQSError: 77006] Oracle BI Presentation Server Error: Authentication failed.
Error Codes: WKY9UVRD:
Authentication Failure.
Error Codes: IHVF6OM7:OPR4ONWY:U9IM8TAC
Odbc driver returned an error (SQLDriverConnectW).
State: 08004. Code: 10018. [NQODBC] [SQL_STATE: 08004] [nQSError: 10018] Access for the requested connection is refused.
[nQSError: 43001] Authentication failed for Administrator in repository Star: invalid user/password. (08004)
+++ ThreadID: 564 : 2007-06-11 10:10:08.000
...Trying main loop again.
+++ ThreadID: 564 : 2007-06-11 10:10:08.000
... Sleeping for 9 seconds.
+++ ThreadID: 564 : 2007-06-11 10:10:17.000
Global Error: [nQSError: 77006] Oracle BI Presentation Server Error: Authentication failed.
Error Codes: WKY9UVRD:
Authentication Failure.
Error Codes: IHVF6OM7:OPR4ONWY:U9IM8TAC
Odbc driver returned an error (SQLDriverConnectW).
State: 08004. Code: 10018. [NQODBC] [SQL_STATE: 08004] [nQSError: 10018] Access for the requested connection is refused.
[nQSError: 43001] Authentication failed for Administrator in repository Star: invalid user/password. (08004)
+++ ThreadID: 564 : 2007-06-11 10:10:17.000
Terminal Error: Exceeded number of retries.
Any help?
Thank you.,
Regards.I have the same Problem :-(
In adittion I have an authentivication with LDAP.
If I create the user in the Repository I can connect to it but I receive the following Problem:
+++ ThreadID: 82c : 2007-10-10 12:17:40.000
[nQSError: 77006] Oracle BI Presentation Server Error: A fatal error occurred while processing the request. The server responded with: Odbc driver returned an error (SQLDriverConnectW).
Error Codes: OPR4ONWY:U9IM8TAC
State: 08004. Code: 10018. [NQODBC] [SQL_STATE: 08004] [nQSError: 10018] Access for the requested connection is refused.
[nQSError: 13024] Successful completion of init block 'IB_LDAP' is required. (08004)
If drop the User the Repository and use an LDAP User, I receive the following:
+++ ThreadID: 38c : 2007-10-10 13:13:21.000
[nQSError: 77006] Oracle BI Presentation Server Error: A fatal error occurred while processing the request. The server responded with: Authentication Failure.
Error Codes: IHVF6OM7:OPR4ONWY:U9IM8TAC
Odbc driver returned an error (SQLDriverConnectW).
State: 08004. Code: 10018. [NQODBC] [SQL_STATE: 08004] [nQSError: 10018] Access for the requested connection is refused.
[nQSError: 43001] Authentication failed for ExtOV01 in repository Star: invalid user/password. (08004)
Regards,
Stefan Hess -
I can create SQL Database with Xcode ??
is can posible create a Database with SQL in Xcode ?
-RaulIf you mean, is there some tool integrated into Xcode that will create a database, then the answer is "not that I know of".
Firstly, there are a number of "SQL" databases - e.g. MySQL - and they don't all have the same "flavour" of the SQL syntax. Sure, the basics are there (depending on which 'standard' they confirm to), but usually you want to create a database that has all of the views, indexes, etc. that are as optimised as possible - and that typically means using the additional keywords of the brand of SQL you are using.
Secondly, I an guessing that you are thinking of the Visual Studio capability of creating an MS-SQL database via the 'GUI' interface they provide.
However, there is nothing to stop you from accessing any type of SQL database from your code. I've quite successfully created and then accessed a MySQL database from code that I've written within Xcode. But you have to do all of the work!!!
If I've not understood your question, then perhaps others will correct me, or you can come back with something more.
Susan -
Cannot create SQL database with free trial subscription
Hello,
I get the error message 'The operation is not supported for your subscription offer type.' when trying to create a sql database with my free trial subscription.
Regards
JulianHi Julian,
It should be allowed, please provide steps that you used and ran into this issue. alternatively try these details
step by step instructions to get started.
Hope this helps
Please mark as answered if it helped
Vishal Narayan Saxena http://twitter.com/vishalishere http://www.ogleogle.com/vishal/ -
Running SSIS Package from SQL Job - with Set Values, a string containing";"
Can anybody help with this problem please?
I’m using “set value” in SQL agent to pass in an email address to my SSIS package, if I put in a value of:
[email protected]
It works fine, but if I attempt to input multiple email addresses it fails
[email protected];[email protected]
It doesn’t appear to like the “;”.
Any ideas anyone???
BoroFCHi Jamie, many thanks for the response.
If I look at my command line table when Email = [email protected], it looks like:
/SET "\package.Variables[EmailAddress].Value";"[email protected]" /REPORTING E
If I change the value to “[email protected];[email protected]”, it looks like:
/SET "\package.Variables[EmailAddress].Value";"\""" [email protected];"" [email protected] ""\"" /REPORTING E
But the weird thing is, if I close the job properties window and re-open it again, I lose this line from my set values screen all together!!!
Help ???
BoroFC -
Creating batch job with 5 classes
Hi All,
I have a requirement in which I have to do five different operations at different time instances.
1.Generate a report at morning 11.00 AM.
2.update a table with more than 6000 rows at night 12.30 AM
3.Generate a second report querying from the database at 10.00 AM Everyday.
4.Generate an automail at 11.30 Am Everyday
All these are plain Java classes and not web components. How could I effectively design the batch job so that it doesnot take nmuch memory and design classes so that they must be reusable like DB connection,Getting a db field value frequently etc.
Can any one help me on this.http://www.google.com/search?q=job+schedule+in+java&client=netscape-pp&rls=com.netscape:en-US
-
Creating Oracle Job with Task Scheduler
Hi,
Platform: Oracle10g R2, Windows 2003 Server
I have the below script on my Linux server that backups up the database. It's run via crontab.
--------------- script ---------------------
-- Environment variables goes here
cd $ORACLE_HOME/bin
./rman target / <<EOF
startup mount;
backup database plus archivelog delete input;
delete noprompt obsolete;
alter database open;
I want something similar I can do on windows like .bat file that I can schedule to run via Task Scheduler.
Any help please?
Thnaks and regards,
CreemsHi AG,
I tried to do that but it's not working.
But I did something similar for auto-delete of flashback logs and it works but the backup thing aint working.
What can I do?
Here is what I did for the auto-flashback delete
=======
RunSQL.bat
=======
-- content of RunSQL.bat
@ECHO OFF
TITLE Resetting Flashback Logs
CLS
ECHO Please be patient. This will take some time.
ECHO.
ECHO.
SET ORACLE_SID=PROD
sqlplus.exe /nolog @del_flashback.sql
ECHO.
ECHO.
ECHO FLASHBACKs reset. Please continue with your other procedures.
ECHO.
==========
del_flashback.sql
==========
-- content of del_flashback.sql
connect /nolog
conn sys/oracle as sysdba
SHOW USER
shutdown immediate
startup mount
alter database flashback off;
alter database flashback on;
alter database open;
SHOW USER
exit
This works, but when I did the same with RMAN backup it doesn't.
Any more help please?
Thanks and regards,
Creems -
Creating a job with DBMS_SCHEDULE from Forms?
I'm new to DBMS_SCHEDULER. I'd like to run a stored procedure from an Oracle Forms application passing some parameters from the Form to the procedure, then immediately running the procedure and after the procedure has finished dropping it from the job list. The procedure may take some time to run and the user doesn't want to wait before exiting the form. Can this be done?
Sure, no problem. The job will be dropped after termination by default (autodrop). If privileges are ok it should work. Things to think about are error reporting and retries.
regards,
Ronald
http://ronr.nl/unix-dba -
Need to run SQL jobs with Non Sys-Admin account
Hi Everyone,
We've recently asked to switch our SQL service account from an account having sysadmin permissions to a non sys-admin account. Could you please give us any inputs on this.
Thanks in advance. :)It's a little difficult to understand what you are talking about. First you say:
We've recently asked to switch our SQL service account from an account having sysadmin permissions to a non sys-admin account. Could you please give us any inputs on this.
No, the service account for SQL Server should not be a Windows administrator. It should be a standard Windows account. When you enter this account in SQL Server Configuration Manager, SSCM will assign the required permissions. You should then also assign
the permissions "Lock pages in memory" and "Perform volume maintenance tasks".
But then you start to talk about proxies and whatnots, and this is where you lose me entirely. Could you clarify what you are talking about?
Erland Sommarskog, SQL Server MVP, [email protected] -
Hi All
we are using webservice task in our ssis package and the package is successful in SSDT . when we created SQL job using that package it is failing with webserviceTaskException: Service Description cannot be null.
we have given access to web service for ssis proxy account and have access on wsdl file folder and given access to temp folder .
what would be the reason for the failure?
Surendra ThotaHi Surenda,
As per my understanding, the error message is too general. In order to troubleshoot this issue, we should view the detail error message about this job. For more details, please see:
Troubleshooting Jobs
SQL Server Agent Error Log
Besides, since when you call a Microsoft SQL Server Integration Services (SSIS) package outside a SQL Server Agent job step, the SSIS package runs successfully. However, if you do not modify the SSIS package, then execute it via SQL Server Agent job step,
it fails. The scenario always related to the user account that is used to run the package under SQL Server Agent. Please also verify that the account has access to the Web site or to the Web Service Description Language (WSDL) file for HTTP connection manager.
References:
SSIS package does not run when called from a SQL Server Agent job step
Example using Web Services with SQL Server Integration Services
Thanks,
Katherine Xiong
If you have any feedback on our support, please click
here.
Katherine Xiong
TechNet Community Support -
How to execute SQL Script using windows powershell(using invoke-sqlcmd or any if)
OS : Windows server 2008
SQL Server : SQL Server 2012
Script: Test.sql (T-SQL) example : "select name from sys.databases"
Batch script: windows MyBatchscript.bat ( here connects to sql server using sqlcmd and output c:\Testput.txt)
(sqlcmd.exe -S DBserverName -U username -P p@ssword -i C:\test.sql -o "c:\Testoutput.txt) ---it working without any issues.....
This can execute if i double click MyBatchscript.bat file and can see the output in c:\testput.txt.
Powershell: Similarly, How can i do in powershell 2.0 or higher versions? can any one give full details with each step?
I found some of them online, but nowhere seen clear details or examples and it not executing through cmd line (or batch script).
example: invoke-sqlcmd -Servernameinstance Servername -inputfile "c:\test.sql" | out-File -filepath "c:\psOutput.txt" --(call this file name MyTest.ps1)
(The above script working if i run manually. I want to run automatic like double click (or schedule with 3rd party tool/scheduler ) in Batch file and see the output in C drive(c:\psOutput.txt))
Can anyone Powershell experts give/suggest full details/steps for this. How to proceed? Is there any configurations required to run automatic?
Thanks in advance.Testeted the following code and it's working.....thanks all.
Execute sql script using invoke-sqlcmd with batch script and without batch script.
Option1: using Import sqlps
1.Save sql script as "C:\scripts\Test.sql" script in side Test.sql: select name from sys.databases
2.Save Batch script as "C:\scripts\MyTest.bat" Script inside Batch script:
powershell.exe C:\scripts\mypowershell.ps1
3.Save powershell script as "C:\scripts\mypowershell.ps1"
import-module "sqlps" -DisableNameChecking
invoke-sqlcmd -Servername ServerName -inputFile "C:\scripts\Test.sql" | out-File -filepath "C:\scripts\TestOutput.txt"
4.Run the Batch script commandline or double click then can able to see the output "C:\scripts\TestOutput.txt" file.
5.Connect to current scripts location cd C:\scripts (enter)
C:\scripts\dir (enter )
C:\scripts\MyTest.bat (enter)
Note: can able to see the output in "C:\scripts" location as file name "TestOutput.txt".
Option2: Otherway, import sqlps and execution
1.Save sql script as "C:\scripts\Test.sql" script in side Test.sql: select name from sys.databases
2.Save powershell script as "C:\scripts\mypowershell.ps1"
# import-module "sqlps" -DisableNameChecking #...Here it not required.
invoke-sqlcmd -Servername ServerName -inputFile "C:\scripts\Test.sql" | out-File -filepath "C:\scripts\TestOutput.txt"
3.Connect to current scripts location
cd C:\scripts (enter)
C:\scripts\dir (enter )
C:\scripts\powershell.exe sqlps C:\scripts\mypowershell.ps1 (enter)
Note: can able to see the output in "C:\scripts" location as file name "TestOutput.txt". -
We use SQLcmd to mail output of some sql properties to our administrators
Code, i have as input a txt file with all my sql servers:
FOR /F "tokens=*" %%I IN (%InputFile%) DO (
SET ServerNameFDQN=%%I
ECHO Start Processing %ServerNameFDQN% ...
FOR /F "tokens=1 delims=." %%A IN ("%ServerNameFDQN%") DO (
SET ServerName=%%A
ECHO Read DB Prop
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.txt" -i "%ScriptFolder%\DBProp.sql"
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.csv" -W -s";" -i "%ScriptFolder%\DBProp.sql"
ECHO %ServerName% >> %ScriptOutputFolder%\TotalDBProp.txt
ECHO --------------- >> %ScriptOutputFolder%\TotalDBProp.txt
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.txt >> %ScriptOutputFolder%\TotalDBProp.txt
ECHO. >> %ScriptOutputFolder%\TotalDBProp.txt
ECHO. >> %ScriptOutputFolder%\TotalDBProp.txt
ECHO %ServerName% >> %ScriptOutputFolder%\TotalDBProp.csv
ECHO --------------- >> %ScriptOutputFolder%\TotalDBProp.csv
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.csv >> %ScriptOutputFolder%\TotalDBProp.csv
ECHO. >> %ScriptOutputFolder%\TotalDBProp.csv
ECHO. >> %ScriptOutputFolder%\TotalDBProp.csv
Output to csv (nice in colums):
server001
DATABASE_NAME
DATABASE_SIZE
REMARKS
DATABASE_SERVER
master
37760
NULL
server001
model
22336
NULL
server001
msdb
52416
NULL
server001
db01
162568
NULL
server001
db02
4158016
NULL
server001
db03
149568
NULL
server001
(6 rows affected)
server002
DATABASE_NAME
DATABASE_SIZE
REMARKS
DATABASE_SERVER
master
8640
NULL
server002
model
23360
NULL
server002
msdb
527104
NULL
server002
db01
2548800
NULL
server002
db02
5447488
NULL
server002
db03
777408
NULL
server002
db04
1416960
NULL
server002
tempdb
112640
NULL
server002
(8 rows affected)
This is output per server because sqlcommand accepts a parameter serverinstance
But what i would like is the following output:
DATABASE_NAME
DATABASE_SIZE
REMARKS
DATABASE_SERVER
master
37760
NULL
server001
model
22336
NULL
server001
msdb
52416
NULL
server001
db01
162568
NULL
server001
db02
4158016
NULL
server001
db03
149568
NULL
server001
master
8640
NULL
server002
model
23360
NULL
server002
msdb
527104
NULL
server002
db01
2548800
NULL
server002
db02
5447488
NULL
server002
db03
777408
NULL
server002
db04
1416960
NULL
server002
tempdb
112640
NULL
server002
(14 rows affected)
And i tried to do it with invoke-sqlcmd, but then i don't get the nice colums when i work with export CSV, Anybody got an idea to get the result i want in powershell or in batch if there isn't another option.Hi Aborgeld,
To achieve your requirement, there's some modification on the part of your batch need to make. please see the below code.
REM for the first run sqlcmd, we need to get the dataset with headers(DATABASE_NAME DATABASE_SIZE REMARKS DATABASE_SERVER)
SET isFirstRunflag=1
FOR /F "tokens=*" %%I IN (%InputFile%) DO (
SET ServerNameFDQN=%%I
ECHO Start Processing %ServerNameFDQN% ...
FOR /F "tokens=1 delims=." %%A IN ("%ServerNameFDQN%") DO (
SET ServerName=%%A
ECHO Read DB Prop
IF %isFirstRunflag%==1 (
REM one more sql file "c:\setNocountOn.sql" to get run to remove the row count message like x rows affected
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.txt" -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql"
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.csv" -W -s"," -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql"
SET isFirstRunflag=0
) ELSE (
REM the paramter -h -1 after sqlcmd ignores the headers
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.txt" -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql" -h -1
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.csv" -W -s"," -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql" -h -1
REM ECHO %ServerName% >> %ScriptOutputFolder%\TotalDBProp.txt
REM ECHO --------------- >> %ScriptOutputFolder%\TotalDBProp.txt
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.txt >> %ScriptOutputFolder%\TotalDBProp.txt
REM ECHO. >> %ScriptOutputFolder%\TotalDBProp.txt
REM ECHO. >> %ScriptOutputFolder%\TotalDBProp.txt
REM ECHO %ServerName% >> %ScriptOutputFolder%\TotalDBProp.csv
REM ECHO --------------- >> %ScriptOutputFolder%\TotalDBProp.csv
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.csv >> %ScriptOutputFolder%\TotalDBProp.csv
REM ECHO. >> %ScriptOutputFolder%\TotalDBProp.csv
REM ECHO. >> %ScriptOutputFolder%\TotalDBProp.csv
So the code can be extracted as below
SET isFirstRunflag=1
FOR /F "tokens=*" %%I IN (%InputFile%) DO (
SET ServerNameFDQN=%%I
ECHO Start Processing %ServerNameFDQN% ...
FOR /F "tokens=1 delims=." %%A IN ("%ServerNameFDQN%") DO (
SET ServerName=%%A
ECHO Read DB Prop
IF %isFirstRunflag%==1 (
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.txt" -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql"
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.csv" -W -s"," -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql"
SET isFirstRunflag=0
) ELSE (
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.txt" -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql" -h -1
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.csv" -W -s"," -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql" -h -1
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.txt >> %ScriptOutputFolder%\TotalDBProp.txt
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.csv >> %ScriptOutputFolder%\TotalDBProp.csv
You also have to create a "c:\setNocountOn.sql" with the content "set nocount on" to igore the output like "x rows affected" that affects the expected output.
As I tested, the code works to lead to the expected output in txt and csv. My table has 2 rows and I set the repeat times as 3 to simulate your scenario(my query returns the rows from my table which are different from yours, but what matters is the output format
here).
If you have any question, feel free to let me know.
Best Regards,
Eric Zhang -
SSRS subscription creating duplicate job
We have this sporadic problem where when we go in to save an edit on a SSRS report subscription, it gives us a duplicate job number error. When I look at the Jobs in the Agent, there are duplicates, so I need to manually delete both duplicate jobs,
then the subscription save will work. If we delete just 1 of the jobs, the issue seems to clear for a while, but then reoccurs. This has happened to us on multiple reports, but not consistently. The subscriptions look fine. Has anyone
else run into this? Any ideas what is causing this to happen?I have the issue with version 10.50.1600.1 where one unique subscription ID has created three corresponding SQL jobs with the same name but unique job IDs. When I attempt to execute the job manually via SSMS, i.e. exec
sp_start_job@job_name
=
'0E02285B-4D85-4F5C-92C3-74F44F27B5ED', SQL Server throws the following error:
Msg 14293, Level 16, State 1, Procedure sp_verify_job_identifiers, Line 54
There are two or more jobs named '0E02285B-4D85-4F5C-92C3-74F44F27B5ED'. Specify @job_id instead of @job_name to uniquely identify the job.
So it would be helpful to know the root cause to avoid the same issue in the future.
Thanks,
Ben Lezin
Ben Lezin
Maybe you are looking for
-
Dock doesn't show in full screen Safari
I have the dock set to reveal itself when I go to the bottom of the screen. When I'm in full screen mode in Safari it takes me swiping down at least 3 or 4 times before the dock will appear. I've tried it in other apps on full screen and it still doe
-
My iPod Nano 4thgen only opens when connected to a pc and/or power adapter
My iPod Nano 4thGen. was brand new and I followed each and every step in the manual. I was able to connect to a computer/iTunes but after disconnecting it from the cable, the power just turns off, I pressed any key on it but failed to put the power o
-
X3 browser returns "unsupported content type"
Hi guys. I have a problem. My phone was updated with the v 08.54 but now my browser can not access some sites including the Ovi site. It just returns the error "unsupported content type". Please help.
-
Pic Ratio and Swap Image Behaviour
Alrite guys, iv been picking up my web design skills by developing my own site, and as part of that iv design a gallery with thumbnails circling a central picture. now iv used the swap image behaviour to change the thumnail to the central large pic,
-
Serious crazy problem, need help
Hey I got a serious problem. What do you do if you get the exclamation triangle and it says iTunes cannot read the contents of the iPod ~DANIEL'S IP~. Use the iPod Software Updater application to restore the iPod to factory settings. I think i saved