有两种方法。
A) 最好的是:
string connectionString =
ConsoleApplication1.Properties.Settings.Default.ConnectionString;
//
// In a using statement, acquire the SqlConnection as a resource.
//
using (SqlConnection con = new SqlConnection(connectionString))
{
//
// Open the SqlConnection.
//
con.Open();
//
// The following code uses an SqlCommand based on the SqlConnection.
//
using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
}
}
}
在 Dogs1 中放置您的表,使用变量通过代码修改查询。当您可以使用变量从代码中管理所有内容时,为什么要在存储过程中放置非常尴尬的动态表名?
B) 第二种方式(不好但有效):
在您的存储过程中使用sp_executesql,将表名作为参数传递并在存储过程中构建查询,如文档中所示并捕获结果。
这样,您可以逐个构建查询,并在其中放入您想要的所有内容(SQL 保留关键字除外,无论如何您都应该小心)。
declare @SqlString nvarchar(2000)
declare @ParamDef nvarchar(2000)
set @SqlString = N'exec proc1 @param1, @param2, @param3'
set @ParamDef = N'@param1 bit, @param2 bit, @param3 bit'
EXECUTE sp_executesql @SqlString ,@ParamDef, @param1 = 0, @param2 = 1, @param3 = 1
解释一下,sp_executesql 的工作原理是这样的
EXECUTE sp_executesql
N'proc1', -- SQL
N'@param1 bit, @param2 bit, @param3 bit', -- DECLARE
@param1 = 0, @param2 = 1, @param3 = 1 -- VALUES
翻译成什么
EXECUTE sp_executesql
N'proc1', -- SQL
N'@param1 bit, @param2 bit, @param3 bit', -- DECLARE
@param1 = 0, @param2 = 1, @param3 = 1 -- VALUES
-- DECLARE
declare @param1 bit, @param2 bit, @param3 bit
-- VALUES
select @param1 = 0, @param2 = 1, @param3 = 1
-- SQL
proc1
3) 最坏的情况:
通过 Sqlcommand 从 C# 代码调用 sp_executesql