2

I have a query as below

IF EXISTS( SELECT * from @dbname.dbo.tbl1)
   BEGIN
   ...
   END
ELSE
   BEGIN
   ...
   END

Also The code in begin and end part for both if and else is large enough to use as a string for dynamic query. How can I achieve this?

2
  • You can use a try/except. Commented Oct 22, 2013 at 8:51
  • Alfons, I am not sure about try except, can you please explain in brief. Commented Oct 22, 2013 at 9:01

1 Answer 1

1
USE MASTER
DECLARE @dbname sysname
SET @dbname = 'MyDB'

IF EXISTS (SELECT NULL FROM sysdatabases WHERE name = @dbname)
BEGIN
-- Action if true
END
ELSE
BEGIN
-- Action if False
END

In case you want to check for a specific table, as hinted in your question, you can modify as

IF EXISTS (SELECT NULL FROM sysobjects WHERE name = @dbname AND type = 'U')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.