日期:2014-05-18 浏览次数:20783 次
CREATE TABLE Test1 ( ID INT IDENTITY(1,1) NOT NULL, UserName VARCHAR(100) NOT NULL, Age INT ) INSERT INTO Test1 SELECT 'A',12 UNION SELECT 'B',13 UNION SELECT 'C',14 UNION SELECT 'D',15 DECLARE @TableColumn TABLE(Id INT IDENTITY(1,1),ColumnName VARCHAR(100)) DECLARE @TotalNum INT DECLARE @Line INT DECLARE @Count Int DECLARE @Sqls NVARCHAR(4000) DECLARE @ColumnName VARCHAR(100) SET @Line = 1 INSERT INTO @TableColumn SELECT name FROM SYS.columns WHERE OBJECT_NAME(OBJECT_ID) = 'Test1' SELECT @TotalNum = MAX(ID) FROM @TableColumn WHILE @Line <= @TotalNum BEGIN SELECT @ColumnName = ColumnName FROM @TableColumn WHERE Id = @Line set @Sqls='select @a=count(1) from Test1 WHERE ' + @ColumnName + '= ''15''' exec sp_executesql @Sqls,N'@a int output',@Count output IF @Count > 0 BEGIN SELECT '数值所在列为:' + @ColumnName END SET @Line = @Line + 1 END
------解决方案--------------------
把 3楼的 改一下就可以。这里引用一下3楼的。
用like
CREATE TABLE Test1 ( ID INT IDENTITY(1,1) NOT NULL, UserName VARCHAR(100) NOT NULL, Age INT ) INSERT INTO Test1 SELECT 'A',12 UNION SELECT 'B',13 UNION SELECT 'C',14 UNION SELECT 'D',15 DECLARE @TableColumn TABLE(Id INT IDENTITY(1,1),ColumnName VARCHAR(100)) DECLARE @TotalNum INT DECLARE @Line INT DECLARE @Count Int DECLARE @Sqls NVARCHAR(4000) DECLARE @ColumnName VARCHAR(100) SET @Line = 1 INSERT INTO @TableColumn SELECT name FROM SYS.columns WHERE OBJECT_NAME(OBJECT_ID) = 'Test1' SELECT @TotalNum = MAX(ID) FROM @TableColumn WHILE @Line <= @TotalNum BEGIN SELECT @ColumnName = ColumnName FROM @TableColumn WHERE Id = @Line set @Sqls='select @a=count(1) from Test1 WHERE ' + @ColumnName + ' like ''15%''' exec sp_executesql @Sqls,N'@a int output',@Count output IF @Count > 0 BEGIN SELECT '数值所在列为:' + @ColumnName END SET @Line = @Line + 1 END