Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table with Select Statements, Executing Dynamic SQL and Returning Values

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.

like image 300
Martin Avatar asked Oct 04 '10 17:10

Martin


1 Answers

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)
like image 128
KM. Avatar answered Nov 12 '22 23:11

KM.