Search code examples
sql-serversqlcmdqsqlquery

Use SQLCMD to execute script return Invalid object name


I have to insert a very large amount of data in sql, the operation did not work via SQL Management Studio therefore I was investigating the insert via sqlcmd. so what I did was the following:

  1. create a file.sql that contains the following query (multiple times):

    IF NOT EXISTS (SELECT * FROM [dbo].[tblAccount] 
                   WHERE [AccountID] = 117242 AND
                         [TimeStamp] = CAST(N'2013-01-16 05:53:50.490' AS DateTime)) 
    BEGIN
        INSERT INTO
            [dbo].[tblAccount] ([AccountID]
                               ,[Name]
                               ,[Comment]
                               ,[IsMachine]
                               ,[UserID]
                               ,[Prefix]
                               ,[Action]
                               ,[Initials]
                               ,[Name]
                               ,[TimeStamp]
                               ,[Reason]
                               ,[Iscal]) 
                        VALUES (117242
                               ,'blabla'
                               ,'The users project)'
                               ,1
                               ,'val'
                               ,39
                               ,'val'
                               ,'blabla'
                               ,'blabla'
                               ,CAST(N'2013-01-16 05:53:50.490' AS DateTime)
                               ,'NORMAL'
                               ,'0')
    END
    
  2. I saved the file into a folder and then from the command line I do the following:

    C:\>sqlcmd -S pc_name\MSSQLEXPRESS -i"C:\Users\name\Desktop\OutPut\Result tblAccount.sql"
    

I get the following error:

Msg 208, Level 16, State 1, Server pc_name\MSSQLEXPRESS, Line 1
Invalid object name 'dbo.tblAccount'.

I'm not sure if it is related to the syntax of the sql or in the way I write the sqlcmd.


Solution

  • I know it's an over a year ago question, but in case somebody run into the same issue, make sure to provide credentials. I just ran into same issue and without providing credentials, sqlcmd issues that error. I don't know what's happening behind the scene, but seems that it connects to some sort of default db when authentication fails and couldn't find the table as a result.

     sqlcmd -S <computer name> -U <username> -P <password> -i  <absolute path to your script>