Checking table existence with dynamic query?
-
the usual is >> if exists (select * from db.dbo.sysobjects WHERE name ='tableName') >>begin >>drop.. >>end in this case, the table I want to check and drop is created using dynamic sql, so we dont know the eaxct name (can vary). This is what I want to do in pic, >>declare @sql varchar(100) >>declare @no float >>set @no=5 --------------------------------------… >> if exists (select * from db.dbo.sysobjects WHERE name ='tableName' + @no) >>--condition OR >>select @sql= 'if exists (select * from db.dbo.sysobjects WHERE name =''tableName''+@no+')' >>exec (@sql) etc.. None of them work, How can I do something like that?
-
Answer:
use a table variable or a temp table to load the information about the table names or ensure the table name is populated before the if exists statement gets executed. You need to ensure that the value gets populated before the statement is executed. Use the syntax something like this set @SQL = 'if exists (select * from db.dbo.sysobjects WHERE name ='+@tableName+')' exec (@sql)
ejaeja at Yahoo! Answers Visit the source
Other answers
declare @tbl varchar(50) select @tbl='abc' exec('declare @is_ex int; select @is_ex=count(table_name) from information_schema.tables where table_name='''+@tbl+'''; if @is_ex>0 ...')
Related Q & A:
- How can I optimize this dynamic SQL query in oracle with PL/SQL?Best solution by docs.oracle.com
- How to add a column header to the dynamic table?Best solution by stackoverflow.com
- How to convert sql query to Hibernate Criteria query?Best solution by Stack Overflow
- How to apply media query in table?Best solution by stackoverflow.com
- How to make a dynamic table in PHP?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.