如何正确地形成一个数组循环以在SQL语句中使用

huangapple go评论52阅读模式
英文:

How to properly form an array loop to use in an SQL statement

问题

我正在尝试使用数组提取表信息。我的数组构建似乎没问题,它包含了正确数量的行。

到目前为止,这是我的代码:

DECLARE @myTableVariable TABLE (name varchar(30))

insert into @myTableVariable SELECT [NAME] FROM SYS.DATABASES

SELECT
   TABLE_CATALOG AS 'DATABASE',
   TABLE_NAME,
   COLUMN_NAME,
   DATA_TYPE,
   CHARACTER_MAXIMUM_LENGTH
FROM @myTableVariable.information_schema.columns

我希望我的问题有意义!提前感谢!

我知道在SQL语句部分需要使用某种循环,但我不确定如何正确地构建它。我一直在查找,但没有找到答案。

英文:

I am trying to use an array to pull table information. My array build seems to be fine and it is created with the correct number of rows.

THis is what I have so far:

DECLARE @myTableVariable TABLE (name varchar(30))

insert into @myTableVariable SELECT [NAME] FROM SYS.DATABASES

SELECT
   TABLE_CATALOG AS 'DATABASE',
   TABLE_NAME,
   COLUMN_NAME,
   DATA_TYPE,
   CHARACTER_MAXIMUM_LENGTH
FROM @myTableVariable.information_schema.columns

I hope my question makes sense! Thanks in advance!

I know there needs to be some sort of WHILE loop around the SQL statement portion, but I am unsure how to properly form it. I have been looking around with no luck.

答案1

得分: 1

你可以通过一点动态SQL来实现你尝试做的事情。

在SQL Server中,我更倾向于使用系统DMV而不是Information_Schema(后者实际上只是为了兼容性而存在),但是假设你有访问数据库的权限并且没有冲突的字符集,以下内容应该有所帮助:

declare @Sql nvarchar(max);
with db as (select name from master.sys.databases where database_id > 4)
select @Sql = string_agg(Convert(nvarchar(max), Concat(N'
  select 
  TABLE_CATALOG as [DATABASE],
  TABLE_NAME,
  COLUMN_NAME,
  DATA_TYPE,
  CHARACTER_MAXIMUM_LENGTH
  from ', QuoteName(db.name), N'.information_schema.columns')), N' union all ')
from db;
select @Sql;
exec (@Sql);
英文:

You can achieve what you're trying to do with a little bit of Dynamic SQL.

In SQL Server I would prefer to use the system DMVs instead of Information_Schema (which really only exist for compatability) however, assuming you have permission to access the database(s) and don't have conflicting collations, the following should help:

declare @Sql nvarchar(max);
with db as (select name from master.sys.databases where database_id > 4)
select @Sql = string_agg(Convert(nvarchar(max), Concat(N'
  select 
  TABLE_CATALOG as [DATABASE],
  TABLE_NAME,
  COLUMN_NAME,
  DATA_TYPE,
  CHARACTER_MAXIMUM_LENGTH
  from ', QuoteName(db.name), N'.information_schema.columns')), N' union all ')
from db;
select @Sql;
exec (@Sql);

huangapple
  • 本文由 发表于 2023年2月10日 05:51:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定