在数据库中定义以下存储过程:
CREATE PROCEDURE GetAll_SP
(
@FirstName VARCHAR(50)
)
AS
BEGIN
(SELECT 1, first_name, last_name FROM UsersTable1 WHERE first_name = @FirstName)
UNION
(SELECT 2, first_name, last_name FROM UsersTable2 WHERE first_name = @FirstName)
UNION
(SELECT 3, first_name, last_name FROM UsersTable3 WHERE first_name = @FirstName)
-- ....
END
GO
或以下一个代替您不需要对您的用户位置进行任何控制:
CREATE PROCEDURE GetAll_SP
(
@FirstName VARCHAR(50)
)
AS
BEGIN
(SELECT first_name, last_name FROM UsersTable1 WHERE first_name = @FirstName)
UNION ALL
(SELECT first_name, last_name FROM UsersTable2 WHERE first_name = @FirstName)
UNION ALL
(SELECT first_name, last_name FROM UsersTable3 WHERE first_name = @FirstName)
-- ....
END
GO
然后,在您的代码中:
String firstName = "Jones";
using (SqlCommand cmd = new SqlCommand("GetAll_SP", m_Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = firstName;
m_Connection.Open();
cmd.ExecuteNonQuery();
}