假设您有一个长而复杂的查询来提取需要一些参数的所需结果。任何都可以,但为了举例:
SELECT
q.PROD_ID, q.NAME, q.STANDARD_PROD, q.DESCRIPTION, q.PART_NUMBER,
q.COMMENTS, q.DESCRIPTION_URL,
PROD_CATEGORY.DESCRIPTION AS CATEGORY_DESCRIPTION,
PROD_TYPES.DESCRIPTION AS PROD_TYPE
FROM
(SELECT
PROD.PROD_ID,
PROD.PROD_TYPE_ID,
PROD.NAME,
PROD.STANDARD_PROD,
PROD.PROD_CATEGORY_ID,
PROD.DESCRIPTION,
PROD.PART_NUMBER,
PROD.COMMENTS,
PROD.DESCRIPTION_URL
FROM
(SELECT
PROD_ID,
PROD_TYPE_ID
FROM
XREF_PRODSYS
WHERE
(PROD_TYPE_ID = (SELECT
PROD_TYPE_ID
FROM
PROD_TYPES
WHERE
(NAME LIKE @prod_type_name)))) AS p
LEFT OUTER JOIN PROD ON p.PROD_ID = PROD.PROD_ID
WHERE
(PROD.NAME LIKE @prod_name)
AND (PROD.HIDDEN = 0)) AS q
LEFT OUTER JOIN PROD_CATEGORY ON q.PROD_CATEGORY_ID = PROD_CATEGORY.PROD_CATEGORY_ID
LEFT OUTER JOIN PROD_TYPES ON q.PROD_TYPE_ID = PROD_TYPES.PROD_TYPE_ID
此特定查询采用两个参数,可能通过 GET/POST 传递给 .NET Web 应用程序。
有没有更简洁的方法来存储这么长的查询,而不是把它放在 webapp 页面的 C# 源代码中?我知道下面的“快速而肮脏”的方法效果很好,但它确实使代码扩展了很多并且变得有点难以管理。例如:
//inside Page_Load...
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.Parameters.Add("@prod_type_name", SqlDbType.VarChar).Value = _type_name;
cmd.Parameters.Add("@prod_name", SqlDbType.VarChar).Value = _prod_name;
cmd.CommandText = @"
SELECT q.PROD_ID, q.NAME, q.STANDARD_PROD, q.DESCRIPTION, q.PART_NUMBER, q.COMMENTS, q.DESCRIPTION_URL,
PROD_CATEGORY.DESCRIPTION AS CATEGORY_DESCRIPTION, PROD_TYPES.DESCRIPTION AS PROD_TYPE
FROM (SELECT PROD.PROD_ID, PROD.PROD_TYPE_ID, PROD.NAME, PROD.STANDARD_PROD, PROD.PROD_CATEGORY_ID, PROD.DESCRIPTION,
PROD.PART_NUMBER, PROD.COMMENTS, PROD.DESCRIPTION_URL
FROM (SELECT PROD_ID, PROD_TYPE_ID
FROM XREF_PRODSYS
WHERE (PROD_TYPE_ID =
(SELECT PROD_TYPE_ID
FROM PROD_TYPES
WHERE (NAME LIKE @prod_type_name)))) AS p LEFT OUTER JOIN
PROD ON p.PROD_ID = PROD.PROD_ID
WHERE (PROD.NAME LIKE @prod_name) AND (PROD.HIDDEN = 0)) AS q LEFT OUTER JOIN
PROD_CATEGORY ON q.PROD_CATEGORY_ID = PROD_CATEGORY.PROD_CATEGORY_ID LEFT OUTER JOIN
PROD_TYPES ON q.PROD_TYPE_ID = PROD_TYPES.PROD_TYPE_ID
";
//... do stuff with cmd