0

In my sql server I got a table named "Product" where a column named "P_name" exist. This column is completely null meaning it has null value in all of its rows eg:

P_name
NULL
NULL
NULL

I wrote two queries. My first query is:

declare @value int
select value = count(P_name) from Product

It returned the value of 0 (which is correct because the P_name column is completely null)

I wrote the second query as follows:

declare @colName nvarchar(max) = 'P_name';
declare @value int
select value = count(@colName) from Product

This returned a value with 3 (which I suppose is wrong)

Isn't both query snippets are same and suppose to return the same value in my case 0? Why they are producing two different values?

0

1 Answer 1

2

In the second query, you are not counting a column, but a static value for each row in the Products table, you actually are running:

SELECT COUNT('P_Name') FROM DBO.Product

instead of giving the column name in the count:

SELECT COUNT(P_Name) FROM DBO.Product
2
  • so what is the solution? Commented Jan 11, 2023 at 20:02
  • Use the first query or dynamic sql if you want to use dynamic columns Commented Jan 11, 2023 at 20:31

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.