Search code examples
cmdsqlcmdsap-ase

How to execute .sql script (sybase) file using cmd


I am having .sql (sybase) file which creates the table i.e. "Create_table_mytable.sql"

But before creating the table it check of the existing table and drops the same.

here is how scripts looks like: -

setuser 'dbo'
go 


    IF EXISTS (SELECT 1 FROM sysobjects o, sysusers u WHERE o.uid=u.uid AND o.name = 'mytable' AND u.name = 'dbo' AND o.type = 'U') 
    begin
        print 'dropping mytable'
         drop table   mytable   
        print 'dropped mytable'  
    end
go    
    IF NOT EXISTS (SELECT 1 FROM sysobjects o, sysusers u WHERE o.uid=u.uid AND o.name = 'mytable' AND u.name = 'dbo' AND o.type = 'U')
    begin       
        create table mytable (
                id numeric(9,0)     IDENTITY ,
                description             varchar(50)     not null
                )

                GRANT SELECT ON dbo.mytable TO my_user

                GRANT INSERT ON dbo.mytable TO my_user

                GRANT DELETE ON dbo.mytable TO my_user
    end
    go


end
go

setuser  
go 

Here is the contents of cmd file: -

@ECHO ON

ECHO ">> START <<  mytable.sql" >> %LOG%
%SQL% -S %SERVER% -U %USER% -P %PWD% -D %DB% -i mytable.sql >> %LOG%

@ECHO OFF

Here is the contents of log file: -

">> START <<  mytable.sql" 
Msg 102, Level 15, State 1:
Server 'myserver', Line 14:
Incorrect syntax near 'go'.
">>> SYBASE SCRIPT COMPLETE <<< " 

Note: the same scripts runs properly if executed using Sybase Intrective SQL or ASE Tools.


Solution

  • Fine I got the answer. Here is what I missed to write after dropping table: -

    use db
    go 
    
    setuser 'dbo'
    go
    
    
    IF EXISTS (SELECT 1 FROM sysobjects o, sysusers u WHERE o.uid=u.uid AND o.name = 'mytable' AND u.name = 'dbo' AND o.type = 'U')
    begin
    print 'dropping mytable'
        drop table mytable
        print 'dropped table - mytable'
    end
    go 
    
    IF (@@error != 0)
    BEGIN
        PRINT "Error CREATING table 'mytable'"
        SELECT syb_quit()
    END
    go
    
    
    IF NOT EXISTS (SELECT 1 FROM sysobjects o, sysusers u WHERE o.uid=u.uid AND o.name = 'mytable' AND u.name = 'dbo' AND o.type = 'U')
    begin       
        create table mytable (
                id numeric(9,0)     IDENTITY ,
                description             varchar(50)     not null
                )
    
    
                GRANT SELECT ON dbo.mytable TO my_user
    
                GRANT INSERT ON dbo.mytable TO my_user
    
                GRANT DELETE ON dbo.mytable TO my_user
    
    end
    go
    
    setuser  
    go