Query runs in management studio but not in SQLAgent job

I have the following query which runs fine in Management Studio but when I put it in a SQLAgent job it fails saying
Error formatting query, probably invalid parameters (SQLState 42000 Error 22050)I have tried changing Quote characters but to no avail.
Does anybody have any idea why this would be happening?
Regards
Ron
declare @servername nvarchar(150)
 set @servername = @@servername
 declare @mysubject nvarchar(200)
 set @mysubject = 'Toners adjusted out '+@servername+'.'
 EXEC msdb.dbo.sp_send_dbmail @recipients='[email protected]',
 @subject = @mysubject,
 @body = 'Toners were adjusted out. View attachment to see the details',
 @query = 'use livedatabase;select trc_part, trc_job, trc_qty, trc_inits from livedatabase.dbo.Traces
where trc_part like "TONER%"
and CAST(trc_date as date) = CAST(getdate() as date)
and trc_typ = "O"',
 @query_result_width = 600,
 @attach_query_result_as_file = 1

I have another SQLAgent job that is almost identical in what it does, ie sending an email with a query result and it works fine. See below.
Therefore it can't be permissions or dbmail setup but I cannot see what it is.
--== This is for SQL 2005 and higher. ==--
--== We will create a temporary table to hold the error log detail. ==--
--== Before we create the temporary table, we make sure it does not already exist. ==--
 IF OBJECT_ID('tempdb.dbo.ErrorLog') IS Not Null
 BEGIN
 DROP TABLE tempdb.dbo.ErrorLog
 END
 --== We have checked for the existence of the temporary table and dropped it if it was there. ==--
 --== Now, we can create the table called tempdb.dbo.ErrorLog ==--
CREATE TABLE tempdb.dbo.ErrorLog (Id int IDENTITY (1, 1) NOT NULL,
logdate DATETIME, procInfo VARCHAR(10), ERRORLOG VARCHAR(MAX))
--== We create a 3 column table to hold the contents of the SQL Server Error log. ==--
--== Then we insert the actual data from the Error log into our newly created table. ==--
 INSERT INTO tempdb.dbo.ErrorLog
 EXEC master.dbo.sp_readerrorlog
--== With our table created and populated, we can now use the info inside of it. ==--
 BEGIN
--== Set a variable to get our instance name. ==--
--== We do this so the email we receive makes more sense. ==--
 declare @servername nvarchar(150)
 set @servername = @@servername
--== We set another variable to create a subject line for the email. ==--
 declare @mysubject nvarchar(200)
 set @mysubject = 'Deadlock event notification on server
'+@servername+'.'
 --== Now we will prepare and send the email. Change the email address to suite your environment. ==--
 EXEC msdb.dbo.sp_send_dbmail @recipients='[email protected]',
 @subject = @mysubject,
 @body = 'Deadlock has occurred. View attachment to see the deadlock info',
 @query = 'select logdate, procInfo, ERRORLOG from tempdb.dbo.ErrorLog where Id >= (select TOP 1 Id from tempdb.dbo.ErrorLog WHERE ERRORLOG Like ''%Deadlock encountered%'' order by Id DESC)',
 @query_result_width = 600,
 @attach_query_result_as_file = 1
 END
 --== Clean up our process by dropping our temporary table. ==--
 DROP TABLE tempdb.dbo.ErrorLog

Similar Messages

  • Named Query (JOIN query) runs in Toplink JPA but not in EclipseLink

    I have a namedquery in JPA entities like (Entities do not include JOIN colums specifically.. no many-to-many or one-to-many relation in entities)
    select a from table1 a, table2 b where a.id=b.id
    This named query runs on Toplink Essentials without any problem.
    When I run this query using EclipseLink
    EclipseLink generates the query below and gives an error.
    select table1.id, table1.name, table1.surname from table1 t0, table2 t1 where t0.id=t1.id
    There are error _"*table1.surname*"_ is invalid identifier. Because; table1 is not define as an alias, must be "t0.surname".
    How can I solce this problem.
    The code runs on Toplink Essential but not in EclipseLink

    I have a namedquery in JPA entities like (Entities do not include JOIN colums specifically.. no many-to-many or one-to-many relation in entities)
    select a from table1 a, table2 b where a.id=b.id
    This named query runs on Toplink Essentials without any problem.
    When I run this query using EclipseLink
    EclipseLink generates the query below and gives an error.
    select table1.id, table1.name, table1.surname from table1 t0, table2 t1 where t0.id=t1.id
    There are error _"*table1.surname*"_ is invalid identifier. Because; table1 is not define as an alias, must be "t0.surname".
    How can I solce this problem.
    The code runs on Toplink Essential but not in EclipseLink

  • SQL query generating data in SQL management studio but not in CUIC interface

    Hello,
    I'm working on a UCCE 9.0 system
    I created SQL query for a  report.
    Whenever I run the query inside the SQL management studio, it works and generates data, but when I run it in the CUIC interface it works but generates nothing. As you can see in the below snapshot, it contains 209 records that are not being displayed.
    Any help would be greatly apprciated

    Is it a custom report ? Can you right click on your Custom Report and click on Edit Views. You need to check whether you have Grid Headers Listed.
    Regards,
    Senthil

  • Query runs from command line, but not from scheduler

    We use Control-M to schedule shell scripts to be run on a Solaris server. Some of the scripts have to access an Oracle database and in that case our security team will include the DB user and password in the script, then encrypt it and the sys admin team schedules the encrypted shell script with Control-M. That works fine, but we've been trying to have the DB user and password on a separate encrypted file so that we don't have to ask for file encryption every time it's necessary to modify a script (this is a test environment).
    We have the script at ~/system_name/scripts, the query at ~/system_name/sql and the encrypted file and key at ~/system_name/keys. The SQLPlus call in the script is:
    ${ORACLE_HOME}/bin/sqlplus "`decrypt -a 3des -k ./../keys/key.3des.system -i ./../keys/login.system`"@instance_name <<EOF
    @${DIR_SQL}/TEST_QUERY.SQL
    quit
    EOF
    The security analyst has tested is successfully from command line, but when we schedule it with Control-M the job abends and we get the following in the sysout:
    + decrypt -a 3des -k ./../keys/key.3des.system -i ./../keys/login.system
    decrypt: cannot open ./../keys/key.3des.system
    decrypt: invalid key.
    + /u00/app/oracle/product/11.1.0/db_1/bin/sqlplus @instance_name
    + 0<<
    @/sistemas/hmp/system_name/sql/TEST_QUERY.SQL
    quit
    SQL*Plus: Release 11.1.0.6.0 - Production on Mon May 3 09:41:55 2010
    Copyright (c) 1982, 2007, Oracle. All rights reserved.
    SP2-0310: unable to open file "instance_name.sql"
    Enter user-name: SP2-0306: Invalid option.
    Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER|SYSASM}]
    where <logon> ::= <username>[<password>][@<connect_identifier>] [edition=valu\
    e] | /
    SP2-0306: Invalid option.
    Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER|SYSASM}]
    where <logon> ::= <username>[<password>][@<connect_identifier>] [edition=valu\
    e] | /
    Enter password:
    ERROR:
    ORA-12545: Connect failed because target host or object does not exist
    SP2-0157: unable to CONNECT to ORACLE after 3 attempts, exiting SQL*Plus
    0000000080
    Any ideas?

    Looks like the command is being split in some way - the connection to sqlplus is being made before it completes the whole string
    It appears to be seeing the @instance_name as a script to execute rather than a db to connect to.
    Is the database on the same server as the script?
    If so, try setting your environment to the correct databsae, so that you can omit the @instance_name part of the syntax and see if it helps
    Also just noticed the failure to open the decrypt script. It would appear uyou are not using a full path name. Have you checked which directroy the scheduled job starts in? You may need to look at running some environment specific scripts first.
    Edited by: LindaA on 05-May-2010 07:43

  • I am having trouble running videos through Safari but not Google Chrome.  All I get is a black screen.  I have the latest adobe flash update and have enabled plug ins.  any suggestions?

    I am having trouble running videos through Safari but not Google Chrome.  All I get is a black screen.  I have the latest adobe flash update and have enabled plug ins.  any suggestions?

    Open System Preferences > Flash Player then select the Advanced tab.
    Click Delete All under Browsing Data and Settings
    Not empty the Safari cache.
    From your Safari menu bar click Safari > Preferences then select the Advanced tab.
    Select:  Show Develop menu in menu bar
    Now click Develop from the menu bar. From the drop down menu click Empty Caches.
    Now try a video.

  • A javaScript code that runs fine in IE but not in other plz help

    Hello friends,
    plese help me in getting the code for Opera and Mozilla browsers. The following code runs fine in IE but not in other browsers. it show titlebar in other browsers. What to do disable titlebar in other browsers? plz help
    <html>
    <head>
    <script>
    //Frameless Banner Popup
    // Set the url of the banner popup window page
    //var theURL = "index.htm";
    var theURL = "/cgi-bin/login";
    // Set the title of the popup window
    var title = "Login"
    // Set the size of the popup window
    var windowWidth = 350; // cannot be less than 100
    var windowHeight = 350; // cannot be less than 100
    //var windowWidth = window.screen.width; // cannot be less than 100
    //var windowHeight = window.screen.height; // cannot be less than 100
    // Set the position of the popup window
    var windowX = ((window.screen.width/2) - 175);
    var windowY = ((window.screen.height/2) - 175);
    // Set true to auto-center (positions will be ignored)
    var autocenter = false;
    // Set true for popup to close when launch page does
    var autoclose = false;
    var s="width="+windowWidth+",height="+windowHeight;
    var beIE=document.all?true:false;
    var done=new Object("no");
    if(autocenter){
    windowX = (window.screen.width-windowWidth)/2;
    windowY = (window.screen.height-windowHeight)/2;
    function doAgilePopup(){
    if (beIE){
    agilePopper = window.open("","popAgile","fullscreen,"+s);
    agilePopper.blur();
    window.focus();
    agilePopper.resizeTo(windowWidth,windowHeight);
    agilePopper.moveTo(windowX,windowY);
    var frameString=""+
    "<html>"+
    "<head>"+
    "<title>"+title+"</title>"+
    "</head>"+
    "<frameset rows='*,0' framespacing=0 border=0 frameborder=0>"+
    "<frame name='top' src='"+theURL+"' scrolling=no>"+
    "<frame name='bottom' src='about:blank' scrolling='no'>"+
    "</frameset>"+
    "</html>"
    agilePopper.document.open();
    agilePopper.document.write(frameString);
    agilePopper.document.close();
    }else{
    agilePopper=window.open(theURL,"popAgile","scrollbars=no,"+s);
    agilePopper.blur();
    window.focus();
    agilePopper.resizeTo(windowWidth,windowHeight);
    agilePopper.moveTo(windowX,windowY);
    agilePopper.blur();
    if (autoclose){
    window.onunload = function(){agilePopper.close();}
    done="okay";
    </script>
    </head>
    <BODY onLoad="doAgilePopup(),top.window.close()">
    </body>
    </html>

    missing semicolon in end of the variable frameString ,
    better write the string in single line thats easy to find the bugs like this.
    var frameString=""+
    "<html>"+
    "<head>"+
    "<title>"+title+"</title>"+
    "</head>"+
    "<frameset rows='*,0' framespacing=0 border=0 frameborder=0>"+
    "<frame name='top' src='"+theURL+"' scrolling=no>"+
    "<frame name='bottom' src='about:blank' scrolling='no'>"+
    "</frameset>"+
    "</html>"

  • Scrolling Header works in Visual Studio but not on Report Server 2008

    2008 R2 Reporting Services. My scrolling header works in Visual Studio but not when deployed to the Report Server and viewed in IE 9. I have read most every post on this issue and can't find a solution. I have the fixed data properties
    set correctly. Any suggestions?
    Help appreciated! 
    Linda

    Hi Linda,
    As a suggestion, I would try to delete the deployed version and instead of deploying ther RDL file, i would try to upload the file and test it.
    If the issue exisit, then I would download the exisiting version from the reportserver and compare the xml versions of the two reports and check if the propoerty is getting over written while deploying.
    HTH,
    Ram
    Please vote as helpful or mark as answer, if it helps

  • Management Studio Login not possible

    Hello,
    I use BB 10.2.1 and after the latest Update the Management Studio is not accessable. I cannot give in Login Name and Password because thies fields are missing. I only the the drop down menu "Log in using" an this is empty.
    Do you have any ideas?
    Thanks and regards.
    Doreen

    are we talking about BES server?
    how are you accessing BMS and what browser version?
    Click here to Backup the data on your BlackBerry Device! It's important, and FREE!
    Click "Accept as Solution" if your problem is solved. To give thanks, click thumbs up
    Click to search the Knowledge Base at BTSC and click to Read The Fabulous Manuals
    BESAdmin's, please make a signature with your BES environment info.
    SIM Free BlackBerry Unlocking FAQ
    Follow me on Twitter @knottyrope
    Want to thank me? Buy my KnottyRope App here
    BES 12 and BES 5.0.4 with Exchange 2010 and SQL 2012 Hyper V

  • Website page displays and javascript runs correctly in IE8 but not in Firefox 3.6.10

    website page displays and javascript runs correctly in IE8 but not in Firefox 3.6.10

    Can you post a link?
    Then we can take a look.

  • SSIS query returns no results - same query in SQL management studio works

    Hello,
    I'm running a very simple join to get a result set:
    SELECT dbo.sap_contracts.svc_id, dbo.sap_contracts.svc_code, dbo.sap_contracts.quantity, dbo.sap_contracts.start_date, dbo.sap_contracts.end_date
    FROM dbo.sap_contracts
    INNER JOIN dbo.contracts
    ON dbo.contracts.contract_id=dbo.sap_contracts.contract_id
    where customer_name='XXXXXXXXX'
    When I run this in SQL management studio it works fine and returns the list of existing "SAP contracts" in the DB (to compare to the customer's contracts actually in SAP).
    In SSIS (SQL 2012) I'm using an Execute SQL task to run this query and putting the full results set into a variable of type "object". I've done very similar things before and it worked fine. With this query in SSIS I get no results at all. Changing
    the variable type to "string" throws an error showing that the type being written to the variable is "DBNull" - so it seems that the query in SSIS returns no records, when in SQL management studio I get the 15 records that should be returned.
    Does anyone have any ideas of what could be wrong?
    Cheers
    Mark

    There are several connections to the DB in tasks before this one, and the task after this is a whole load of C# in a script task doing SOAP communications to the SAP ERP system to compare the result set from this SQL with the contracts in SAP ERP for the
    specific customer.
    Input variables are all correct (I've checked them about 15 times now with breakpoints on just about every task in the whole package) and I'm at the point of having to test everything in an attempt to see exactly what query is being sent to the SQL server
    and anything else I can do to see why nothing comes back. There is a almost complete lack of debugging tools in SSIS which doesn't make life any easier (something I've heard quite a few times in various forums).
    I'm tearing my hair out on this for half a day now and it's not funny any more, so apologies if I come across as a little frustrated.
    Cheers
    Mark

  • Query editing in Management Studio

    I've accidentally done something to my install of Management Studio that is making query editing very difficult.  I must have used a weird key combination to enable some feature that is now opening an Intellisense like window with suggested keywords
    or column names.  I've tried every option I can find to disable this and even tried all the <ctrl> key combinations from A-Z to try to turn this off.  Can anyone tell me how to have the editor revert to the "default" behavior as installed?
    I've received several replies about disabling Intellisense or changing the Intellisense options and I've already done this to no effect.  I've also not installed any 3rd party tools.  I was editing queries when the problem began and I think I had
    hit a <ctrl> or <alt> key combination key that started this problem.
    I took a screen shot but when I hit the <ctrl> key, the options fade out but hopefully it can still be seen.

    I've accidentally done something to my install of Management Studio that is making query editing very difficult.  I must have used a weird key combination to enable some feature that is now opening an Intellisense like window with suggested keywords
    or column names.  I've tried every option I can find to disable this and even tried all the <ctrl> key combinations from A-Z to try to turn this off.  Can anyone tell me how to have the editor revert to the "default" behavior as installed?
    My guess is that you have installed any third party SQL-Server plug in and which is active. Click on Tools and check if it shows any add-on is there. You need to uninstall it from Control Panel then.
    Cheers,
    Vaibhav Chaudhari
    MCP, MCTS, MCSA (SQL Server 2012)

  • Management studio dialogs not displayed correct in high resolution

    I am using a Lenovo Yoga2 with 3200x1800 screen resolution, and some dialog boxes are not displayed correct, like the Select backup file dialog that doesn't display directory and the file list. Is there any fix for this?

    I'm having the same issue. Let me try to elaborate a little, providing you with more details.
    Laptop, Dell Precision M3800
    Resolution, 3200x1800 (getting more common on new high-end laptops with 15+ inches)
    OS, Windows 8.1
    Application, SSMS aka SQL Server Management Studio - version 2014 (earlier version has same issue)
    SQL Server Engine irrelevant (tested with 2014 and below - all the same)
    I understand you want to see a screenshot, but really, it doesn't make sense as you won't be able to reproduce the error if you are watching on e.g. a FullHD screen. therefore, I've taken a screenshot and resized it to a FullHD size so you get a better feel
    of the issue - however, I have to mention text will look a lot more crisp on a 3200x1800 screen (that's kind of why you want a screen with high PPI). That said, it's still way too small to look at.
    If you view below image on a 15.4 inch screen with FullHD, you get a feel of how I work with SSMS today.
    http: // i.imgur.com / TwOmzjr.png (remove spaces)

  • Abnormal, Same query get data in sql but not working on Fron-end

    Dear,
    Version :Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
    We have created packed in oracle database befor two months ago & was working fine, but since morning select statment in package is not working while running via application which mentioned below and raise not data found but surprising thing is that same query is getting data when we execut on sql plus return one record.
    i don't know either it's abnormal behaviour or sth else becuase the same query run without changing any singl column in where_clause work in sql but not getting data while submition request through oracle application and raising not data found.
    --thankse
    Edited by: oracle0282 on Dec 29, 2011 2:20 AM

    Actully when i run this query in sql it return one record on the same parameter, while when we exeucte this select in pl/sql on the same parameter oracle raise no data found error.
    so i got confused the same query with same parameter retur record in sql but when we call it fron-end through packege raise 'no data found error'.
    hope you understand now.
    --thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Query runs fine in 9i but results to ORA-01652 unable to extend temp in 10g

    Hi,
    We are having issues in running a SQL query in 10g. In 9i, it runs fine with no problems but when run in 10g, It takes forever and the temp tablespace grows very large upto 60GB until we get ORA-01652 error due to lack of disk space. This does not occur in 9i, where query runs in only 20 mins and does not take up temp that big. 9i version is 9.2.0.8. 10g is 10.2.0.3

    Heres the SQL query:
    SELECT
    J2.EMPLID,
    TO_CHAR(J2.EFFDT,'YYYY-MM-DD'),
    J2.EFFSEQ,
    J2."ACTION",
    J2.ACTION_REASON,
    TO_CHAR(J2.GRADE_ENTRY_DT,'YYYY-MM-DD'),
    J2.COMPRATE,
    J2.CHANGE_AMT,
    J2.COMP_FREQUENCY,
    J2.STD_HOURS,
    J2.JOBCODE,
    J2.GRADE,
    J2.PAYGROUP,
    PN2.NATIONAL_ID,
    TO_CHAR(PC.CHECK_DT,'YYYY-MM-DD'),
    SUM(PO.OTH_EARNS),
    To_CHAR(SUM(PO.OTH_EARNS)),
    PO.ERNCD,
    '3',
    TO_CHAR(PC.PAY_END_DT,'YYYY-MM-DD'),
    PC.PAYCHECK_NBR
    FROM PS_JOB J2,
    PS_PERS_NID PN2,
    PS_PAY_OTH_EARNS PO,
    PS_PAY_CHECK PC
    WHERE J2.EMPL_RCD = 0
    AND PN2.EMPLID = J2.EMPLID
    AND PN2.COUNTRY = 'USA'
    AND PN2.NATIONAL_ID_TYPE = 'PR'
    AND J2.COMPANY <> '900'
    AND J2.EFFDT <= SYSDATE
    AND PC.EMPLID = J2.EMPLID
    AND PC.COMPANY = PO.COMPANY
    AND PC.PAYGROUP = PO.PAYGROUP
    AND PC.PAY_END_DT = PO.PAY_END_DT
    AND PC.OFF_CYCLE = PO.OFF_CYCLE
    AND PC.PAGE_NUM = PO.PAGE_NUM
    AND PC.LINE_NUM = PO.LINE_NUM
    AND PC.SEPCHK = PO.SEPCHK
    AND EXISTS (SELECT ERNCD
    FROM PS_P1_CMP_ERNCD P1_CMP
    WHERE P1_CMP.ERNCD = PO.ERNCD AND EFF_STATUS = 'A')
    GROUP BY J2.EMPLID,
    J2.EFFDT,
    J2.EFFSEQ,
    J2.ACTION,
    J2.ACTION_REASON,
    J2.GRADE_ENTRY_DT,
    J2.COMPRATE,
    J2.CHANGE_AMT,
    J2.COMP_FREQUENCY,
    J2.STD_HOURS,
    J2.JOBCODE,
    J2.GRADE,
    J2.PAYGROUP,
    PN2.NATIONAL_ID,
    PC.CHECK_DT,
    PO.ERNCD,
    '3',
    PC.PAY_END_DT,
    PC.PAYCHECK_NBR

  • MQ Series JCA Connector run in Standalone OC4J but not in OAS on Linux

    Hi all,
    My problem is my application run in a Standalone OC4J in Windows and Linux and
    in a Oracle Application Server 10.1.3 in Windows but not run in a Oracle
    Application Server 10.1.3 on Linux why ?
    When i try deploy my application in Oracle Application Server on linux the
    error is throw:MQJMS2005: failed to create MQQueueManager for
    'ms009.queue.manager'
    In Standalone container in linux and windows and in a Oracle Application Server on Windows the deploy is fine.
    I use the same configurations in all containers and only in a OAS 10.1.3 on
    linux my app not run.
    I thank any suggestions!
    Message was edited by:
    Carlos Lacerda

    The JCA Connector to MQ Series run in Oracle Application Server on Linux ??
    Standalone is OK i test but in OAS this run ??
    The only difference entire OC4J configuration used in Standalone and OAS is in opmn.xml, that it is its necessary add a <enviroment> to found the MQ Libraries. Have another difference ??
    tanks

Maybe you are looking for