SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 IF EXISTS & UNION
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

mmalaka
Starting Member

Ireland
33 Posts

Posted - 03/20/2013 :  10:40:45  Show Profile  Visit mmalaka's Homepage  Reply with Quote
I hope this is not a tricky one...

I am building a stored procedure which will go through some table in SQL 2000 database to build a table that shows field names from multiple tables and the count of the distinct values

my script is something like this




SELECT @sSQL = 'select distinct(Field1) Field1, count(*) counter from Table1  
 group by  Field1 
 UNION ALL 
 select distinct(Field1)  Field1, count(*) counter from Table2
 group by  Field1'

EXEC sp_executesql @sSQL




Now my issue is that at some cases the required field would not be in Table1 or In table2 but for sure it is in one of the tables at least...

So How can I add a validation into my script

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 03/20/2013 :  10:55:08  Show Profile  Reply with Quote
just add a validation like

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME =<yourcolumn> AND TABLE_NAME = <yourtable>)

your select...


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

bandi
Flowing Fount of Yak Knowledge

India
2224 Posts

Posted - 03/21/2013 :  00:28:53  Show Profile  Reply with Quote
Why yu need DISTINCT keyword in your script....
Group By clause itself will give you the distinct values

'select distinct(Field1) Field1, count(*) counter from Table1
group by Field1
UNION ALL
select distinct(Field1) Field1, count(*) counter from Table2
group by Field1'



--
Chandu
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000