SQL script based on hostname and database name?

I am trying to write a script that I can run on several unix servers and databases that will do different sql statements based on which server and database it is being run in.
Something like:
if hostname = 'A' and database name = 'D' then do this
else if hostname = 'B' and database name = 'F' then do that
I have tried many diifferent combinations of shell scripts and sql scripts but can't seem to get anything that works.
Can someone help me out? Thanks.

Since you are already able to get he db and host info, you are well on your way to branching based on that information. All you need is the basic framework:
declare
  db VARCHAR2(30);
  host VARCHAR2(30);
  sqlcmd VARCHAR2(4000);
begin
  select sys_context('userenv','host') host
       , sys_context('userenv','db_name') db_name
    into host
       , db
    from dual;
  case
    when db = 'XE' and host = 'mypc' then
      sqlcmd := q'[local_package.do_something('parm1', :db, :host)]';
      execute IMMEDIATE sqlcmd USING db, host;
    when db = 'DEV' and host in ('serv1','serv2') then
      sqlcmd := q'[different_packge.do_something('parm1', :db, :host)]';
      execute IMMEDIATE sqlcmd USING db, host;
    else
      dbms_output.put_line('unrecognized db/host combination: '||db||', '||host);
  end case;
end;
/In this example I've used dynamic SQL since not all instances are guaranteed to have any or all of the package procedures referenced in the dynamic sql. With out the dynamic sql, you would get errors and be unable to run the script on any instance lacking one or more of the reference package procedures..

Similar Messages

  • Out of memory Error while querying SQL Script based Calculation View

    Hi All,
    I wanted to test the performance of Graphical and SQL Script based Calculation views.
    Created Graphical (CA_GRPH) and SQL Script (CA_SQL) Calculation views.
    Analytic View (AN_GRPH) for both Calculation views are the same which is Graphical based (90 Attributes and 5 Measures)
    In Analytic View data foundation I have a Fact table which has 1.5 Billion records and 9 Dimension Tables –collectively 500 million records (7 Attribute Views). 9 Referential joins with cardinality N:1 and 1 Referential join with cardinality N:N.
    I wanted to keep (CA_GRPH) and (CA_SQL) as a base Calculation views and leverage those to create various calculation views (Will be creating different Calc views for respective Business segments)
    In order to test this I have created below calc views on top of base calc views.
    Graphical Based: Created (CA_GRAPH_XYZ) by having CA_GRPH in projection with 30 Calculated Columns. – This retrieves data in 13 secs
    SQL Script Based: Created (CA_GRPH_ABC) by having CA_SQL in projection view with 30 calculated columns – This errors out after 1.50 mins.
    Could not execute 'SELECT "COLUMN_A","COLUMN _B"," COLUMN _C"," COLUMN _D", SUM("COLUMN _REVENUE") AS ...' in 1:50.480 minutes .
    SAP DBTech JDBC: [2048]: column store error:  [2048] column store error: search table error: [1000002] Error executing physical plan: exception 1000002:
    ltt/impl/memory.cpp:63
    Out of memory ; $size$=1507711; $name$=ihm; $type$=pool; $inuse_count$=170104; $allocated_size$=219215007925
    exception 1000002:
    Any suggestion / help in fixing this issue will be greatly appreciated.
    Regards,
    Av

    Hi Raj,
    Thanks for your time, please find edited snap hot of Analytic View (AN_GRPH) below,
    Calculation view(CA_SQL)
            /********* Begin Procedure Script ************/
    BEGIN
           var_out =
         SELECT
                "COLUMN_1"
                "COLUMN_2",
                "COLUMN_84",
                "COLUMN_85;",
                SUM("REVN") AS "REVN",
                SUM("MGN") AS "MGN",
                SUM("ORD_QTY") AS "ORD_QTY",
                SUM("SYS_QTY1") AS "SYS_QTY1",
                SUM("SYS_QTY") AS "SYS_QTY"
    FROM
          "_SYS_BIC"."XYZ/AN_GRPH"
    GROUP BY
                "COLUMN_1"
                "COLUMN_2",
                "COLUMN_84",
                "COLUMN_85";
    END
    /********* End Procedure Script ************/
    Later i have built one more Calculation view(CA_GRPH_ABC) using (CA_SQL)in projection. i have 30 calculated measures in this final calc view. this final calc view is throwing above mentioned error.
    Not sure if i can use SQL script based calc view in graphical based calc views?
    Regards,
    AV

  • How to generate sql script based on table structure

    I want to generate a sql script based on a table structure.
    For example:
    if the table is:
    cid id c_value
    1 1 zz
    2 1 yy
    3 2 zz
    4 2 xx
    5 3 ss
    6 3 tt
    The expected output is:
    WITH
    CHILD_tab as (
    SELECT 1 cid, 1 id,'zz' c_value from dual union all
    SELECT 2 cid, 1 id,'yy' c_value from dual union all
    SELECT 3 cid, 2 id,'zz' c_value from dual union all
    SELECT 4 cid, 2 id,'xx' c_value from dual union all
    SELECT 5 cid, 3 id,'ss' c_value from dual union all
    SELECT 6 cid, 3 id,'tt' c_value from dual )
    Release 11.1.0.7.0

    I'm doing a lot of XML these days (too much perhaps) so here's a solution involving XQuery.
    We pass a query string and it outputs a CLOB containing the WITH clause :
    SELECT DBMS_XMLGEN.Convert(
    XMLQuery(
    q'[concat(
    "WITH t AS (
    string-join(
    for $i in /ROWSET/ROW
    return concat( " SELECT ",
                    string-join($i/*/concat("'",ora:replace(text(),"'","''"),"' ",local-name()),", "),
                    " FROM dual" ),
    " UNION ALL
    passing dbms_xmlgen.getXMLType('SELECT * FROM scott.emp')
    returning content
    ).getClobVal(), 1) AS WITH_CLAUSE
    FROM dual;
    WITH_CLAUSE
    WITH t AS (
    SELECT '7369' EMPNO, 'SMITH' ENAME, 'CLERK' JOB, '7902' MGR, '17/12/80' HIREDATE, '800' SAL, '20' DEPTNO FROM dual UNION ALL
    SELECT '7499' EMPNO, 'ALLEN' ENAME, 'SALESMAN' JOB, '7698' MGR, '20/02/81' HIREDATE, '1600' SAL, '300' COMM, '30' DEPTNO FROM dual UNION ALL
    SELECT '7521' EMPNO, 'WARD' ENAME, 'SALESMAN' JOB, '7698' MGR, '22/02/81' HIREDATE, '1250' SAL, '500' COMM, '30' DEPTNO FROM dual UNION ALL
    SELECT '7566' EMPNO, 'JONES' ENAME, 'MANAGER' JOB, '7839' MGR, '02/04/81' HIREDATE, '2975' SAL, '20' DEPTNO FROM dual UNION ALL
    SELECT '7654' EMPNO, 'MARTIN' ENAME, 'SALESMAN' JOB, '7698' MGR, '28/09/81' HIREDATE, '1250' SAL, '1400' COMM, '30' DEPTNO FROM dual UNION ALL
    SELECT '7698' EMPNO, 'BLAKE' ENAME, 'MANAGER' JOB, '7839' MGR, '01/05/81' HIREDATE, '2850' SAL, '30' DEPTNO FROM dual UNION ALL
    SELECT '7782' EMPNO, 'CLARK' ENAME, 'MANAGER' JOB, '7839' MGR, '09/06/81' HIREDATE, '2450' SAL, '10' DEPTNO FROM dual UNION ALL
    SELECT '7788' EMPNO, 'SCOTT' ENAME, 'ANALYST' JOB, '7566' MGR, '19/04/87' HIREDATE, '3000' SAL, '20' DEPTNO FROM dual UNION ALL
    SELECT '7839' EMPNO, 'KING' ENAME, 'PRESIDENT' JOB, '17/11/81' HIREDATE, '5000' SAL, '10' DEPTNO FROM dual UNION ALL
    SELECT '7844' EMPNO, 'TURNER' ENAME, 'SALESMAN' JOB, '7698' MGR, '08/09/81' HIREDATE, '1500' SAL, '0' COMM, '30' DEPTNO FROM dual UNION ALL
    SELECT '7876' EMPNO, 'ADAMS' ENAME, 'CLERK' JOB, '7788' MGR, '23/05/87' HIREDATE, '1100' SAL, '20' DEPTNO FROM dual UNION ALL
    SELECT '7900' EMPNO, 'JAMES' ENAME, 'CLERK' JOB, '7698' MGR, '03/12/81' HIREDATE, '950' SAL, '30' DEPTNO FROM dual UNION ALL
    SELECT '7902' EMPNO, 'FORD' ENAME, 'ANALYST' JOB, '7566' MGR, '03/12/81' HIREDATE, '3000' SAL, '20' DEPTNO FROM dual UNION ALL
    SELECT '7934' EMPNO, 'MILLER' ENAME, 'CLERK' JOB, '7782' MGR, '23/01/82' HIREDATE, '1300' SAL, '10' DEPTNO FROM dual
    )It may be useful for small data sets only because we quickly hit ORA-01706.

  • How to execute sql scripts from Powershell across multiple databases

    Re: How to execute sql scripts from Powershell across multiple databases
    I have an tsql script that I want to run across a list of databases. How is the best way to do this in Powershell? Thanks.

    My example below, using just the SMO and not breaking up the batches, the ExecuteWithResults give the following error when the .sql file contains a GO. My script files are as simple as a DECLARE and then a GO.
    WARNING: SQL Script Failed
    The object of type "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" is not valid or not in the correct sequence. This is likely caused by a user-specified "format-list" comm
    and which is conflicting with the default formatting.
        + CategoryInfo          : InvalidData: (:) [out-lineoutput], InvalidOperationException
        + FullyQualifiedErrorId : ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand
    Also, when executing from the ISE, is there a way to force the ISE to release the files. I am having to close the ISE and reopen my script every time I want to make a testing change to the .sql file.
    [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
    $scriptspath = "C:\temp\psExecuteSQLScripts\scripts"
    $SQLServer = "fidevc10"
    $SQLDB = "Bank03"
    # Create SMO Server Object
    $Server = New-Object ('Microsoft.SQLServer.Management.Smo.Server') $SQLServer
    # Get SMO DB Object
    $db = $Server.Databases[$SQLDB]
    # Load All SQL Scripts in Directory
    $scripts = Get-ChildItem -Path (Join-Path $scriptspath "*") -Include "*.sql" -Recurse
    # Loop through each script and execute
    foreach ($SQLScript in $scripts)
    $fullpath = $SQLScript.FullName
    # Read the Script File into Powershell Memory
    $reader = New-Object System.IO.StreamReader($fullpath)
    $script = $reader.ReadToEnd()
    # Execute SQL
    Write-Host "Executing $SQLScript on $SQLDB...."
    try
    $ds = $db.ExecuteWithResults($script)
    Foreach ($t in $ds.Tables)
    Foreach ($r in $t.Rows)
    Foreach ($c in $t.Columns)
    Write-Host $c.ColumnName "=" $r.Item($c)
    Write-Host "Complete"
    catch [Exception]
    Write-Warning "SQL Script Failed"
    echo $_.Exception|format-list -force
    Write-Host " " -BackgroundColor DarkCyan

  • How to change IP, Hostname and domain name for Oracle Application R12

    Hi,
    I'm new to Oracle, we used to have one production and one test server for Oracle Application R12, but the test server was corrupted, so we decided to clone production server and create a new test server, after cloning and creation of test server, how should we do to change IP address, hostname and domain name for test server?
    Our production and test server environment is:
    Linux Enterprise AS 2.6.9
    Application module: E-Business Suite Treasury only
    Your advice will be much appreciated.
    Regards,
    Kenneth
    Edited by: 850209 on Apr 7, 2011 5:37 PM

    850209 wrote:
    Hi,
    There are few tnsnames.ora and listener.ora files in the system, how to know which one are effective? If I change tnsnames.ora hostname entry, do I need to change listerner.ora file also?
    Thanks.
    Regard,
    Kenneth.tnsnames.ora is used only by client processes. listner.ora is used only to configure the listener, and that is a server side issue only. In addition, the listener can start without any listener.ora at all, using all default values. See my discussion of tns issues at edstevensdba.wordpress.com
    If you are using dbcontrol, you will most likely need to reconfigure it, using the emca utility.

  • Generating SQL Script for Existing Tables and DBs

    Hello,
    is it possible to generate automatically a SQL-Script from an existing table or oracle database ?
    I want to export an existing table from an Oracle DB (g11) if its possible with the data.
    Perhaps somebody could me explain how to to do this.
    I am using the "SQL Developer 2.1" and the "enterprise manager konsole".
    I'm a rookie in using this tools.
    Thank you for any informations.
    N. Wylutzki

    If you want to export data, you should use the export utility. This is documented:
    http://tinyurl.com/23b7on

  • Service name and database name are different.

    Hi,
    I had created a database with name PROD, latter i changed DB name to PRODT as per management request.
    But i notice the following things.
    1. At OS level ORACLE_SID variable is still PROD.(.bash_profile too have this entries)
    2. From sql prompt DB_NAME is PRODT.
    3. In Listener service name is showing PRODT and instance name is PROD.
    can any one please explain me, why oracle is behaving like this.
    Our all the applications are working fine with out any issues till now.
    [oracle@qual ~]$ echo $ORACLE_SID
    PROD
    [oracle@qual ~]$ sqlplus '/ as sysdba'
    SQL*Plus: Release 10.2.0.1.0 - Production on Tue Mar 5 10:35:01 2013
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    Connected to an idle instance.
    SQL> startup
    ORACLE instance started.
    Total System Global Area 608174080 bytes
    Fixed Size 1220868 bytes
    Variable Size 209719036 bytes
    Database Buffers 394264576 bytes
    Redo Buffers 2969600 bytes
    Database mounted.
    Database opened.
    SQL> select name from v$database;
    NAME
    PRODT
    SQL> !lsnrctl status
    LSNRCTL for Linux: Version 10.2.0.1.0 - Production on 05-MAR-2013 10:38:30
    Copyright (c) 1991, 2005, Oracle. All rights reserved.
    Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=qual.com)(PORT=1521)))
    STATUS of the LISTENER
    Alias LISTENER
    Version TNSLSNR for Linux: Version 10.2.0.1.0 - Production
    Start Date 05-MAR-2013 10:36:54
    Uptime 0 days 0 hr. 1 min. 35 sec
    Trace Level off
    Security ON: Local OS Authentication
    SNMP OFF
    Listener Parameter File /u001/app/oracle/product/10.2.0/network/admin/listener.ora
    Listener Log File /u001/app/oracle/product/10.2.0/network/log/listener.log
    Listening Endpoints Summary...
    (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=qual.com)(PORT=1521)))
    (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC0)))
    Services Summary...
    Service "PLSExtProc" has 1 instance(s).
    Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
    Service "PRODT" has 1 instance(s).
    Instance "PROD", status READY, has 2 handler(s) for this service...
    Service "PRODT_XPT" has 1 instance(s).
    Instance "PROD", status READY, has 2 handler(s) for this service...
    The command completed successfully
    SQL> exit
    Disconnected from Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    [oracle@qual ~]$

    Hello,
    I had created a database with name PROD, latter i changed DB name to PRODT as per management request.Using NID ?
    But i notice the following things.
    1. At OS level ORACLE_SID variable is still PROD.(.bash_profile too have this entries)ORACLE_SID is the instance name. Changing DB name does not change the instance name. You can manually change it by creating a new PFILE/SPFILE and Password file for the new instance.
    2. From sql prompt DB_NAME is PRODT.Yes, as you have changed the DB name from PROD to PRODT.
    3. In Listener service name is showing PRODT and instance name is PROD.Database name is PRODT and the instance associated with it is PROD. There can be multiple instances for a single database.
    Regards,
    Shivananda

  • Running sql script files to re create database

    We have having around 10 sql script file that has sql statments inside it (example insert .... delete...update.... etc).Right now what we do is that in jdbc we open each script file, and read each line ,and then make jdbc call run jdbc for each sql statement inside the file.
    Wondering if there is a better way to do this.
    Right now the challenges are
    1)The process goes wrong if there is an extra semi colon ...or extra space after a statments...etc...Basically I find this way of creating data odd...
    2)it is slow because of the network traffic between application server and database server for every sql statements that gets executed.The solution for this issue is to do a batch update....But still I dont like this solution.
    Can someone give me any better idea.
    I am thinking to have all this sql script moved to a store procedure (rather than inside the sql script file) .JDBC then can pick this store procedure sql file ,and create this store procedure via jdbc, and then execute this store procedure.
    This will be faster because all the sql will be running in the databsase.Only one trip to database to call this store procedure.
    Is this a good idea ?
    thx
    m

    Manjit wrote:
    We have having around 10 sql script file that has sql statments inside it (example insert .... delete...update.... etc).Right now what we do is that in jdbc we open each script file, and read each line ,and then make jdbc call run jdbc for each sql statement inside the file.
    Wondering if there is a better way to do this.
    Right now the challenges are
    1)The process goes wrong if there is an extra semi colon ...or extra space after a statments...etc...Basically I find this way of creating data odd...
    2)it is slow because of the network traffic between application server and database server for every sql statements that gets executed.The solution for this issue is to do a batch update....But still I dont like this solution.
    Can someone give me any better idea.
    I am thinking to have all this sql script moved to a store procedure (rather than inside the sql script file) .JDBC then can pick this store procedure sql file ,and create this store procedure via jdbc, and then execute this store procedure.
    This will be faster because all the sql will be running in the databsase.Only one trip to database to call this store procedure.
    Is this a good idea ?
    thx
    mI'm not 100% sure i follow (it's Friday and i have a mild case of ADD).
    Are you suggesting having the Java application create procedures in the database on the fly? If so i would say that's not a good idea.
    Create the stored procedures in the database, have Java call them as needed to process data.
    If you need to load copious amounts of data, look in to external tables, it's possible they could come in handy for what you are doing .... or not ... again, it's hard to say given i find your description of what's currently happening somewhat confusing.

  • Need script to add path and file name to fillable  form

    I have a fillable pdf form that I would like to have a script that adds the path and file name to the form. This script would be in a field at the end of the document.
    I am a newbie to javascript and formcalc. The script will be the only one in the form.
    Thanks for any assistance.
    Lisa

    Hi,
    I have a sample that attach a file to the PDF and write in a text field the file name. I don´t know how to get the full path and it only works in Acrobat. To work in Adobe Reader is necessary the LC Reader Extensions to give some special permissions to the document. But, regard this, you still want the sample send me a email to [email protected]
    Best Regards,

  • Need to set hostname and domain name

    Hi All,
    I need to
    1) set my "hostname" (foo), and
    2) set my "domain name" (acme.local)
    such that my machine identifies itself as "foo.acme.local". Anyone know how to do this? (I found the host name in file sharing, but it will not let me set the domain name.)
    Many thanks,
    -T

    etresoft wrote:
    Your domain is the name of your server.
    What gave you that idea? My domain name is "acme.local". It is not the name of my server. I have three servers on my network. The one with the DNS, DHCP, and firewall servers on it called "server.acme.local".
    I am confused about why you feel the need to have a subdomain.
    This is not a subdomain. What gave you the impression I was asking for a subdomain?
    What you seek to accomplish is entirely unnecessary and far more involved than just editing a config file.
    Pretty easy in Linux and Windows. They just grab the domain name from the DHCP server. Or, you can hand configure them if you wish. Do you know how accomplish same in 10.6.4?
    Give your machine a name in System Preferences > Sharing and it will have the name "whatever.local". That is all you need.
    I would like to the entire network name displayed correctly. "whatever.local" is incorrect. It should be "machinename.domainname" or "foo.acme.local". In my example, "foo" is the machine name ("whatever" in your example) and "acme.local" is the domain name. (Not the server's name, by the way.)
    "System Preferences > Sharing" will not let me add any extra periods. And will not let me change the ".local" either. (In this instance, I want the ".local".)
    Here is the reverse rule I had to hand create:
    182 PTR foo.acme.local.
    (The dot on the end is not a mistake.)
    I do not want a stray computer floating around that does not identify itself correctly. "foo.acme.local" is correct. "foo.local" is not.
    By the way, this computer gets its IP address from a DHCP server, which does tell this Apple what the domain name is. (It gets ignored.)
    /etc/dhcpd.conf
    option domain-name "acme.local";
    That is the config file for your DHCP server. You would use this if your machine were sharing its internet connection, for example. You don't need to edit this file.
    You misunderstand. The DHCP server, not on this Mac, is not being used to share Internet connections. It is being used to assign IP addresses to machines on the local network. It is also being used to assign fixed IP's to network printers based on their MAC addresses. In my network, these are "off Internet" addresses. The firewall, also not on this Mac, it used to share a single Internet connection with all the internal users.
    Hmmm. I created the file (dhcpd.conf) by hand. And, yes I do need to edit it all the time. Especially when I have bone headed machines on my network that do not follow or respond to standard networking conventions. This Mac does not accept the domain name given to it by my DHCP server and as such my DHCP server will not automatically update my DNS tables.
    Evidence of this can be found in the dhcpd.leases, where I had to hand enter
    client-hostname "foo";
    into the lease table (did not do me any good).
    I am wondering if 10.6.4 is not capable of handling this kind of standard network naming convention. (FreeBSD, which Apple run on top, is capable, so I am confused.)
    MacOS X does not run on top of FreeBSD. They are different operating systems. MacOS X has a POSIX layer which most closely resembles BSD, that is all.
    Interesting. Thank you for pointing out the difference. I bet POSIX know how, just like FreeBSD, which it resembles.
    If I change the name in /etc/hosts, will Apple over ride it? (I am not at the machine or I would just try it.)
    You do not "change" the name in /etc/hosts. You are just adding entries into your machine's lookup table. You can add as many aliases to as many IP addresses as you want. This is not the same as changing your machine's name, but it may be sufficient for what you are trying to accomplish - assuming I knew that, which I don't.
    Then, where do I make the change?
    10.6.4 did not tell the DHCP server what its name was either, so I had to hand add it into my DNS forward and reverse records. AAAAHHHHH!!!!
    I strongly advise against editing files you don't understand.
    I create my entire DNS configuration by hand, including my forward and reverse tables. Oh yes, I understand it, do I ever understand it. You should not jump to conclusions: it is insulting. I am presuming you meant no insult. Just be more careful next time.
    I think that what is happening here is that 10.6.4 is not set up to follow standard network naming conventions. I would posit that the idea is to keep home users out of trouble. Probably a good thing. If 10.6.4 is not capable of using standard naming conventions, (or following standard DHCP conventions), I would just like a confirmation of that so I will stop trying to figure out how to do it. And, stop wasting my time and just hand configure any additional Mac's that enter my network.
    Again, a "confirmation that it can not be done", or "how to do it" is what I am looking for.
    Thank you for the assistance,
    -T

  • Save As Script with predefined path and file name

    Hello,
    Livecycle version: 8.2.1.4029.1.523496
    The aim of the script I have is to save the livecycle form to a predefined directory and using the values of a text field in the file name.
    The script is placed in an exit event on a field using javascript as follows:
    this.saveAs("/c/forms/Template/Leave Application "  + Applicants_Name.rawValue".pdf");
    The script does not work.
    Can any one please provide some assistance with correcting my script?
    Any help will be most appreciated.

    This solution is misleading....
    Of course this works only if you plan to load Trusted script on each machine you plan to use that form. In other words you can not rollout form to entire organization with out loading trusted function in each targeted machine.
    Also there are other limitations... like if for some reason user reinstalls Acrobat x or Reader x or upgrade to latest version they need to remember to redeploy the trusted function to the required location.

  • Cannot run SQL script on Oracle Database 10g Express Edition

    I'm trying to upload a script, and the file is being uploaded fine, but in the Script Editor window where I'm going to actually run the script, the entire file content is shown on one line and the whole edit area is in red. I'm not being able to run that script. Also if I create a new script from the editor, the edit area is again in red and I'm not able to save it. Please help me understand what's to be done so that I can run my SQL scripts.

    I'd bet the database is down.
    Try a login through sqlplus ("Run SQL Command Line" in the Oracle Express Edition 'Start' menu).
    Do a CONN / AS SYSDBA
    If you get a message about database or memory area not available, try STARTUP.
    If that doesn't work, you are best off in the General Database forum or the Express Edition forum.
    You'll probably get the most expert response in General Database, but the Express Edition forum can be gentler on newbies (as it is more accepted that questioners are not and do not have access to full-time DBAs).

  • How to find the logins,program name and databases for a session id?

    I used the following the following query.
    select pr.spid ,pr.dbid,pr.program_name,pr.loginame,ss.session_id,ss.host_name,ss.login_time,db.name from master.dbo.sysprocesses pr,sys.dm_exec_sessions ss,sys.databases db
    where pr.spid = ss.session_id and pr.dbid = db.database_id
    order by ss.login_time desc
    Is spid in master.dbo.sysprocesses the same as session_id in sys.dm_exec_sessions and dbid in master.dbo.sysprocesses the same as database_id in sys.databases?
    My intention is to get the active sessions with the program name,login Name and database name corresponding to the session?

    1)Why you included the clause session_id > 50?
    Sessions with session_id <= 50 are system processes.
    2)Is there any problem with the query I used?
    You query was better than Latheesh's. To wit, his query will only show the database for sessions who are actually running something.
    On SQL 2005 and SQL 2008, this is the best solution:
    SELECT  des.session_id, des.[status], des.login_name,
            d.name AS database_name, des.program_name
    FROM    sys.dm_exec_sessions des
    JOIN    sys.sysprocesses p ON des.session_id = p.spid
    LEFT JOIN sys.databases d ON p.dbid = d.database_id
    WHERE   des.session_id > 50
      AND   p.ecid =0
    ORDER BY des.session_id;
    The condition p.ecid = 0 is needed to weed out extra rows when there are parallism in force.
    On SQL 2012, you don't need sysprocesses, but this works:
    SELECT  des.session_id, des.[status], des.login_name,
            d.name AS database_name, des.program_name
    FROM    sys.dm_exec_sessions des
    LEFT JOIN sys.databases d ON des.database_id = d.database_id
    WHERE   des.session_id > 50
    ORDER BY des.session_id;
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Can we execution  sql script through java ?

    Hi All,
    Can we execute sql script ("name.sql") through java programe.
    I am not talking about reading sql script one by one and excute.
    I just want to send this sql script to oracle console.
    Or any body can give other alternative I have to lot of db operation in less time.
    - Vikas Kumar Sahu

    Kumar,
    not sure whether this is any help, but you can try and use the code below.
    I've knocked it together in about an hour so it's far from production ready (particularly, assumes one-line comments starting with '#' and nothing else - queries are assumed multi-line, but terminated by ';' the following would cause trouble:
    SELECT * FROM table; SELECT *
    FROM another_table;
    and, of course, you can't get to the ResultSet.
    But, hey, it's a start!
    Best,
    Marco.
    (www.infinitebw.com)
    admin (at) infinitebw.com
    package com.ibw.database;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.sql.*;
    import com.ibw.exception.DatabaseException;
    public class SqlScript {
         public final static char QUERY_ENDS = ';';
         private File script;
         private Connection conn;
         private Statement stat;
         * @param args
         * @throws SQLException
         public SqlScript(String scriptFileName) throws SQLException {
              script = new File(scriptFileName);
    // this is a 'custom' class, just use instead getConnection() from the
    // DriverManager instead
              conn = ConnectionManager.getConn("test");
              stat = conn.createStatement();
         public static void main(String[] args) {
              try {
                   SqlScript sqlScript = new SqlScript("C:/temp/myscript.sql");
                   sqlScript.loadScript();
                   sqlScript.execute();
              } catch (SQLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         protected void loadScript() throws IOException, SQLException {
              BufferedReader reader = new BufferedReader(new FileReader(script));
              String line;
              StringBuffer query = new StringBuffer();
              boolean queryEnds = false;
              while ((line = reader.readLine()) != null) {
                   if (isComment(line))
                        continue;
                   queryEnds = checkStatementEnds(line);
                   query.append(line);
                   if (queryEnds) {
                        stat.addBatch(query.toString());
                        query.setLength(0);
         private boolean isComment(String line) {
              if ((line != null) && (line.length() > 0))
                   return (line.charAt(0) == '#');
              return false;
         public void execute() throws IOException, SQLException {
              stat.executeBatch();
         private boolean checkStatementEnds(String s) {
              return (s.indexOf(QUERY_ENDS) != -1);
    }

  • IF statement syntax in SQL script view

    I need to include a "IF" condition in the "SELECT" section of my SQL script view.
    I tried the following syntax's but I get the error 'Incorrect SQL syntax near 'IF'
    1.  IF(Revenue <> '0' AND Quantity <> '0', Revenue/Quantity, '0') AS Gross Price
    2.  IF(Revenue != '0' AND Quantity != '0', Revenue/Quantity, '0') AS Gross Price
    3.  IF(Revenue <> '0' AND Quantity <> '0' THEN Revenue/Quantity ELSE  '0' END) AS Gross Price
    4.  IF(Revenue != '0' AND Quantity != '0' THEN Revenue/Quantity ELSE  '0' END) AS Gross Price
    My final SQL would read like follows:
    SELECT field1, field2, IF(......) AS field3
    FROM table1
    Can anybody please help with the correct IF statement syntax to be used in the SQL script based view?

    Hi Lakshmi,
    below is the syntax for IF statement.
    IF <bool_expr1> THEN
    <then_stmts1>
    ELSEIF <bool_expr2>
    THEN <then_stmts2>
    [ELSE <else_stmts3>]
    END IF
    eg :
    BEGIN
    DECLARE found INT := 1;
    SELECT count(*) INTO found FROM books WHERE isbn = :v_isbn;
    IF :found = 0 THEN
    INSERT INTO books VALUES (:v_isbn, 'In-Memory Data Management', 1, 1, '2011', 42.75, 'EUR');
    ELSE
    UPDATE books SET price = 42.75 WHERE isbn =:v_isbn;
    END IF;
    END;
    Sreehari

Maybe you are looking for

  • E-Rec Reference Code in the Publication tab should not appear after enddate

    hi, There is a requirement from the client after the end date of the publication ,the reference code should not be displayed to the candidate in the Candidate page ,presently the same is manually done in the system by changing the status to withdrawn

  • Windows 7, IE8, and bookmarks

    Ever since I upgraded to Windows 7 and Internet Explorer 8, my browser bookmarks don't sync with the iPhone any more. Is there a trick to making this work? My guess (and that's all it is) is that IE8 stores its bookmarks in a different place than IE7

  • Exception while trying to write xml file

    When I try to write my DOM tree to an XML file a get the following exception form the transformer.transform() function call: Exception in thread "AWT-EventQueue-0" java.lang.AbstractMethodError: org.apache.crimson.tree.XmlDocument.getXmlStandalone()Z

  • Flash Media Server Temp Files

    Hi all, Maybe this topic has been asked and answered before. But I have not found relevant information on this issue. So there it is: I found out that when the FMS service is running, it creates a lot of temporily files in the c:\windows\tempdirector

  • Help regarding a macbook 2gb RAM HELP!

    hey guys, i am 15 and i am really getting interested in graphic design and video editing (aka photoshop and imovie). I have used PC's all my life but i think it is finally time to jump to the real deal, a Mac. Specifically a MacBook. Now my question