gpt4 book ai didi

c# - SQL 监控和插入

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:53 25 4
gpt4 key购买 nike

来自另一个线程,该线程为我提供了有关如何向 SQL Server 添加监控的信息......

See SQL From EntityFramework with Collection-like Queries

这很好用,但我想更进一步。我希望能够在交易发生时将评论添加到日志中。

不过,我希望能够将注释写入到 SQL 日志记录中。就像,我可以做一个查询,然后调用 Debugger.Logger.Write("Some kind of comment") 所以我知道什么是什么。我不太了解 SQL,因此我试图了解正在运行的内容以及运行位置。

非常感谢任何帮助。我想我必须运行另一个 SQL 查询才能将评论“插入”到查询流中。

我设计我的数据上下文 (DbContext)

using(var context = new SampleDataContext(dbModel))
{
// ...
// prepare a logging model.
if (Debugger.SetupLog(context))
Console.WriteLine("Logging Enabled...");
// open up the debugger log
Debugger.Open();
}

public class SampleDataContext: DbContext, IDisposable
{
public new void Dispose()
{
Debugger.Log(this);

base.Dispose();
}
}

然后是 Debugger 类..

public static class Debugger
{
public static System.IO.TextWriter File
{
get;
set;
}
public static void Open()
{
// open a file for storing SQL results from queries
File = new System.IO.StreamWriter("results.sql", false);
}

public static void Write(string text)
{
File.WriteLine(text);
}

public static bool Log(SampleDataContext context)
{
var results = context.Database.Connection.CreateCommand();
results.CommandText = Sql.Review;
context.Database.Connection.Open();

System.Data.Common.DbDataReader resultsReader;
do
{
resultsReader = results.ExecuteReader();
}
while (resultsReader == null);

Console.WriteLine("Discovered a Data Reader");

// Retrieves the schema of the table.
var dtSchema = resultsReader.GetSchemaTable();

string strRow; // represents a full row
// Reads the rows one by one from the SqlDataReader
// transfers them to a string with the given separator character and
// writes it to the file.
while (resultsReader.Read())
{
Console.WriteLine("Reading Data Reader... ");

strRow = "";
for (int i = 0; i < resultsReader.FieldCount; i++)
{
strRow += resultsReader.GetValue(i).ToString();
if (i < resultsReader.FieldCount - 1)
{
strRow += " ";
}
}

Sql.Text.Lexer lexer = new Sql.Text.Lexer();
lexer.Enscribe();

var matches = lexer.Tokenize(strRow);
matches.ForEach(x =>
{
strRow = strRow.Replace(x.Value, Environment.NewLine);
});

File.WriteLine(strRow);
}

File.Close();
context.Database.Connection.Close();

return false;
}

public static bool SetupLog(SampleDataContext context)
{
var command = context.Database.Connection.CreateCommand();
command.CommandText = Sql.Record;

context.Database.Connection.Open();
command.ExecuteNonQuery();
context.Database.Connection.Close();

return true;
}
}

我基本上已经将以下 SQL 插入到 C# 中的资源中......

这是“Project.SQL.Record”。

IF EXISTS(SELECT * FROM sys.server_event_sessions WHERE name='test_trace')
DROP EVENT SESSION [test_trace] ON SERVER;
CREATE EVENT SESSION [test_trace]
ON SERVER
ADD EVENT sqlserver.sp_statement_completed(
ACTION (package0.callstack, sqlserver.session_id, sqlserver.sql_text)
-- WHERE (([sqlserver].[username]='Domain\Username'))
),
ADD EVENT sqlserver.sql_statement_completed(
ACTION (package0.callstack, sqlserver.session_id, sqlserver.sql_text)
--WHERE (([sqlserver].[username]='Domain\Username'))
)
ADD TARGET package0.ring_buffer
WITH (MAX_MEMORY = 4096KB, EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS,
MAX_DISPATCH_LATENCY = 1 SECONDS, MAX_EVENT_SIZE = 0KB,
MEMORY_PARTITION_MODE = NONE, TRACK_CAUSALITY = OFF, STARTUP_STATE = OFF)

ALTER EVENT SESSION [test_trace] ON SERVER STATE = START

然后我有另一个,“Project.SQL.Review”。

DECLARE 
@session_name VARCHAR(200) = 'test_trace'

SELECT
pivoted_data.*
FROM
(
SELECT MIN(event_name) AS event_name,
MIN(event_timestamp) AS event_timestamp,
unique_event_id,
CONVERT ( BIGINT, MIN (
CASE
WHEN d_name = 'cpu'
AND d_package IS NULL
THEN d_value
END ) ) AS [cpu],
CONVERT ( BIGINT, MIN (
CASE
WHEN d_name = 'duration'
AND d_package IS NULL
THEN d_value
END ) ) AS [duration],
CONVERT ( BIGINT, MIN (
CASE
WHEN d_name = 'object_id'
AND d_package IS NULL
THEN d_value
END ) ) AS [object_id],
CONVERT ( INT, MIN (
CASE
WHEN d_name = 'object_type'
AND d_package IS NULL
THEN d_value
END ) ) AS [object_type],
CONVERT ( DECIMAL(28,0), MIN (
CASE
WHEN d_name = 'reads'
AND d_package IS NULL
THEN d_value
END ) ) AS [reads],
CONVERT ( VARCHAR(MAX), MIN (
CASE
WHEN d_name = 'session_id'
AND d_package IS NOT NULL
THEN d_value
END ) ) AS [session_id],
CONVERT ( INT, MIN (
CASE
WHEN d_name = 'source_database_id'
AND d_package IS NULL
THEN d_value
END ) ) AS [source_database_id],
CAST((SELECT CONVERT ( VARCHAR(MAX), MIN (
CASE
WHEN d_name = 'sql_text'
AND d_package IS NOT NULL
THEN d_value
END ) ) AS [processing-instruction(x)] FOR XML PATH('') ) AS XML) AS [sql_text],
CONVERT ( DECIMAL(28,0), MIN (
CASE
WHEN d_name = 'writes'
AND d_package IS NULL
THEN d_value
END ) ) AS [writes]
FROM
(
SELECT
*,
CONVERT(VARCHAR(400), NULL) AS attach_activity_id
FROM
(
SELECT
event.value('(@name)[1]', 'VARCHAR(400)') as event_name,
event.value('(@timestamp)[1]', 'DATETIME') as event_timestamp,
DENSE_RANK() OVER (ORDER BY event) AS unique_event_id,
n.value('(@name)[1]', 'VARCHAR(400)') AS d_name,
n.value('(@package)[1]', 'VARCHAR(400)') AS d_package,
n.value('((value)[1]/text())[1]', 'VARCHAR(MAX)') AS d_value,
n.value('((text)[1]/text())[1]', 'VARCHAR(MAX)') AS d_text
FROM
(
SELECT
(
SELECT
CONVERT(xml, target_data)
FROM sys.dm_xe_session_targets st
JOIN sys.dm_xe_sessions s ON
s.address = st.event_session_address
WHERE
s.name = @session_name
AND st.target_name = 'ring_buffer'
) AS [x]
FOR XML PATH(''), TYPE
) AS the_xml(x)
CROSS APPLY x.nodes('//event') e (event)
CROSS APPLY event.nodes('*') AS q (n)
) AS data_data
) AS activity_data
GROUP BY
unique_event_id
) AS pivoted_data;

我的第一个想法是做一个这样的方法..

    public static void WriteSql(SampleDataContext context, string text)
{
var command = context.Database.Connection.CreateCommand();
command.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Comment",System.Data.SqlDbType.VarChar));
command.Parameters["@Comment"].Value = String.Format("--{0}", text);
command.CommandText = String.Format("PRINT '{0}'", text.Replace("'", "''"));
context.Database.Connection.Open();
command.ExecuteNonQuery();
context.Database.Connection.Close();
}

它应该像查询一样执行评论,应该显示在评论中,对吧?好吧,那没有用。所以我对其他想法持开放态度...

最佳答案

您可以为此使用 PRINT 语句。使用带有名为 @Comment 的参数的参数化查询,然后执行

PRINT @Comment

如果评论需要与常规查询轻松区分,您可以添加一个新事件

,
ADD EVENT sqlserver.error_reported(
ACTION (sqlserver.sql_text)
WHERE (([severity]=(1))))

并使用 RAISERROR( @Comment,1,1) 代替。

关于c# - SQL 监控和插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3702721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com