SQL agent proxy account for Powershell

I am trying to use a sql agent proxy account for PowerShell. Created the ad account, credential and the proxy but because the PowerShell accesses a bunch o sql servers it errors out.Even when I created a login for all the sql servers the powershell is trying
to access it still failed so next I'd need to look at what permissions the powershell ad account needs to the objects it accesses. Is this the correct approach?
What is the best way to go here and avoid using a sysadmin account to run the sql agent powershell job? Thanks!
Paula

Hi,
Please check the error message in job history for details of job failed.
Sysadmin is required or not depends on what you want to achieve on the SQL Server. For example, to execute sp_readerrorlog, the login must be a member of the securityadmin role and it is not required sysadmin.
It does need to create the login(proxy account) on the all the SQL Server instances.
A SQL Server Agent Proxy defines the security context under which different job steps run. The proxy contains the credentials of a Windows user account that does have access to the resources needed by the job. If you have a proxy specified in a job step, SQL
Server Agent will impersonate the proxy account and run the job step while impersonating that user account.
In order to find out the required permission, you may log in with this Windows user account(proxy credential) and run the PowerShell on the local machine and see the result. Alternately, connect in SQL Server Management Studio with this login and see what
permission is required to execute the script.
Thanks.
Tracy Cai
TechNet Community Support

Similar Messages

  • Is there a way to get long running SQL Agent jobs information using powershell?

    Hi All,
    Is there a way to get long running SQL Agent jobs information using powershell for multiple SQL servers in the environment?
    Thanks in Advance.
    --Hunt

    I'm running SQL's to fetch the required details and store it in centralized table. 
    foreach ($svr in get-content "f:\PowerSQL\Input\LongRunningJobsPowerSQLServers.txt"){
    $dt = new-object "System.Data.DataTable"
    $cn = new-object System.Data.SqlClient.SqlConnection "server=$svr;database=master;Integrated Security=sspi"
    $cn.Open()
    $sql = $cn.CreateCommand()
    $sql.CommandText = "SELECT
    @@SERVERNAME servername,
    j.job_id AS 'JobId',
    name AS 'JobName',
    max(start_execution_date) AS 'StartTime',
    max(stop_execution_date)AS 'StopTime',
    max(avgruntimeonsucceed),
    max(DATEDIFF(s,start_execution_date,GETDATE())) AS 'CurrentRunTime',
    max(CASE WHEN stop_execution_date IS NULL THEN
    DATEDIFF(ss,start_execution_date,stop_execution_date) ELSE 0 END) 'ActualRunTime',
    max(CASE
    WHEN stop_execution_date IS NULL THEN 'JobRunning'
    WHEN DATEDIFF(ss,start_execution_date,stop_execution_date)
    > (AvgRunTimeOnSucceed + AvgRunTimeOnSucceed * .05) THEN 'LongRunning-History'
    ELSE 'NormalRunning-History'
    END) 'JobRun',
    max(CASE
    WHEN stop_execution_date IS NULL THEN
    CASE WHEN DATEDIFF(ss,start_execution_date,GETDATE())
    > (AvgRunTimeOnSucceed + AvgRunTimeOnSucceed * .05) THEN 'LongRunning-NOW'
    ELSE 'NormalRunning-NOW'
    END
    ELSE 'JobAlreadyDone'
    END)AS 'JobRunning'
    FROM msdb.dbo.sysjobactivity ja
    INNER JOIN msdb.dbo.sysjobs j ON ja.job_id = j.job_id
    INNER JOIN (
    SELECT job_id,
    AVG
    ((run_duration/10000 * 3600) + ((run_duration%10000)/100*60) + (run_duration%10000)%100)
    +
    STDEV
    ((run_duration/10000 * 3600) + ((run_duration%10000)/100*60) + (run_duration%10000)%100) AS 'AvgRuntimeOnSucceed'
    FROM msdb.dbo.sysjobhistory
    WHERE step_id = 0 AND run_status = 1
    GROUP BY job_id) art
    ON j.job_id = art.job_id
    WHERE
    (stop_execution_date IS NULL and start_execution_date is NOT NULL) OR
    (DATEDIFF(ss,start_execution_date,stop_execution_date) > 60 and DATEDIFF(MINUTE,start_execution_date,GETDATE())>60
    AND
    CAST(LEFT(start_execution_date,11) AS DATETIME) = CAST(LEFT(GETDATE(),11) AS DATETIME) )
    --ORDER BY start_execution_date DESC
    group by j.job_id,name
    $rdr = $sql.ExecuteReader()
    $dt.Load($rdr)
    $cn.Close()
    $dt|out-Datatable
    Write-DataTable -ServerInstance 'test124' -Database "PowerSQL" -TableName "TLOG_JobLongRunning" -Data $dt}
    You can refer the below link to refer out-datatable and write-dataTable function.
    http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/01/use-powershell-to-collect-server-data-and-write-to-sql.aspx
    Once we've the table details, I'm sending one consolidated email to automatically.
    --Prashanth

  • SQL Agent jobs status for multiple servers using Powershell.

    Hi All,
    I am following website link:
    http://www.toadworld.com/platforms/sql-server/b/weblog/archive/2013/09/17/powershell-script-to-monitor-a-service-on-a-group-of-servers-html-formatted-email-output.aspx
    I require to gather status details about all the SQL Agent jobs in the environment on multiple SQL Servers.
    I tried to edit the script using:
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
    $sqlServerName = 'localhost\developer'
    $sqlServer = New-Object Microsoft.SqlServer.Management.Smo.Server($sqlServerName)
    foreach($job in $sqlServer.JobServer.Jobs)
        $job | select Name, OwnerLoginName, IsEnabled, LastRunDate, LastRunOutcome, DateCReated, DateLastModified
    but SQL Agent jobs are not reflecting in the mail output...
    requesting help...!!
    Thanks in Advance.
    Hunt

    I've created a new script for you.  Let me know if you've any questions
    Create the function
    Function Get-SQLJobHTMLReport
    param(
    [String]$ComputerList,[string]$Outputfile,[String]$To,[String]$From,[string]$SMTPMail
    New-Item -ItemType file $Outputfile -Force
    # Function to write the HTML Header to the file
    Function writeHtmlHeader
    param($fileName)
    $date = ( get-date ).ToString(‘yyyy/MM/dd’)
    Add-Content $fileName “<html>”
    Add-Content $fileName “<head>”
    Add-Content $fileName “<meta http-equiv=’Content-Type’ content=’text/html; charset=iso-8859-1′>”
    Add-Content $fileName ‘<title>Service Status Report </title>’
    add-content $fileName ‘<STYLE TYPE=”text/css”>’
    add-content $fileName “<!–”
    add-content $fileName “td {“
    add-content $fileName “font-family: Tahoma;”
    add-content $fileName “font-size: 11px;”
    add-content $fileName “border-top: 1px solid #999999;”
    add-content $fileName “border-right: 1px solid #999999;”
    add-content $fileName “border-bottom: 1px solid #999999;”
    add-content $fileName “border-left: 1px solid #999999;”
    add-content $fileName “padding-top: 0px;”
    add-content $fileName “padding-right: 0px;”
    add-content $fileName “padding-bottom: 0px;”
    add-content $fileName “padding-left: 0px;”
    add-content $fileName “}”
    add-content $fileName “body {“
    add-content $fileName “margin-left: 5px;”
    add-content $fileName “margin-top: 5px;”
    add-content $fileName “margin-right: 0px;”
    add-content $fileName “margin-bottom: 10px;”
    add-content $fileName “”
    add-content $fileName “table {“
    add-content $fileName “border: thin solid #000000;”
    add-content $fileName “}”
    add-content $fileName “–>”
    add-content $fileName “</style>”
    Add-Content $fileName “</head>”
    Add-Content $fileName “<body>”
    add-content $fileName “<table width=’100%’>”
    add-content $fileName “<tr bgcolor=’#CCCCCC’>”
    add-content $fileName “<td colspan=’4′ height=’25′ align=’center’>”
    add-content $fileName “</td>”
    add-content $fileName “</tr>”
    add-content $fileName “</table>”
    # Function to write the HTML Header to the file
    Function writeTableHeader
    param($fileName)
    Add-Content $fileName “<tr bgcolor=#CCCCCC>”
    Add-Content $fileName “<td width=’10%’ align=’center’>ServerName</td>”
    Add-Content $fileName “<td width=’50%’ align=’center’>Name</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>OwnerLoginName</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>IsEnabled</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>LastRunDate</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>LastRunOutcome</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>DateCReated</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>DateLastModified</td>”
    Add-Content $fileName “</tr>”
    Function writeHtmlFooter
    param($fileName)
    Add-Content $fileName “</body>”
    Add-Content $fileName “</html>”
    Function writeDiskInfo
    param($filename,$Servername,$name,$OwnerLoginName,$IsEnabled,$LastRunDate,$LastRunOutcome,$DateCReated,$DateLastModified)
    Add-Content $fileName “<tr>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$servername</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$name</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$OwnerLoginName</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$IsEnabled</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$LastRunDate</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$LastRunOutcome</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$DateCReated</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$DateLastModified</td>”
    Add-Content $fileName “</tr>”
    writeHtmlHeader $Outputfile
    Add-Content $Outputfile “<table width=’100%’><tbody>”
    Add-Content $Outputfile “<tr bgcolor=’#CCCCCC’>”
    Add-Content $Outputfile “<td width=’100%’ align=’center’ colSpan=8><font face=’tahoma’ color=’#003399′ size=’2′><center><strong> SQL Server Agent Job Details</strong></font></td>”
    Add-Content $Outputfile “</tr>”
    writeTableHeader $Outputfile
    #Change value of the following parameter as needed
    Foreach($ServerName in (Get-Content $ComputerList))
    $sqlServer = New-Object Microsoft.SqlServer.Management.Smo.Server($ServerName)
    foreach($item in $sqlServer.JobServer.Jobs)
    Write-Host $sqlServer $item.name $item.OwnerLoginName $item.IsEnabled $item.LastRunDate $item.LastRunOutcome $item.DateCReated $item.DateLastModified
    writeDiskInfo $Outputfile $sqlServer $item.name $item.OwnerLoginName $item.IsEnabled $item.LastRunDate $item.LastRunOutcome $item.DateCReated $item.DateLastModified
    Add-Content $Outputfile “</table>”
    writeHtmlFooter $Outputfile
    Function sendEmail
    param($from,$to,$subject,$smtphost,$htmlFileName)
    [string]$receipients=”$to”
    $body = Get-Content $htmlFileName
    $body = New-Object System.Net.Mail.MailMessage $from, $receipients, $subject, $body
    $body.isBodyhtml = $true
    $smtpServer = $smtphost
    $smtp = new-object Net.Mail.SmtpClient($smtphost)
    $smtp.Send($body)
    write-output “Email Sent!!”
    $date = ( get-date ).ToString(‘yyyy/MM/dd’)
    sendEmail -from $From -to $to -subject “Service Status – $Date” -smtphost $SMTPMail -htmlfilename $Outputfile
    Get-SQLJobHTMLReport -ComputerList f:\powersql\server.txt -SMTPMail hq.abc.com -To [email protected] -From [email protected] -Outputfile F:\Powersql\jobs.htm
    --Prashanth

  • Package hangs when exporting data to Access DB when running under SQL agent & proxy - works fine under BIDS

    Hi all - - I have searched every nook & cranny to find a similar issue, but the ones I have found have not solved my problem.
    I have a simple package that exports data from a SQL database (2008R2) to several Access databases (Client needs them to be mdb, not accdb).  The whole thing works fine in BIDS, but even though we have created a proxy for the SQL agent, the job runs
    without throwing an error, updates the time stamp on the databases, but does not do anything to them.  I created a log file with both the BIDS version & SQL agent version, and the logs look very similar, except that the BIDS one is about 3 times longer.
     The SQL agent one shows no obvious errors or issues.
    I do have the Access database engine installed on both the server where the SQL agent is running as well as my development environment.
    The job does have the 32 bit runtime option checked as well.
    The DBAs are working on the proxy & permissions, and I am wondering if they have missed something in that arena, or if there is something else I may have missed in settings on the package?
    We have been beating on this for days now, so any help would be greatly appreciated.
    Thanks,
    John

    Hi John,
    Not sure what "but does not do anything to them" means, but I believe once you start running your job with a domain account based proxy it must work (JET uses Admin behind the scenes to actually manipulates on the db that needs to be impersonated).
    Arthur My Blog

  • Is it advisable or practical to run SQL Agent with Account from another domain?

    A SQL Server in domain A needs to mount databases downloaded on a weekly basis to a second SQL Server, in domain B.
    Right now, the two domains, which were deliberately separated for security, have no trust.
    Currently, a manager of the server in domain A uses credentials in domain B to logon to domain B and do a file copy of the databases, which he then mounts on the server in domain A.
    Having noticed that the best way to place a copy of a database onto a remote server is via SQL backup, as opposed to a file copy, because it is five times faster, and suspecting that a SQL restoration
    operation might be as much faster than the current file copy from domain B to A, the idea has been floated that the SQL Agent in domain A could schedule a restoration from databases residing on the hard drive of the server in domain B.
    Can credentials of an account in domain B be used to drive the SQL Agent on the server in domain A, and if so, does this require the establishment of a trust? I suspect that it would, although
    once a user of the server in domain A establishes a connection to a file share in domain those credentials are cached for future use.
    Would using an account in domain B to logon the SQL Agent in domain A -- with or without a trust -- cause all the jobs in domain A to fail on the grounds of missing permissions?

    Thank you for your prompt reply.
    The FTP download seems technically feasible. But, I think, the FTP transfer would not provide the speed our organization has been looking for. We are making do with 100Mbps where we actually
    need 1Gbps.
    The SSIS proposal is not feasible because a trust between the two domains would not be allowed. In any event, if it were a straight file copy, not a SQL backup, we would not obtain the speed
    we seek. You mention, in this context, a 'file copy.' Is this a simple copy from an arbitrary TCP port on Server B to port 445 on server A, or is it a different type of copy, such as that used when a SQL runs a backup job to a network destination?
    What do you think of this: in domain B, where the files reside, use the proxy account to run a backup job to the server in domain A. That would give us the speed we need. But that would also
    require a trust, wouldn't it? Is there any way to get around the need for the trust? If the backup job could run from server in domain B to the server in domain A, another job could be setup on server in domain A to complete the restore.
    When I create the SQL Proxy, do I supply the name of the account in the trusting domain?  When I look at the dialog for the creation of the "new proxy account" on a server without trust
    connections, I am offered only two GUIDs as candidate proxies.  Would that change once I create the trust, and would I be allowed to browse accounts in the trusting domain?
    Are you familiar with the dramatic advantage taht a SQL backup job holds over a copy of files from point A to point B? It's something like ten times faster.
    Yours,
    Bob Hindla.

  • Proxy account for Cache group creation

    i have a customer that wants to use a proxy account on the database to create timesten cache group. Schema_owner owns all the base tables and app_user has select,insert,delte,update privs on the base tables as well as private synonym. Customer wants to use app_user account to configure cache connect setting and create cache groups. Is this possible and supported?
    thanks

    It depends on the type of cache group that you are creating. The quick start section of the TimesTen Cache Connect Guide (cacheconnect.pdf) gives full details of the type of Oracle users required, and the privileges they must have.
    Chris

  • Errors running SQL Agent Jobs for 64 bit SSIS packages on a 64 bit server, but Source server 32 bit

    Hi,
    I can able ran the SSIS package in BIDS, since set to false in Run64BitRuntime property.
    Then I created SQL server Agent job I tried the following ways
    Step 1:
    Type is set as SQL Server Integration Services Packages,
    Run as - SQL Server Agent Service Account
    Package source - FileSystem
    then Execution option tab I selected 32 bit runtime
    and then run the job I am getting the below error
    Message
    Executed as user: CIT\svc_CS_SS2008Agent. Microsoft (R) SQL Server Execute Package Utility  Version 11.0.2100.60 for 32-bit  Copyright (C) Microsoft Corporation. All rights reserved.    Started:  7:29:17 AM  Error: 2013-11-28
    07:29:18.57     Code: 0xC0014020     Source: Example Connection manager "DataSource.DataExtract"     Description: An ODBC error -1 has occurred.  End Error  Error: 2013-11-28 07:29:18.57    
    Code: 0xC0014009     Source: Imports20_OAC_Gifts Connection manager "DataSource.DataExtract"     Description: There was an error trying to establish an Open Database Connectivity (ODBC) connection with the
    database server.  End Error  Error: 2013-11-28 07:29:18.59     Code: 0x0000020F     Source: DFT_Example ODBC_SRC Example [11]     Description: The AcquireConnection method call to the connection
    manager DataSource.DataExtract failed with error code 0xC0014009.  There may be error messages posted before this with more information on why the AcquireConnection method call failed.  End Error  Error: 2013-11-28 07:29:18.59    
    Code: 0xC0047017     Source: DFT_Example SSIS.Pipeline     Description: ODBC_SRC Example failed validation and returned error code 0x80004005.  End Error  Error: 2013-11-2
    Step 2:
    Type - Operating sytem (CmdExec)
    Run as - Sql Server agent service account
    Command - C:\Program Files\Microsoft SQL Server\110\DTS\Binn\dtexec.exe /FILE "D:\Example\Example.dtsx" /x86  /CHECKPOINTING OFF /REPORTING E
    then run the job I am getting the below error
    Message
    Executed as user: MIS\svc_CS_SS2008Agent. Microsoft (R) SQL Server Execute Package Utility  Version 11.0.2100.60 for 64-bit  Copyright (C) Microsoft Corporation. All rights reserved.    Started:  6:37:58 AM  Error: 2013-11-28
    06:37:58.94     Code: 0xC0014020     Source: Example Connection manager "DataSource.DataExtract"     Description: An ODBC error -1 has occurred.  End Error  Error: 2013-11-28 06:37:58.96    
    Code: 0xC0014009     Source: Example Connection manager "DataSource.DataExtract"     Description: There was an error trying to establish an Open Database Connectivity (ODBC) connection with the database server. 
    End Error  Error: 2013-11-28 06:37:59.01     Code: 0x0000020F     Source: DFT_Example ODBC_SRC Example [11]     Description: The AcquireConnection method call to the connection manager DataSource.DataExtract
    failed with error code 0xC0014009.  There may be error messages posted before this with more information on why the AcquireConnection method call failed.  End Error  Error: 2013-11-28 06:37:59.07     Code: 0xC0047017    
    Source: DFT_Example SSIS.Pipeline     Description: ODBC_SRC Example failed validation and returned error code 0x80004005.  End Error  Error: 2013-11-28 06:37:59.12     Code: 0xC004700C    
    Source: DFT_Example SSIS.Pipeline     Description: One or more component failed validation.  End Error  Error: 2013-11-28 06:37:59.16     Code: 0xC0024107     Source: DFT_Example     
    Description: There were errors during task validation.  End Error  DTExec: The package execution returned DTSER_FAILURE (1).Started:  6:37:58 AM  Finished: 6:37:59 AM  Elapsed:  1.373 seconds.  Process Exit Code 1. 
    The step failed.
    Note:
    My source server is 32 bit and development environment in 64 bit
    if anybody have idea please share your knowledge

    Hi BIRam,
    Based on the current information, the issue may be caused by the factor that the SQL Server Agent Service Account doesn’t have access to the MySQL server. Try to create a SQL Server Agent Proxy account that has sufficient permission on the MySQL server.
    In addition, also pay attention to the package protection level setting.
    For more information, please see:
    http://social.technet.microsoft.com/Forums/sqlserver/en-US/e13c137c-1535-4475-8c2f-c7e6e7d125fc/how-do-i-troubleshoot-ssis-packages-failed-execution-in-a-sql-agent-job?forum=sqlintegrationservices.   
    Regards,
    Mike Yin
    TechNet Community Support

  • Using Powershell to execute DBCC CheckDB from SQL Agent.

    So, I have a weird situation that I think is tied tot he resource group and powershell, but I am having trouble determining if it is that or not. I run DBCC CheckDB using a resource pool and a secondary account. The account has permissions to do the work
    and if I log onto the server and run the procedure locally it runs fine in the resource pool configuration. However, when I kick it from the SQL Agent job using the powershell step, it only does checkDB on the first 3 system databases and then stops once it
    hits a user database. I am not seeing any errors or messages, it just stops. I ran profiler and I see it do the work, get to the first user database, issues this statement from DBCC, then just stops, and the job ends.
    SELECT @BlobEater = CheckIndex (ROWSET_COLUMN_FACT_BLOB)
    FROM { IRowset 0xD0936A7902000000 }
    GROUP BY ROWSET_COLUMN_FACT_KEY
    >> WITH ORDER BY
      ROWSET_COLUMN_FACT_KEY,
      ROWSET_COLUMN_SLOT_ID,
      ROWSET_COLUMN_COMBINED_ID,
      ROWSET_COLUMN_FACT_BLOB
    OPTION (ORDER GROUP)
     I am not doing anything special in my code that would limit which databases to process. As I said earlier, executing the call to the procedure from a query window runs as expected and processes all of the databases.
    Here is the Agent Code calling powershell:
    [string] $DayOfWeek = ""
    $DayOfWeek = (get-date).DayOfWeek.ToString()
    $DayOfWeek
    if ($DayOfWeek -eq 'Sunday')
    invoke-sqlcmd -database sysadm -serverinstance HQIOSQLDEV01\DEV01 "exec ConsistencyCheck.upConsistencyCheck NULL, 'N', 'Y', 'N', 'N', 'N'"
    else
    invoke-sqlcmd -database sysadm -serverinstance HQIOSQLDEV01\DEV01 "exec ConsistencyCheck.upConsistencyCheck NULL, 'Y', 'N', 'N', 'N', 'N'"
    John M. Couch

    There are 3 additional databases. The last known good is today as I am able to execute the procedure via query window just fine. It is only when executed from a SQL Agent job as above that it stops after only doing the System Databases. The largest database
    is 130GB in size, with the largest table being 62 GB.
    -- Create Procedures
    raiserror('Creating Procedure ''%s''', 0, 1, '[ConsistencyCheck].[upConsistencyCheck]')
    go
    /*==============================================================================
    Procedure: upConsistencyCheck
    Schema: ConsistencyCheck
    Database: SysAdm
    Owner: dbo
    Application: dbo
    Inputs: Catalogue : nvarchar(128) : NULL = All Databases
    Physical Only : nchar(1) : Y/N, NULL = N
    Data Purity : nchar(1) : Y/N, NULL = N
    No Index : nchar(1) : Y/N, NULL = N
    Extended Logical Checks : nchar(1) : Y/N, NULL = N
    Table Lock : nchar(1) : Y/N, NULL = N
    Outputs: (0 = Success, !=0 = failure)
    Result Set: N/A
    Usage: declare @ii_Rc int
    ,@invc_Catalogue nvarchar(128)
    ,@inc_PhysicalOnly nchar(1)
    ,@inc_DataPurity nchar(1)
    ,@inc_NoIndex nchar(1)
    ,@inc_ExtendedLogicalChecks nchar(1)
    ,@inc_TabLock nchar(1)
    select @invc_Catalogue = NULL
    ,@inc_PhysicalOnly = 'Y'
    ,@inc_DataPurity = 'N'
    ,@inc_NoIndex = 'N'
    ,@inc_ExtendedLogicalChecks = 'N'
    ,@inc_TabLock = 'N'
    exec @ii_Rc = ConsistencyCheck.upConsistencyCheck @invc_Catalogue
    , @inc_PhysicalOnly
    , @inc_DataPurity
    , @inc_NoIndex
    , @inc_ExtendedLogicalChecks
    , @inc_TabLock
    print 'Return Code: ' + convert(varchar, @ii_Rc)
    Description: This Procedure is used to run DBCC CheckDB on 1 or all Databases
    on the existing instance.
    Version: 1.00.00
    Compatability: SQL Server 2008 (100)
    Created By: John M. Couch
    Created On: 04-26-2012
    ================================================================================
    Notes
    1. Some logic was taken directly from Ola Hallengren's Maintenance Script.
    http://ola.hallengren.com
    ================================================================================
    History: (Format)
    When Who Version Code Tag What
    04-26-2012 John Couch 1.00.00 (None) Initial Revision
    ==============================================================================*/
    alter procedure ConsistencyCheck.upConsistencyCheck (@invc_Catalogue nvarchar(128)
    ,@inc_PhysicalOnly nchar(1)
    ,@inc_DataPurity nchar(1)
    ,@inc_NoIndex nchar(1)
    ,@inc_ExtendedLogicalChecks nchar(1)
    ,@inc_TabLock nchar(1)) as
    /*==============================================================================
    Variable Declarations & Temporary Tables
    ==============================================================================*/
    declare @li_Rc int = 0
    ,@lnvc_ExecutedBy nvarchar(128) = user_name()
    ,@ldt_ExecutedOn datetime = getdate()
    ,@lnvc_Catalogue nvarchar(128) = @invc_Catalogue
    ,@lnc_PhysicalOnly nchar(1) = coalesce(@inc_PhysicalOnly, 'N')
    ,@lnc_DataPurity nchar(1) = coalesce(@inc_DataPurity, 'N')
    ,@lnc_NoIndex nchar(1) = coalesce(@inc_NoIndex, 'N')
    ,@lnc_ExtendedLogicalChecks nchar(1) = coalesce(@inc_ExtendedLogicalChecks, 'N')
    ,@lnc_TabLock nchar(1) = coalesce(@inc_TabLock, 'N')
    ,@lnvc_Instance nvarchar(128) = cast(serverproperty('ServerName') as nvarchar)
    ,@lnvc_Version nvarchar(40) = cast(serverproperty('ProductVersion') as nvarchar)
    ,@lnvc_Edition nvarchar(40) = cast(serverproperty('Edition') as nvarchar)
    ,@li_Compatibility int
    ,@ldt_CreateDate datetime
    ,@lnvc_UserAccess nvarchar(35)
    ,@lnvc_StateDescription nvarchar(35)
    ,@lnvc_PageVerifyOption nvarchar(35)
    ,@lti_IsReadOnly tinyint
    ,@lti_IsInStandBy tinyint
    ,@lnvc_Recipients nvarchar(2000) = '[email protected]'
    ,@lnvc_Subject nvarchar(128)
    ,@lnvc_ErrorMessage nvarchar(4000)
    ,@lnvc_SQL nvarchar(max)
    ,@lnvc_ManualSQL nvarchar(max)
    ,@lnvc_Query nvarchar(2048)
    ,@li_ConsistencyCheckID int
    ,@ldt_ExecutionStart datetime
    ,@ldt_ExecutionFinish datetime
    declare @ltbl_Catalogue table (Catalogue sysname
    ,CompatibilityLevel int
    ,CreateDate datetime
    ,UserAccess nvarchar(35) -- MULTI_USER, SINGLE_USER, RESTRICTED_USER
    ,StateDescription nvarchar(35) -- ONLINE, RESTORING, RECOVERING, RECOVERY_PENDING, SUSPECT, EMERGENCY, OFFLINE
    ,PageVerifyOption nvarchar(35) -- NONE, TORN_PAGE_DETECTION, CHECKSUM
    ,IsReadOnly tinyint
    ,IsInStandBy tinyint
    ,IsAutoShrink tinyint
    ,IsAutoClose tinyint
    ,Flag bit default 0)
    create table #ltbl_Output (Error int,
    Level int,
    State int,
    MessageText nvarchar(max),
    RepairLevel nvarchar(30),
    Status int,
    DBID smallint,
    ObjectID int,
    IndexID smallint,
    PartitionID bigint,
    AllocunitID bigint,
    [File] int,
    Page int,
    Slot int,
    RefFile int,
    RefPage int,
    RefSlot int,
    Allocation int)
    /*==============================================================================
    Initialize Environment
    ==============================================================================*/
    set nocount on
    set quoted_identifier on
    /*==============================================================================
    Parameter Validation
    ==============================================================================*/
    -- Configure Alert Mail Subject Line
    set @lnvc_Subject = 'Check consistency parameter validation error occurred on ' + cast(@@servername as nvarchar)
    if @lnc_PhysicalOnly not in ('Y','N')
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_PhysicalOnly is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_DataPurity not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_DataPurity is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_NoIndex not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_NoIndex is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_ExtendedLogicalChecks not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_ExtendedLogicalChecks is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_TabLock not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_TabLock is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_ExtendedLogicalChecks = 'Y' and @lnc_PhysicalOnly = 'Y' and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'Extended Logical Checks and Physical Only cannot be used together.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_DataPurity = 'Y' and @lnc_PhysicalOnly = 'Y' and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'Physical Only and Data Purity cannot be used together.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @li_Rc != 0
    goto errlog
    /*==============================================================================
    Code Section
    ==============================================================================*/
    select @lnvc_SQL = N'select d.name, d.compatibility_level, d.create_date, d.user_access_desc, d.state_desc,
    d.page_verify_option_desc, cast(d.is_in_standby as tinyint), cast(d.is_read_only as tinyint),
    cast(databasepropertyex(quotename(d.name), ''IsAutoShrink'') as tinyint),
    cast(databasepropertyex(quotename(d.name), ''IsAutoClose'') as tinyint),
    0
    from master.sys.databases d
    where d.name = ' + case when isnull(@lnvc_Catalogue, '') = '' then ' d.name'
    else '''' + @lnvc_Catalogue + ''''
    end + '
    and d.name != ''tempdb'''
    insert into @ltbl_Catalogue (Catalogue, CompatibilityLevel, CreateDate, UserAccess,
    StateDescription, PageVerifyOption, IsReadOnly, IsInStandBy,
    IsAutoShrink, IsAutoClose, Flag)
    exec sp_executesql @lnvc_SQL
    while (select top 1 1
    from @ltbl_Catalogue c
    where c.Flag = 0) = 1
    begin
    select top 1 @lnvc_Catalogue = c.Catalogue
    ,@li_Compatibility = c.CompatibilityLevel
    ,@ldt_CreateDate = c.CreateDate
    ,@lnvc_UserAccess = c.UserAccess
    ,@lnvc_StateDescription = c.StateDescription
    ,@lnvc_PageVerifyOption = c.PageVerifyOption
    ,@lti_IsReadOnly = c.IsReadOnly
    ,@lti_IsInStandBy = c.IsInStandBy
    from @ltbl_Catalogue c
    where c.Flag = 0
    select top 1 @lnvc_Catalogue
    ,@li_Compatibility
    ,@ldt_CreateDate
    ,@lnvc_UserAccess
    ,@lnvc_StateDescription
    ,@lnvc_PageVerifyOption
    ,@lti_IsReadOnly
    ,@lti_IsInStandBy
    if @lnvc_StateDescription = 'ONLINE' and @lnvc_UserAccess != 'SINGLE_USER'
    begin
    -- Build Execution String
    select @lnvc_SQL = N'dbcc checkdb (' + quotename(@lnvc_Catalogue) + ')' + case when @lnc_NoIndex = 'Y' then ', noindex'
    else ''
    end + ' with tableresults, no_infomsgs, all_errormsgs '
    + case when @lnc_PhysicalOnly = 'Y' then ', physical_only'
    else ''
    end
    + case when @lnc_DataPurity = 'Y' then ', data_purity'
    else ''
    end
    -- Option not supported with Compatibility < 100 (SQL Server 2005 and below)
    + case when @lnc_ExtendedLogicalChecks = 'Y' then
    case when @li_Compatibility = 100 then ', extended_logical_checks'
    else ''
    end
    else ''
    end
    + case when @lnc_TabLock = 'Y' then ', tablock'
    else ''
    end
    -- Prepare Processing Environment
    truncate table #ltbl_Output
    set @ldt_ExecutionFinish = null
    set @ldt_ExecutionStart = null
    -- Capture Start Time.
    set @ldt_ExecutionStart = getdate()
    -- Execute the Command.
    insert into #ltbl_Output(Error, Level, State, MessageText, RepairLevel, Status,
    DBID, ObjectID, IndexID, PartitionID, AllocunitID,
    [File], Page, Slot, RefFile, RefPage, RefSlot, Allocation)
    exec sp_executesql @lnvc_SQL
    -- Capture Completion Time.
    set @ldt_ExecutionFinish = getdate()
    -- Add Header Record to Confirm Execution.
    insert into SysAdm.ConsistencyCheck.ExecutionLog(Instance, [Version], Edition, Catalogue, PhysicalOnly,
    NoIndex, ExtendedLogicalChecks, DataPurity, [TabLock],
    Command, ExecutionStart, ExecutionFinish,
    CreatedOn, CreatedBy)
    values(@lnvc_Instance, @lnvc_Version, @lnvc_Edition, @lnvc_Catalogue, @lnc_PhysicalOnly,
    @lnc_NoIndex, @lnc_ExtendedLogicalChecks, @lnc_DataPurity, @lnc_TabLock,
    @lnvc_SQL, @ldt_ExecutionStart, @ldt_ExecutionFinish,
    @ldt_ExecutedOn, @lnvc_ExecutedBy)
    -- Capture Header Record ID
    select @li_ConsistencyCheckID = @@IDENTITY
    -- Were there errors?
    if (select top 1 1
    from #ltbl_Output t) = 1
    begin
    select @li_ConsistencyCheckID, t.Error, t.Level, t.State, t.MessageText, t.RepairLevel,
    t.Status, t.ObjectID, t.IndexID, t.PartitionID, t.AllocunitID, t.[File], t.Page,
    t.Slot, t.RefFile, t.RefPage, t.RefSlot, t.Allocation, @ldt_ExecutedOn, @lnvc_ExecutedBy
    from #ltbl_Output t
    -- Log Failure Entries
    insert into SysAdm.ConsistencyCheck.ErrorLog (ExecutionLogID, Error, Severity, [State]
    ,ErrorMessage, RepairLevel, [Status], ObjectID
    ,IndexID, PartitionID, AllocationUnitID, FileID
    ,Page, Slot, RefFileID, RefPage, RefSlot, Allocation
    ,CreatedOn, CreatedBy)
    select @li_ConsistencyCheckID, t.Error, t.Level, t.State, t.MessageText, t.RepairLevel,
    t.Status, t.ObjectID, t.IndexID, t.PartitionID, t.AllocunitID, t.[File], t.Page,
    t.Slot, t.RefFile, t.RefPage, t.RefSlot, t.Allocation, @ldt_ExecutedOn, @lnvc_ExecutedBy
    from #ltbl_Output t
    -- Configure Alert Mail Subject Line
    set @lnvc_Subject = 'Consistency Check failure for Database ' + quotename(@lnvc_Catalogue) + ' on Instance ' + quotename(@lnvc_Instance) + ' !'
    set @lnvc_ErrorMessage = 'To view more details, logon to the Instance and execute the query: ' +
    + char(13) + char(10) + char(13) + char(10) +
    'select * from sysadm.consistencycheck.ErrorLog where ExecutionLogID = ' + cast(@li_ConsistencyCheckID as varchar) + ''
    + char(13) + char(10) + char(13) + char(10) +
    'Consistency Check Output: ' +
    + char(13) + char(10)
    select @lnvc_SQL = N'set nocount on;select ltrim(rtrim(ErrorMessage)) as Message
    from SysAdm.ConsistencyCheck.ErrorLog r
    where r.ExecutionLogID = ''' + cast(@li_ConsistencyCheckID as nvarchar(128)) + ''''
    exec msdb.dbo.sp_send_dbmail @profile_name = 'SQL Mailbox',
    @recipients = @lnvc_Recipients,
    @subject = @lnvc_Subject,
    @body = @lnvc_ErrorMessage,
    @query = @lnvc_SQL,
    @execute_query_database = @lnvc_Catalogue,
    @query_result_header = 1,
    @query_result_width = 32767,
    @query_no_truncate = 1,
    @body_format = 'TEXT',
    @importance = 'High'
    end
    end
    else
    begin
    -- If we get here, then the database was not processed due to it having a status other than ONLINE, being in SINGLE_USER mode or
    -- having a compatability level < 100
    set @lnvc_Subject = 'Unable to perform consistency checks for Database ' + quotename(@lnvc_Catalogue) + ' on ' + quotename(@lnvc_Instance) + '!'
    set @lnvc_ErrorMessage = 'One of the following conditions was not met. ' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) +
    '* Database must be ONLINE. It''s current state is: ' + @lnvc_StateDescription + CHAR(13) + CHAR(10) +
    '* Database access level cannot be set to SINGLE_USER. It''s current access level is: ' + @lnvc_UserAccess
    exec msdb.dbo.sp_send_dbmail @profile_name = 'SQL Mailbox',
    @recipients = @lnvc_Recipients,
    @subject = @lnvc_Subject,
    @body = @lnvc_ErrorMessage,
    @body_format = 'TEXT',
    @importance = 'High'
    end
    update t
    set Flag = 1
    from @ltbl_Catalogue t
    where t.Catalogue = @lnvc_Catalogue
    end
    /*==============================================================================
    Cleanup Temp Tables
    ==============================================================================*/
    cleanup:
    if object_id('tempdb..#ltbl_Output') is not null
    drop table #ltbl_Output
    /*==============================================================================
    Exit Procedure
    ==============================================================================*/
    quit:
    return @li_Rc
    /*==============================================================================
    Error Processing
    ==============================================================================*/
    errlog:
    -- Raise Error, and write to Application Event Log
    raiserror (@lnvc_ErrorMessage, 16, 1) with log, nowait
    -- Send Email Notification of Error
    exec msdb.dbo.sp_send_dbmail @profile_name = 'Mailbox',
    @recipients = @lnvc_Recipients,
    @subject = @lnvc_Subject,
    @body = @lnvc_ErrorMessage,
    @importance = 'High'
    goto cleanup
    go
    John M. Couch

  • Sql agent jobs based on the database and the user

    Dear All,
    I have a requirement of configuring an user who should only have access to one database out of all and also able to create, view and modify sql agent jobs only for the allowed database. For allowing to see the selected database to particular user I have
    granted permissions as per below,
    create LOGIN mhtc WITH PASSWORD='mhtc', CHECK_POLICY = OFF;
    USE master;
    GO
    DENY VIEW ANY DATABASE TO mhtc;
    USE master;
    GO
    ALTER AUTHORIZATION ON DATABASE::MHTC TO mhtc;
    GO
    but user not able to see sql agent jobs so I want to give necessary permission to this user to view,create and modify sql agent jobs only in allowed databases. Basically I want to separate users from each database and separate sql agent jobs based on the
    user and database.
    Your expert advices are highly appreciated.
    Thanks,
    Manjula

    I want to give necessary permission to this user to view,create and modify
    sql agent jobs only in allowed databases.
    Hello Manjula,
    SQL Server Agent Jobs are not created / dedicated for a user database. The Jobs are store in System database "msdb".
    See
    Implement SQL Server Agent Security for Details about required permissions.
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • SQL Agent and Oracle Error

    Hello,
    This is the error I'm getting:
    Oracle client and networking components were not found. These components are supplied by Oracle Corporation and are part of the Oracle Version 7.3.3 or later client software installation. Provider is unable to function until these components are installed.
    I only have ODAC installed and that's all, not the full-blown Oracle database. This is on a Windows Server 2003 (32-bit) Developing on this server was fine, I could run packages within BIDS, create a deployment utility and actually run the package from Integration Services, it's when creating a SQL Agent Job and trying to execute the steps where I get the above error.
    Any advice would be appreciated.
    Thanks.

    SQL Agent is a SQL Server tool... it is looking for an extremely old version of the Oracle client, one that is no longer supported. Since this is the support forum for the Visual Studio tools, I don't know anything about that.
    Based on the fact that SQL Agent is looking for such old software, I would naively suggest:
    1) Upgrade SQL Agent to a new version
    2) If you do not intend it to connect to Oracle anyway, try to find out where in the configuration it is attempting to do so.

  • Service Account for SQL Server Agent on SQL Server 2008 R2

    This SQL Server instance is SQL Server 2008 R2 (10.50.4000).  We had Active Domain Service accounts created to run the service accounts for SQL Server and SQL Server Agent.
    It has become company policy to alter the service accounts that run SQL Server and SQL Server Agent.  Currently, both were running under the Local System Accounts.  We have altered the SQL Server but we are having issues with the SQL Server Agent. 
    I am told by another DBA that
    "The agent is requiring elevated rights.  It will startup if it has local admin rights, but not with domain accounts without admin rights."
    So I was wondering if anyone has come across this issue and how did they resolve it.
    lcerni

    "The agent is requiring elevated rights.  It will startup if it has local admin rights, but not with domain accounts without admin rights."
    This is completely not true. It is indeed possible to run agent as a domain account without giving it local admin. Chances are you'll need to update the local acls by adding the account to the local security groups. Please see this article for more information:
    http://technet.microsoft.com/en-us/library/ms143504(v=sql.105).aspx
    Edit: In addition, it'll need rights to SQL server for that account to connect and do its work. It will need to be given sysadmin:
    http://technet.microsoft.com/en-us/library/ms191543.aspx
    Sean Gallardy | Blog |
    Twitter

  • Error Using New-WebServiceProxy cmdlet with SQL Agent Powershell Subsystem

    I created a powershell script to connect to SSRS via web service so I can cache reports in the database and expose them directly through our application. The script works fine when I run it through Powershell directly, but when I try running it through the
    SQL Agent Powershell subsystem I am getting a strange error:
    "A job step received an error at line 61 in a PowerShell script. The corresponding line is '$RS = New-WebServiceProxy -Class 'RS' -Namespace 'RS' -Uri $reportServerURI -UseDefaultCredential  '. Correct the script and reschedule the job. The error
    information returned by PowerShell is: 'Could not load file or assembly 'file:///C:\WINDOWS\TEMP\yfqiivtg.dll' or one of its dependencies. The system cannot find the file specified.  '.  Process Exit Code -1.  The step failed."
    I am using SQL Server 2014, SSRS 2014, Windows 8.1. The only difference I can think of is that when I run Powershell from the OS, I am using v 4.0 whereas when I run it from SQL Agent it loads v 2.0. My understanding is that v 2.0 supports the New-WebServiceProxy
    cmdlet, so I'm not convinced the version discrepancy is the culprit. Any ideas what might be causing this?
    On a side note, is there a way to have SQL Agent use Powershell 4.0 for the subsystem? v 2.0 feels a little dated for SQL Server 2014.

    Hi WilliamW,
    When creating a PowerShell job step, there is only one security context available, which is the "SQL Server Agent Service Account." That means that if you intend to execute PowerShell scripts from SQL Agent Job steps, the SQL Server Agent
    service account must have appropriate permissions.
    According to your error message, I recommend to check if the SQL Server Agent service account has access to the folder where the scripts live, as well as the folder C:\WINDOWS\TEMP.
    In addition, when we execute a PowerShell job step in SQL Server, SQL Server Agent subsystem run the sqlps utility, and the sqlps utility launches PowerShell 2.0 and imports the sqlps module. If you need to run a PowerShell v4.0 script from a SQL Server
    Agent job, you can create a proxy account to run the agent job which contains PowerShell script. For more details, please review this similar blog:
    Run a PowerShell v3 Script From a SQL Server Agent Job.
    Thanks,
    Lydia Zhang

  • SQL Agent Job failing - not using credentials in the config file for Data source

    Hi
    We have an SSIS pkg, that is secheduled as SQL Agent job using proxy account. The pkg contanins data source for connecting different SQL servers and the proxy account do not have access to the external DBs. The data source credentials are stored in the Config
    file.
    Why the job is not using the credentials in the config file and try to use the proxy account and failing.
    Do the proxy account need access to all the external dbs in the pkg, and then what is the purpose of the config file.
    I am sorry, i am not SSIS person trying to understand. If any one can explain tha will be great!!
    Thank you!
    VR

    Please take a look at these URLs:
    Schedule a Package by using SQL Server Agent
    SSIS package does not run when called from a SQL Server Agent job step
    Cheers,
    Saeid Hasani
    Database Consultant
    Please feel free to contact me at [email protected] as well as on Twitter and Facebook.
    [My Writings on TechNet Wiki] [T-SQL Blog] [Curah!]
    [Twitter] [Facebook] [Email]

  • How to Create a SQL Agent Job For A SSIS Package with Sql Server Authentication

    Hi ALl,
    I have a SSIS package which basically has a data flow task in which i pull the data from one server and copy it into another server and my source server is the one where i dont have windows authentication and i have to only use a sql server authentication
    . This package runs fine if i click the server connection properties type the password and save it.
    Now, my task is to set up a sql agent job which basically uses a proxy account and takes this package from the file system and runs it.But when i try to run this package, its failing with an error saying 
    "Login Failed For rpt5user" where rpt5user is the username for my sql server authentication of the source connection.
    Can someone please help me with any suggestions on how to do this?
    I have heard that we can achieve it by using xml config file which i have never used and i am trying to google around but for no luck.
    So, If someone can please throw any suggestions or ideas on this it would be great.
    Thanks

    You need to add password as a config item and set it from the file source or sql table
    see this as an example
    http://blogs.msdn.com/b/runeetv/archive/2009/12/22/ssis-package-using-sql-authentication-and-dontsavesensitive-as-protectionlevel.aspx
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • SQL Agent Permssions With SSIS for each loop not looping through files

    Hi I am Having trouble getting a ssis package to iterate through a file directory using a proxy account set up in Sql Server.
    So I have a package that loops over csv files. If I run the package manually or set the sql agent job to run as Sysadmin the pakage runs fine all files are processed.
    However if I use the proxy account. the package completes but no files are processed. there are no failures, there is no error handling set up in the control flow. the for each loop container simply does not recognise any files when run under a proxy.
    Note: the proxy is set up with credentials to access the folder. the credential is also set up with the server admin server role... still nothing
    i'm not sure is this is a ssis or permissions problem?
    Any comments will be appreciated

    Can you check this and see if you've configured all the steps correctly
    http://www.mssqltips.com/sqlservertip/2163/running-a-ssis-package-from-sql-server-agent-using-a-proxy-account/
    Also enable logging in package and see if you're getting any error messages obtained in output table/file based on the logging option you chose.
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Maybe you are looking for