Amitesh Verma

Amitesh Verma

  • NA
  • 12
  • 2.5k

How to check table exist,if exist rename it and load in sql

Jun 28 2017 1:58 PM
Hi coder, 
 

I Have to create a query in which I have to do many thing:

First check if table is already exist in the database or not

Second I have to check if it is not exist create it and then load the data from text file into database using bcp for that, if it is already created i have to rename it


DECLARE @TableSchema sys.sysname = N'dbo'; DECLARE @TableName sys.sysname = N'x';
DECLARE @BackupTable sys.sysname = @TableName + '_' + CONVERT(VARCHAR  (32),    
GETDATE(), 120);   
DECLARE @SQL NVARCHAR(MAX) =
N'  DECLARE @TableWithSchema NVARCHAR(256) = QUOTENAME(@TableSchema) + ''.'' +    
QUOTENAME(@TableName);  IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES          
 WHERE TABLE_SCHEMA = @TableSchema         
 AND  TABLE_NAME = @TableName)) 
BEGIN  EXEC sp_rename @TableWithSchema, @BackupTable, ''OBJECT''  END   
CREATE TABLE ' + QUOTENAME(@TableSchema) + '.' + QUOTENAME(@TableName) +
 '(  /* Column definitions here*/  );  '; EXEC sp_executesql  
 @stmt = @SQL  , @params = N'@TableSchema sys.sysname, 
@TableName sys.sysname, @BackupTable sys.sysname' , 
@TableSchema = @TableSchema  , 
@TableName = @TableName ,
 @BackupTable = @BackupTable  ; 
DECLARE @CMD nvarchar(8000) 
SET @CMD='BCP db..'+@TableName+' IN file path -T -f -t,-c -E' 
EXEC MASTER..XP_CMDSHELL @CMD
in this code suppose I have no table with name x so I m doing it for the first time, when I run it for the first time it will create a table with x when I run it second time it should update the existing one name with x_getdate() but it is creating new table, what i want is when it run for the second time it will update the existing table and load data in it.
 

Answers (1)