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
    – Peter
    Commented Jan 11, 2023 at 20:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.