I have a select statement that returns a table full of SELECT statements (It goes through every column in every table and creates a select to find if that column contains any bad data).
I need to take this table full of SELECT statements, execute them, and see if any of them return rows. If the count(*) > 0, then I want to print out some data.
I was thinking I had to use a cursor, but I have no idea how I would accomplish that.
Here is my code to get the count of bad data.
SELECT 'SELECT count(*), '' '+sysobjects.name + ' - ' + syscolumns.name +
' '' FROM ['
+sysobjects.name + '] WHERE UNICODE(SUBSTRING(['+syscolumns.name+'],Len(['+syscolumns.name+']),1)) = 0'
FROM sysobjects
JOIN syscolumns ON sysobjects.id = syscolumns.id
JOIN systypes ON syscolumns.xtype=systypes.xtype
WHERE sysobjects.xtype='U' and systypes.name IN ('varchar', 'nvarchar')
ORDER BY sysobjects.name,syscolumns.colid
This returns a table with rows like:
SELECT count(*), ' All_MW_Users - LastName ' FROM [All_MW_Users] WHERE UNICODE(SUBSTRING([LastName],Len([LastName]),1)) = 0
I need to execute this select, and if the count(*) > 0, then print the second column. I don't want to show anything in the results or messages unless there is data to show.
try this:
DECLARE @SQL nvarchar(max)
SET @SQL='DECLARE @TempTable table (RowID int identity(1,1), CountOf int, DescriptionOf nvarchar(500));'
SELECT @SQL=@SQL+';INSERT @TempTable (CountOf,DescriptionOf ) SELECT count(*), '' '+sysobjects.name + ' - ' + syscolumns.name +
' '' FROM ['
+sysobjects.name + '] WHERE UNICODE(SUBSTRING(['+syscolumns.name+'],Len(['+syscolumns.name+']),1)) = 0'
FROM sysobjects
JOIN syscolumns ON sysobjects.id = syscolumns.id
JOIN systypes ON syscolumns.xtype=systypes.xtype
WHERE sysobjects.xtype='U' and systypes.name IN ('varchar', 'nvarchar')
ORDER BY sysobjects.name,syscolumns.colid
SET @SQL=@SQL+';SELECT * FROM @TempTable WHERE CountOF>0' --make sure there is no truncation of the commands
EXEC (@SQL)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With