c# sql 获取表下面组的名称 和组下面表的名称
时间: 2024-04-08 12:30:45 浏览: 61
sql 数据库 得到表列名
你可以使用以下代码来获取表下面的组名称和组下面的表名称:
```csharp
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "YourConnectionString"; // 替换为你的数据库连接字符串
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 查询表下面的组名称
string groupQuery = "SELECT DISTINCT g.name FROM sys.tables t INNER JOIN sys.indexes i ON t.object_id = i.object_id INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id INNER JOIN sys.objects o ON c.object_id = o.object_id INNER JOIN sys.schemas s ON o.schema_id = s.schema_id INNER JOIN sys.sysusers u ON o.principal_id = u.uid INNER JOIN sys.database_permissions dp ON o.object_id = dp.major_id INNER JOIN sys.database_principals gp ON dp.grantee_principal_id = gp.principal_id INNER JOIN sys.database_permissions dp2 ON o.object_id = dp2.major_id INNER JOIN sys.database_principals g ON dp2.grantor_principal_id = g.principal_id WHERE g.type_desc = 'DATABASE_ROLE' AND dp.state_desc = 'GRANT' AND dp.permission_name = 'SELECT' AND t.name = 'YourTableName';"; // 替换为你的表名
using (SqlCommand groupCommand = new SqlCommand(groupQuery, connection))
{
using (SqlDataReader groupReader = groupCommand.ExecuteReader())
{
Console.WriteLine("组名称:");
while (groupReader.Read())
{
string groupName = groupReader.GetString(0);
Console.WriteLine(groupName);
}
}
}
// 查询组下面的表名称
string tableQuery = "SELECT DISTINCT t.name FROM sys.tables t INNER JOIN sys.indexes i ON t.object_id = i.object_id INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id INNER JOIN sys.objects o ON c.object_id = o.object_id INNER JOIN sys.schemas s ON o.schema_id = s.schema_id INNER JOIN sys.sysusers u ON o.principal_id = u.uid INNER JOIN sys.database_permissions dp ON o.object_id = dp.major_id INNER JOIN sys.database_principals gp ON dp.grantee_principal_id = gp.principal_id INNER JOIN sys.database_permissions dp2 ON o.object_id = dp2.major_id INNER JOIN sys.database_principals g ON dp2.grantor_principal_id = g.principal_id WHERE g.type_desc = 'DATABASE_ROLE' AND dp.state_desc = 'GRANT' AND dp.permission_name = 'SELECT' AND g.name = 'YourGroupName';"; // 替换为你的组名
using (SqlCommand tableCommand = new SqlCommand(tableQuery, connection))
{
using (SqlDataReader tableReader = tableCommand.ExecuteReader())
{
Console.WriteLine("表名称:");
while (tableReader.Read())
{
string tableName = tableReader.GetString(0);
Console.WriteLine(tableName);
}
}
}
connection.Close();
}
Console.ReadLine();
}
}
```
请把上述代码中的 `YourConnectionString` 替换为你的数据库连接字符串,`YourTableName` 替换为你的表名,`YourGroupName` 替换为你的组名。运行代码后,你将会得到表下面的组名称和组下面的表名称。
阅读全文