带有Select语句、执行动态SQL并返回值的表
我有一个 select 语句,它返回一个充满 SELECT 语句的表(它遍历每个表中的每一列并创建一个 select 来查找该列是否包含任何错误数据)。
我需要获取这个充满 SELECT 语句的表,执行它们,并查看其中是否有任何返回行。如果计数(*)> 0,那么我想打印出一些数据。
我想我必须使用光标,但我不知道如何实现这一点。
这是我的代码来获取坏数据的计数。
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
这将返回一个表,其中包含如下行:
SELECT count(*), ' All_MW_Users - LastName ' FROM [All_MW_Users] WHERE UNICODE(SUBSTRING([LastName],Len([LastName]),1)) = 0
我需要执行此选择,并且如果 count(*) > > 0,然后打印第二列。我不想在结果或消息中显示任何内容,除非有数据要显示。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
try this:
首先,我将您正在构建的 SQL 字符串稍微更改为:
当满足条件时,这将为您提供字符串,而当不满足条件时,将为您提供 NULL。
至于光标本身的机制:
First, I'd change the SQL string you're building slightly to be
This would get you the string when the condition is met and NULL when it is not.
As for the mechanics of the cursor itself:
sp_executesql 可以接受输出参数:
sp_executesql can accept output parameters: