Skip to content

Instantly share code, notes, and snippets.

@chilismaug
Last active October 2, 2019 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chilismaug/1c29b1662e92be2cd3c40a27288364fd to your computer and use it in GitHub Desktop.
Save chilismaug/1c29b1662e92be2cd3c40a27288364fd to your computer and use it in GitHub Desktop.
Horrible T-SQL hack to count columns without asking the system tables
-- how many columns in my table?
-- have to count null elements too
DECLARE @rowString AS VARCHAR(MAX)
DECLARE @StringToCount1 AS VARCHAR(100) = '</'
DECLARE @StringToCount2 AS VARCHAR(100) = '/>'
DECLARE @StringCount AS INT
DECLARE @ColCount AS INT
SELECT @rowString = (SELECT TOP 1 * FROM PE_CS_CUBE ORDER BY LASTUPDATED DESC FOR XML PATH, ELEMENTS XSINIL )
SET @StringCount = (LEN(@rowString) - LEN(REPLACE(@rowString, @StringToCount1,'')))/COALESCE(NULLIF(LEN(@StringToCount1), 0), 1)
+ (LEN(@rowString) - LEN(REPLACE(@rowString, @StringToCount2,'')))/COALESCE(NULLIF(LEN(@StringToCount2), 0), 1)
--protect division from zero
SELECT @rowString
SET @ColCount = @StringCount - 1
PRINT @ColCount
@chilismaug
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment