如何在c#中运行sql server中的代码

SqlCommand cmd = new SqlCommand("select Developer from Stackoverflow where UserID='786' and Developer='Sufiyan'", con); if (con.State == ConnectionState.Closed) { con.Open(); } SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { string codeSnippet = reader["CodeSnippet"].ToString(); dynamic script = CSScript.LoadCode(@" using System; using System.Windows.Forms; using System.Collections.Generic; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; public class RunFromSqlServer { public void RunCode(string developer){" + codeSnippet + "}"+ "}").CreateObject("*");script.RunCode("Mohammad Sufiyan Shaikh"); } if (con.State == ConnectionState.Open) { con.Close(); } 

其中codeSnippet可以是你想要运行的任何c#代码我已经发布了这个问题并给出了帮助其他人的答案..

你不能真正混合和匹配SQL和c#代码。 有一种方法可以在SQL Server 2005+上运行.net代码,使用一个名为SQL CLR的function,但是你可以做什么有限制。 这是一个用于创建SQL CLR用户定义函数的教程http://msdn.microsoft.com/en-us/library/w2kae45k%28v=vs.80%29.aspx

您还可以使用SQL CLR触发器和存储过程创建其他内容。 研究SQL CLR以获取更多信息。

在我阅读这个问题之前,我不知道CS-Script是否存在。 非常有趣的技术。 从文档中看来,您使用它是错误的。

http://www.csscript.net/help/script_hosting_guideline_.html

你应该做这样的事情:

 var result = CSScript.Eval("Mohammad Sufiyan Shaikh", @"func(string user) {" + codeSnippet + "); }"); 

嗯,这很酷,但我怀疑它是非常有用的,因为你失去了很多从编译代码中获得的好东西。 例如,如果有人将语法错误的代码插入数据库表,您的程序会突然崩溃。