How to run .sql file in tsql or powershell

Hi All,
HOw to run .sql file inside the TSQL or powershell using with IF else condition. This below query works fine but when i executing through the SQL Agent it's geeting an error.Please could help how to run through the SQL agent already using execution type
in agent as 'Operating system(CmdExec)'
Declare @computerName varchar(100), @InstanceName varchar(50)                             
SET @ComputerName = REPLACE(CAST(SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS varchar),'\','$')  
SET @InstanceName = REPLACE(CAST(SERVERPROPERTY('instancename') AS varchar),'\','$')
IF (@InstanceName = 'SQL2008R2')
Begin  
:r C:\BackupFolder\Test1.sql    
:r C:\BackupFolder\Test2.sql    
End
IF (@InstanceName = 'SQLINS2')
BEGIN
:r C:\BackupFolder\Test3.sql
END
IF (@InstanceName = 'SQL2012')
BEGIN
:r C:\BackupFolder\Test4.sql
END
Thansk in Advance
A-ZSQL

In T-SQL, you can try using sqlcmd to invoke sql file
if @@SERVERNAME='abcd'
begin
Master..xp_cmdshell 'sqlcmd -S <ServerName> -i BackupDetails.sql -E'
end
OR 
 PowerShell 
Load the snapins
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
Function Get-SqlInstances {
Param($ServerName = '.')
$localInstances = @()
[array]$captions = gwmi win32_service -computerName $ServerName | ?{$_.Name -match "mssql*" -and $_.PathName -match "sqlservr.exe"} | %{$_.Caption}
foreach ($caption in $captions) {
if ($caption -like "MSSQLSERVER") {
$localInstances += $ServerName
} else {
$temp = $caption | %{$_.split(" ")[-1]} | %{$_.trimStart("(")} | %{$_.trimEnd(")")}
$localInstances += "$ServerName\$temp"
$localInstances
$instance=Get-SqlInstances -ServerName HQDBSP17
foreach($i in $instance)
if($i -like 'CRM2011')
write-host 'CRM Database'
invoke-sqlcmd -inputfile 'F:\PowerSQL\test.sql' -ServerInstance 'abcd'
if( $i -like 'SQL2012')
write-host 'SQL 2012 instance'
invoke-sqlcmd -inputfile 'F:\PowerSQL\test.sql' -ServerInstance 'abcd'
--Prashanth

Similar Messages

  • How to run SQL files from Java?

    Hi,
    Can someone point me towards a link on how to run sql files in Java? Thanks.
    P.S...if I've been completely blind please go easy on me!

    Sorry forgot the formating code thingy
    public static boolean executeScript(File script, Connection conn){
        boolean success = true;
        success = script.exists();
        if(success){
          DEBUG.print("ES::READING SCRIPT:" + script.getAbsolutePath());
          StringBuffer buffer = new StringBuffer();
          success=readScript(script,buffer);
          if(success){
            try{
              String creationScript = buffer.toString();
              Statement st = conn.createStatement();
              int start = 0;
              int end = 0;
              while (end != -1 && start < creationScript.length()) {
                end = creationScript.indexOf("GO", start);
                if (end != -1) {
                  DEBUG.print(creationScript.substring(start, end));
                  st.executeUpdate(creationScript.substring(start, end));
                  start = end + 2; //2 is the length of "GO"
              st.close();
            }catch(Exception e){
              success=false;
              DEBUG.printStackTrace(e);
        }else{
          DEBUG.print("ES::SCRIPT FILE DOES NOT EXISTS");
          success=false;
        return success;
      public static boolean readScript(File script, StringBuffer buffer){
        boolean success = true;
        DEBUG.print("RS:: reading file :" + script.getAbsolutePath());
        try{
          InputStreamReader isr = new InputStreamReader(new FileInputStream(script),"UTF16");
          int ch;
          while ( (ch = isr.read()) > -1) {
            buffer.append( (char) ch);
          if (isr != null)
            isr.close();
        }catch(Exception e){
          success=false;
          DEBUG.printStackTrace(e);
        return success;
      }

  • How to run batch file from oracle forms 9i

    Hi everyone.
    i have a data in csv file. i want to upload it to my database. i am using sql loader for it.
    i have made a batch file which run the sql loader and transfer my data to database.
    How to run batch file from oracle forms 9i.
    when i press the button, nothing uploads in my database. (when i simply run the batch file it works).
    here is my code
    Begin
    HOST('C:\temp\batchfile.bat');
    message('done');
    end;
    Thanks in advance
    regards
    sajid

    this is my log file, when i run manually.
    SQL*Loader: Release 10.2.0.1.0 - Production on Thu Jul 1 23:27:53 2010
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    Control File: file_to_upload.ctl
    There are 2 data files:
    Data File: sk.csv
    Bad File: sk.bad
    Discard File: none specified
    (Allow all discards)
    Data File: sk1.csv
    Bad File: sk1.bad
    Discard File: none specified
    (Allow all discards)
    Number to load: ALL
    Number to skip: 0
    Errors allowed: 50
    Bind array: 64 rows, maximum of 256000 bytes
    Continuation: none specified
    Path used: Conventional
    Table KHAN, loaded from every logical record.
    Insert option in effect for this table: APPEND
    Column Name Position Len Term Encl Datatype
    SR FIRST * , O(") CHARACTER
    DATES NEXT * , O(") CHARACTER
    AGENT NEXT * , O(") CHARACTER
    COUNTRY NEXT * , O(") CHARACTER
    TRANSACTIONS NEXT * , O(") CHARACTER
    PKR NEXT * , O(") CHARACTER
    USD NEXT * , O(") CHARACTER
    BANK NEXT * , O(") CHARACTER
    Table KHAN:
    11088 Rows successfully loaded.
    0 Rows not loaded due to data errors.
    0 Rows not loaded because all WHEN clauses were failed.
    0 Rows not loaded because all fields were null.
    Space allocated for bind array: 132096 bytes(64 rows)
    Read buffer bytes: 1048576
    Total logical records skipped: 0
    Total logical records read: 11088
    Total logical records rejected: 0
    Total logical records discarded: 0
    Run began on Thu Jul 01 23:27:53 2010
    Run ended on Thu Jul 01 23:27:54 2010
    Elapsed time was: 00:00:00.63
    CPU time was: 00:00:00.17

  • How to run ear file in java application server

    i want how to run .ear file in java application server
    1. i m created ear file
    2. i m created jar file (bean,home,remote)
    3.i m created war file(in the form of jsp)
    but till now i couldnt run ear file
    how to run
    please hel me

    You must create :
    1.Jar file
    2.War file
    And then put them into an ear file
    Exemple : myapp.ear contains
    myappEJB.jar
    myappWEB.war
    META-INF/application.xml
    and application.xml looks like this :
    <application xmlns="http://java.sun.com/xml/ns/j2ee" version="1.4"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com /xml/ns/j2ee
                            http://java.sun.com/xml/ns/j2ee/application_1_4.xsd">
        <display-name>myapp</display-name>
        <description>Demo application</description>
        <module>
            <ejb>myappEJB.jar</ejb>
        </module>
        <module>
          <web>
             <web-uri>myappWAR.war</web-uri>
             <context-root>/myapp</context-root>
          </web>
        </module>
    </application>Good luck

  • How to run .exe files with Virtual PC for Mac

    Hey Guys, I'm new around here and with mac technology as well. Anyway, I have an iMac OS X 10.5.1 Leopard and I've recently purchased the Virtual PC for Mac 7.0.2 software. So I'd like to know how to use this program properly, because I need to run some executable files in my computer. It is confusing for me because I don't know how to get started, and I only get to the part when it says "OS not found, Install an OS on this hard drive".
    Honestly I've no idea of what an OS is or where do I get that. So I'd really appreciate if one of you guys could tell me, step by step, what to do to use Virtual PC properly, and finally learn how to run .exe files on mac.
    Thanks in advance!
    Have a nice day!

    Always nice to see new faces
    Honestly I've no idea of what an OS is or where do I get that.
    This brings up the second part of your problem. The first part is setting up either a proper Virtual Machine program like Parallels or VMfusion, or setting up a Boot Camp partition on your drive.
    http://www.parallels.com/
    http://www.vmware.com/products/fusion/
    OS stands for Operating System. You are running Leopard 10.5.7 as an operating system on your Mac (MacOS X).
    The second part of your problem - You will need a copy of Windows XP or Vista if you want to run Windows on your Mac.
    There is at least one other solution for running Windows programs on a Mac. It's called "CrossOver" by a company named 'Codeweavers'. It's based on a project for "Wine" to be able to run PC programs on a Mac or Linux, without having to buy or install Windows. It works with a narrow subset of Windows programs so you would want to make sure the program you want to run is compatible with CrossOver before you buy it.
    http://www.codeweavers.com/products/cxmac/
    In addition to all the above information, you need to upgrade your Mac to the latest 10.5.7 from 10.5.1. "Software Update" is located under the black Apple icon in the Menu Bar at the top left corner of your monitor. After you are updated you will want to update your Profile here so that it shows the proper OS version.
    With your level of experience with MacOS X and the Windows OS's you should probably get some help from a local Apple store. They have an appointment system and do offer many types of help and training, and they can offer assistance with choosing the proper programs for you to purchase for your machine.
    You are also welcome to continue to ask questions here, of course. You will want to ask your questions with different issues that come up in different threads so that the answers stay focused on the title of the thread.
    Message was edited by: dechamp to try to be more accurate with a fairly complicated issue...

  • How to run .exe files in mac pro?

    how to run .exe files in mac pro?
    i am looking for this to play games in my mac pro.
    if someone got a answer, just let me know
    cheers.

    mailking wrote:
    And I fail to see why you are attacking me...
    My comment is Valid...  " .exe files will not run natively on Mac OS X..."
    I am sorry. I had the false impression that it was commonly known that .exe files did not run on Mac OSX natively and failed to see any constructive critique you were bringing. Maybe I am wrong. Again deepest apologies.
    Unfortunately... these days... not every one is aware of this .exe  fact..
    Apology accepted.. and Thank You..

  • How to run script file ( unix script file like ksh or sh file) using Java

    How to run script file ( unix script file like ksh or sh file) using Java Program?.
    I am using the following code snippet to run the simple commands like top or ls ,etc....
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("top");
    Thanks In Adavance
    -Siva

    String [] { "ksh" , "-c" , "script", "arg 1", "arg 2", "arg 3"}

  • How to run media file after Runtime.exc the real player?

    Hi
    How to run media file after Runtime.exc the real player application

    String command = "cmd /c start videotest.rm";
    Runtime.getRuntime().exec(command);

  • How to run .java file in windows ?

    How to run .java file in windows without installing any program? Thx!

    First, U must make sure that there is JDK on your computer
    Then, set the envionment variables which the os can find your compiler and interpreter: javac java
    after those, you must complie your .java file to .class file, then you can excute it by java, for example " java helloworld"

  • How to run .pdb file

    we using Oracle 10g on AIX 6 server. In our server, have 3 different Database namely Test, training and production. I want to run a patch file extension PDB. But how can I run PDB file in Test database.

    Hello people,
    is anybody here who can give an example without
    refering to instruction how to run jar file?java -jar yourJarFile.jar
    in case if you want to be refered to instructions later during the day, [url http://java.sun.com/docs/books/tutorial/jar/basics/index.html] here it is

  • 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

  • How to run sql query in bat file in task schedular at every 10 seconds

    This is my sql script :
    DECLARE @countRows INT,
    @currDate DATE,
    @checkForTasks INT,
    @created_by_id INT,
    @gst_ID int;
    SET @currDate = Getdate()
    SET @countRows = (SELECT Count(*)
    FROM [dbo].[sd_gst_effective_table]
    WHERE isapplied = 0)
    IF @countRows > 0
    -- Check for those GST''s who are not applied yet : if they are greater than 0 then perform next task
    BEGIN
    SET @checkForTasks = (SELECT Count(*)
    -- Check is current date equals to task date or not
    FROM [dbo].[sd_gst_effective_table]
    WHERE effect_date = @currDate AND isapplied = 0)
    IF @checkForTasks > 0
    -- If current date = task date then perform this task
    BEGIN
    SET @created_by_id = (SELECT TOP 1 createdby FROM [dbo].[sd_gst_effective_table] WHERE effect_date = @currDate AND isapplied = 0)
    SET @gst_ID = (SELECT gst_id FROM [dbo].[sd_gst_effective_table] WHERE effect_date = @currDate AND isapplied = 0)
    -- STEP 1 :: InActivate the existing GST according to createdbyID
    UPDATE sd_gst_rate
    SET isactive = 0,
    inactivedate = Getdate()
    WHERE isactive = 1
    AND createdby = @created_by_id
    -- STEP 2 :: Activate the New GST according to implementation date and gstID
    UPDATE sd_gst_rate
    SET isactive = 1,
    activedate = Getdate()
    WHERE id = @gst_ID
    -- STEP 3 :: Inactivate the applied GST from sd_gst_effective_table
    UPDATE [dbo].[sd_gst_effective_table] SET isApplied = 1 WHERE gst_id = @gst_ID
    END
    END
    DECLARE @Text AS VARCHAR(100)
    DECLARE @Cmd AS VARCHAR(100)
    DECLARE @value nvarchar(1000);
    SET @value = (SELECT CONVERT(TIME,GETDATE()) AS HourMinuteSeconds);
    SET @Text = 'File Writed ' + @value
    SET @Cmd ='echo ' + @Text + ' > E:\AppTextFile.txt'
    EXECUTE Master.dbo.xp_CmdShell @Cmd
    This is resided in videos folder of windows , i have created a task schedular in windows 8.1 to run daily at every 10 seconds , but it is not working ... Please tell me how to deal with it.
    Please note : This sql query is running perfectly in sql server. Query have no errors. Please check whats wrong with my time schedular. I just want my schedular to run every 10 seconds regardless of date.

    Hi Emad,
    Is your script in a ".sql" file? May I know how you configure the schedule task action?
    Since you didn't mention how you configure the schedule task, can you confirm you have followed the below step correctly?
    Save your script in a ".sql" file.
    Create a ".bat" file and call the sql file above inside with
    sqlcmd.exe, you can reference
    here.
    Configure a schedule task to run the ".bat" file in a certain interval.
    Have you tried to run the script in you bat file in a standalone commandline window? Please post the script in your bat file, It can help to diagnose the issue.
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • How to run SQL script file on Linux using Java ?

    Hi,
    I need to execute .sql file using java. I used following approach for this.
    private void runScriptEvent(java.awt.event.ActionEvent evt) {                               
            String sqlOutput = "";
            String sqlPromptLines="";
            String currentFunctionName = "";
            if(con!=null){
                String userName = jTextField4.getText();
                String password = jPasswordField1.getText();
                String databaseName = jTextField3.getText();
                try {
                    String script_location = "";
                    ProcessBuilder processBuilder =null;
                    Process process = null;
                    //File file = new File("C:/ScriptFile");
                    File file = new File("./SQL_Script");
                    //File file = new File("E:\\install\\SQL_Script");
                    if(file.exists()){
                        File [] list_files= file.listFiles(new FileFilter() {
                                        public boolean accept(File f) {
                                        if (f.getName().toLowerCase().endsWith(".sql"))
                                        return true;
                                        return false;
                    int count = 0;
                        for (int i = 0; i<list_files.length;i++){
                            script_location = "@" + list_files.getAbsolutePath();//ORACLE
    //currentFunctionName = list_files[i].getName();
    StringTokenizer st = new StringTokenizer(list_files[i].getName(), ".");
    while(st.hasMoreTokens()) {
    currentFunctionName = st.nextToken();
    String extention= st.nextToken();
    System.out.println("Function Name = "+currentFunctionName + "\t Extention = " + extention);
    processBuilder = new ProcessBuilder("sqlplus",userName+"/"+password+"@"+databaseName, script_location); //ORACLE
    processBuilder.redirectErrorStream(true);
    process = processBuilder.start();
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String currentLine = null;
    while ((currentLine = in.readLine()) != null) {
    sqlPromptLines = " "+sqlPromptLines + currentLine +"\n";
    count ++;
    System.out.println(count+" " + currentLine);
    if(currentLine.equalsIgnoreCase("Function created.")){
    sqlOutput = "\n" sqlOutput currentFunctionName + " " currentLine"\n" ;
    break;
    }// end while
    in.close();
    process.destroy();
    }//end for
    }//end if file exists
    } catch (IOException e1) {
    jTextArea1.setText(e1.getMessage());
    System.out.println("Script Done");
    jTextArea1.append(sqlOutput);
    }// end id Connection is not null
    Above code working appropriate on Windows but not on Linux.
    is there any changes needed ?
    Regards,
    Ajay
    Edited by: Ajay Sharma on Nov 21, 2012 6:43 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hi gimbal2,
    about code
    jTextArea1.setText(e1.getMessage());I am using this code so that the user will be prompted with a message rather than stack trace.
    About the issue I am getting on linux i believe its because of following statement.
    processBuilder = new ProcessBuilder("sqlplus",userName+"/"+password+"@"+databaseName, script_location); //ORACLERegards,
    Ajay
    Edited by: Ajay Sharma on Nov 23, 2012 12:05 PM
    Edited by: Ajay Sharma on Nov 23, 2012 12:06 PM

  • Is it possible to run .sql files in oracle

    Hi
    I have a .sql file which contains the scripts of the tables .Is it possible for me to run the .sql file in oracle or will i have to run the scripts of each tables separately becoz there is about 240 table scripts in that single .sql file. In mysql by giving " \.filename.sql " the whole scripts in the .sql file will get executed .Is there any thing like this in oracle9i.Also i want to know how to make a dump file in oracle and to run that?
    Thanking you in advance

    Hi
    I did the way u said the whole script file is running but the execution of the script is not happening. The below is a part of script but the table creation is not happening at the end of each table script
    5946 drop table lms_class_permission;
    5947 CREATE TABLE lms_class_permission (
    5948 pk_permission_id NUMBER(11) NOT NULL ,
    5949 fk_class_Id NUMBER(11) default NULL,
    5950 fkSysGroupId NUMBER(11) default NULL,
    5951 perm NUMBER(11) default '0',
    5952 CONSTRAINT pk_permission_id_lms_class PRIMARY KEY (pk_permission_id),
    5953 CONSTRAINT uk_lms_class_permission UNIQUE (fk_class_Id,fkSysGroupId),
    5954 CONSTRAINT fk_lms_Class_Permission_1 FOREIGN KEY (fk_class_Id) REFERENCES lms_class (pk_class
    5955 CONSTRAINT fk_lms_Class_Permission_2 FOREIGN KEY (fkSysGroupId) REFERENCES t_system_groups (g
    5956 );
    5957 create index fk_class_Id_lms_class_perm on lms_class_permission (fk_class_Id);
    5958 create index fkSysGroupId on lms_class_permission (fkSysGroupId);
    5959 CREATE SEQUENCE lms_class_permission_SEQ INCREMENT BY 1 START WITH 1 MAXVALUE 2147483647 NO
    5960 CREATE OR REPLACE TRIGGER TR_lms_class_permission_BI
    5961 BEFORE INSERT
    5962 ON lms_class_permission
    5963 REFERENCING NEW AS NEW OLD AS OLD
    5964 FOR EACH ROW
    5965 BEGIN
    5966 SELECT lms_class_permission_SEQ.NEXTVAL INTO :NEW.pk_permission_id FROM dual;
    5967 END ;
    5968 drop table lms_contact_us ;
    5969 CREATE TABLE lms_contact_us (
    5970 pkautoid NUMBER(10) not null ,
    5971 user_name VARCHAR2(255) default '0',
    5972 email VARCHAR2(255) default '0',
    5973 subject VARCHAR2(1000),
    5974 message VARCHAR2(1000),
    5975 loginId VARCHAR2(255) default NULL,
    5976 status NUMBER(11) default NULL,
    5977 classId NUMBER(11) default NULL,
    5978 CONSTRAINT pkautoid_lms_contact_us PRIMARY KEY (pkautoid)
    5979 );
    5980 CREATE SEQUENCE lms_contact_us_SEQ INCREMENT BY 1 START WITH 1 MAXVALUE 2147483647 NOCYCLE NO
    5981 CREATE OR REPLACE TRIGGER TR_lms_contact_us_BI
    5982 BEFORE INSERT
    5983 ON lms_contact_us
    5984 REFERENCING NEW AS NEW OLD AS OLD
    5985 FOR EACH ROW
    5986 BEGIN
    5987 SELECT lms_contact_us_SEQ.NEXTVAL INTO :NEW.pkautoid FROM dual;
    5988 END ;
    5989 drop table borland_feedback ;
    5990 CREATE TABLE borland_feedback (
    5991 pkautoid NUMBER(10) not null ,
    5992 FeedTitle VARCHAR2(1000),
    5993 FeedBody VARCHAR2(1000),
    5994 EnteredBy NUMBER(11) default '0',
    5995 FeedStatus NUMBER(11) default '0',
    5996 FeedEnteredDate TIMESTAMP,
    5997 CONSTRAINT pkautoid_borland_feedback PRIMARY KEY (pkautoid)
    5998 );
    5999 CREATE SEQUENCE borland_feedback_SEQ INCREMENT BY 1 START WITH 1 MAXVALUE 2147483647 NOCYCLE
    6000 CREATE OR REPLACE TRIGGER TR_borland_feedback_BI
    6001 BEFORE INSERT
    6002 ON borland_feedback
    6003 REFERENCING NEW AS NEW OLD AS OLD
    6004 FOR EACH ROW
    6005 BEGIN
    6006 SELECT borland_feedback_SEQ.NEXTVAL INTO :NEW.pkautoid FROM dual;
    6007 END ;
    Thanking you advance
    dinny

  • Information on how to run SQL queries on the CUCM itself please

    Good Day All,
    I need to run an sql query on the CUCM to list all of my directory numbers, their partition, and their external mask values.
    I came across this excerpt below earlier so I have a bit of an idea how to do it but iw would be great to see some other examples of sql queries.
    Any assistance is most appreciated.
    Also, is there a document somewhere to tell me how to run these queries?
    Thanks in advance
    Regards
    Amanda
    Currently Being Moderated
    05/04/2011 5:18 AM (in response to Joshua Royle)
    Re: Is there a way of pulling a report off CM showing all phones that have diverts on?
    Try if running this SQL query from the CLI helps you, it should list all DN's that have CFA enabled to VM or a DN:
    run sql select dnorpattern,cfadestination,cfavoicemailenabled from CallForwardDynamic c, numplan n where c.fknumplan = n.pkid and (cfadestination != '' or cfavoicemailenabled ='t')

    Hi Amanda
    Basically it's standard SQL, so it wouldn't hurt to google 'informix select statements' and do a little reading to get the basics. There are millions of permutations of queries so it's a matter of understanding the syntax, and then applying that to the database in question. The only difference when running commands from the CLI are that:
    - You prefix the standard informix SQL statement with 'run sql'
    - You don't get any help from CUCM with the syntax, so you might be well advised to use something that understands SQL a little and colorises it as you type, and then paste the resulting commands into the CUCM SSH window. I use a text editor named JEdit, if you create a text file and save it as a file ending in .sql it will highlight your syntax.
    - Other programs are available that do reasonable syntax highlighting (e.q. SquirrelSQL) that are designed for querying the DB directly, but you can't actually query directly against the DB for security reasons. You'd still have to copy/paste the commands.
    Now... to understand the DB you'll need a reference describing all the tables etc. This is here:
    http://www.cisco.com/en/US/products/sw/voicesw/ps556/products_programming_reference_guides_list.html
    Pick your version of CUCM and download the 'Data Definition' document.
    A few notes on the command:
    run sql : is just the CLI command that tells the shell to run the following text as SQL.
    select : the SQL command to retrieve data
    dnorpattern,cfadestination,cfavoicemailenabled : the column names to retrieve
    callforwarddynamic c, numplan n : the names of two tables, and the abbreviations you want to refer to them as
    where c.fknumplan = n.pkid : this tells SQL to return values from the two tables where these fields match up. In the data definition you'll see notes that c.fknumplan (i.e. the fknumplan column in the callforwarddynamic table, as noted by the c. prefix) refers to the PKID column in the numplan field. This is a very standard type of join in the CCM DB.
    and (cfadestination != '' or cfavoicemailenabled ='t') : another clause, basically in this query we want to see only rows where cfadestination isn't blank or cfavoicefmailenabled is set to 't' for true).
    Most tables are linked in one of two ways in this database:
    - a column prefixed 'fk' refers to the pkid field (there is always only one pkid field per table) in the table following the 'fk' prefix. E.g. above fknumplan refers to the numplan table, pkid field. fkdevice would refer to the device table, pkid field.
    - a column prefiex 'tk' refers usually to an enum table which is prefixed with 'type'. This is a table that maps the number value in the 'tk' field to a string. An example would be tkmodel - this represents the phone physical model type (e.g. 7962), and maps to a table called typemodel, and the 'enum' column in that table.
    Regards
    Aaron HarrisonPrincipal Engineer at Logicalis UK
    Please rate helpful posts...

Maybe you are looking for