Last active
October 2, 2019 14:45
-
-
Save chilismaug/1c29b1662e92be2cd3c40a27288364fd to your computer and use it in GitHub Desktop.
Horrible T-SQL hack to count columns without asking the system tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to this StackOverflow post
https://stackoverflow.com/questions/1860457/how-to-count-instances-of-character-in-sql-column