Click here to Skip to main content
15,891,673 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why am I getting the error message: Invalid column name 'theField' with the following query?

SQL
Declare @aField varchar
Set @aField = 'nameFirst'

Select 
	Case ISNULL(@aField,'Null') 
	When 'Null' Then 'Null'
	Else 'NotNull'
	End as theField,
	COUNT(*)
From
	tblCustomer
Group By 
	theField
Posted
Updated 9-Oct-15 3:24am
v3
Comments
dhMac 9-Oct-15 9:03am    
Instead of putting a new field name in the query each time I just replace the 'nameFirst' with a new new name. I want the query to just tell me how many row are Null and how many aren't Null.
PIEBALDconsult 9-Oct-15 9:11am    
The ISNULL isn't doing anything useful for you.
You might also try SELECT COUNT(*) [Total] , COUNT([nameFirst]) [NotNull] FROM [tblCustomer] and then calculate how many are null.

Because there is no column on tblCustomer called theField
Sometimes you can get around this by doing something like
SQL
Select
 Case ISNULL(@aField,'Null')
 When 'Null' Then 'Null'
 Else 'NotNull'
 End as theField,
 COUNT(*)
 From
 tblCustomer
 Group By 1
but in this case you will get another error
Quote:
Each GROUP BY expression must contain at least one column that is not an outer reference.

Again because you are trying to use Group By with something that does not use columns on the table.

It's not entirely clear what you are trying to do with @afield
 
Share this answer
 
You can't use alias column name with GROUP BY OR WHERE clause. You can use Common Table Expression to solve the issue.

Declare @aField varchar
Set @aField = 'nameFirst'

;WITH CTE AS(
Select Case ISNULL(@aField,'Null') When 'Null' Then 'Null' Else 'NotNull' End as theField
From tblCustomer)
SELECT COUNT(*) FROM CTE
Group By
theField
 
Share this answer
 
This will get what you want without any group-by:

SQL
Declare @aField varchar
Set @aField = 'sort_order'
 
Select
  'Null', COUNT(@aField) from EDIT_code
 where @aField is null
UNION
 select 
 'NotNull', COUNT(@aField) from EDIT_code
 where @aField is not null
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900