在LINQPad中有没有办法使用LINQ访问SYSOBJECTS表或各种INFORMATION_SCHEMA.xxx视图?
我花了很多时间在我们庞大的公司数据库中搜索部分名称,因为有太多的表和存储过程来记住它们的名称。
我知道我可以在LINQPad中输入和运行SQL,但我想在LINQ而不是SQL中执行此操作,因为LINQ更有趣:)
由于
Xanthalas
答案 0 :(得分:5)
您还可以将SQL嵌入到LINQ语句中,如下所示:
void Main()
{
var matches = this.ExecuteQuery<SysObject>("SELECT name, type_desc AS "
+ "TypeDesc FROM [sys].[objects]");
foreach(var match in matches)
Console.WriteLine("{0,-30}{1}", (match.Name + ":"), match.TypeDesc);
}
// Define other methods and classes here
class SysObject
{
public string Name;
public string TypeDesc;
// etc...
}
默认情况下,LinqPad不使用等宽字体作为结果,但您可以通过将以下位css粘贴到“编辑 - &gt;首选项 - &gt;结果 - &gt;启动编辑器”中轻松更改它
body { font-family:Consolas,monospace; }
答案 1 :(得分:5)
是的,你可以。
您所要做的就是在选定的连接中包含系统视图和SP,并使用LINQ,如下所示:
sys.Sysobjects.Where(sp => sp.Xtype == "P") // returns SPs
sys.Sysobjects.Where(t => t.Xtype == "U") // returns Tables
或直接使用sys.Views [示例返回包含字符串“person”的所有表]:
sys.Tables.Join(sys.Columns,
t => t.Object_id,
c => c.Object_id,
(t, c) => new { t, c })
.Where(x => x.c.Name.Contains("person"))
.Select(x => new { ObjName = x.t.Name,
ChildName = x.c.Name } )
.Distinct()
答案 2 :(得分:0)
from d in Databases
select d
当LINQPad中的数据库连接指向master数据库时。
答案 3 :(得分:0)
创建一个包含SYSOBJECTS内容的新表,然后在新表中搜索</ p>
select * into SYSOBJECTS_COPY from SYS.OBJECTS
from o in SYSOBJECTS_COPY.AsEnumerable()
where Regex.IsMatch( d.Name, "partialName", RegexOptions.IgnoreCase )
select o
答案 4 :(得分:0)
此代码还返回对象定义,并允许您在定义中搜索(如果需要)。
void Main()
{
var matches = FetchObjects(true);
var searchTerm = "tblName"; //<--Change this to filter for what you are looking for
bool searchName = true; //search the object name
bool searchDef = false; //search inside object definition (ie the stored procedure definition)
TypeDescs typeDesc = TypeDescs.Any; //specify whether you want to limit your search to tables or stored procedures
matches
.Where(x=> (
(searchName && x.Name.Contains(searchTerm))
|| (searchDef && (x.ObjectDefinition!=null && x.ObjectDefinition.Contains(searchTerm))) )
&& (typeDesc==TypeDescs.Any || x.TypeDesc == typeDesc.ToString())
)
.Select(x=> new {x}).Dump();
}
IEnumerable<SysObject> FetchObjects(bool includeDefinitions){
return this.ExecuteQuery<SysObject>("SELECT Name=convert(varchar(30), name), type_desc AS "
+ " TypeDesc "
+ string.Format(", ObjectDefinition={0}", (includeDefinitions)?"OBJECT_DEFINITION (OBJECT_ID(name))":"NULL")
+ " FROM [sys].[objects]");
}
enum TypeDescs {Any, SQL_STORED_PROCEDURE, USER_TABLE}
class SysObject
{
public string Name;
public string TypeDesc;
public string ObjectDefinition;
}
答案 5 :(得分:0)
除了@ Nick的回答之外,here是一个片段,它在markdown中生成表信息并在VS Code中打开它。