2

Like we had query to find no of columns in a Table, is there any similar query to find total no of columns in a Sql Server View ?

0

4 Answers 4

5

Even simpler is to use sys.columns.

select count(*)
from sys.columns
where OBJECT_ID = OBJECT_ID('YourView')
Sign up to request clarification or add additional context in comments.

1 Comment

This is simpler indeed. The advantage of the other approaches is: They would work with any ad-hoc statement, joined sources etc. But the OP wasn't asking for this actually. So +1 from my side ;-)
3

Similar to Larnu's comment, I tend to prefer the Table-Valued-Function

Example

Declare @tsql nvarchar(max) =  N'Select * from YourView_Table_Or_Query'

Select column_ordinal
      ,name
      ,system_type_name 
 From  sys.dm_exec_describe_first_result_set(@tsql,null,null )  

-- Or for the Count

Select ColumnCnt=count(*) 
 From  sys.dm_exec_describe_first_result_set(@tsql,null,null)  

2 Comments

Ah, yes! forgot about the TVF (introduced with v2012). +1 From my side
As did I. I should really begin using that; far easier than shoving everything in a temporary table.
1

Besides the rather clumsy procedure sp_describe_first_reuslt_set you can use the generic abilities of XML:

SELECT (SELECT TOP 1 * FROM YourView FOR XML RAW, ELEMENTS XSINIL ,TYPE).value('count(/row/*)','int');

Edit: Forgot to add ELEMENTS XSNIL which would omit columns with a value of NULL otherwise...

Comments

0

--this might help

SELECT v.name, count(1) ColumnCount
FROM SYS.VIEWS v
INNER JOIN SYS.all_columns c ON v.object_id = c.object_id
WHERE v.name IN (SELECT name FROM sys.VIEWS)
GROUP BY v.name
ORDER BY v.name

SELECT name FROM sys.VIEWS, can be replaced by viewname/s or query which returns viewname/s

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.