0
我知道爲了防止SQL注入,您可以使用像@param1
和@param2
這樣的參數 - 但是如果您需要多次傳遞相同的參數,您將如何實現此目的?使用多個參數運行SQL查詢
現在,參數將從WinForm上的兩個文本框傳入。但是我的? C#如何處理傳遞參數到SQL字符串中的2個不同位置?
;WITH CTE AS
(
Select
RTRIM(LTRIM(employeename)) As employeename
,psrti
,nes
FROM helper1
)
Select
[Employee Name] = RTRIM(LTRIM(cte.employeename))
,[days employed] = (Select COUNT([days])
FROM [empinfo] jb
WHERE CAST([hiredate] As Date) BETWEEN @startdate AND @enddate
AND RTRIM(LTRIM(jb.employeename)) = RTRIM(LTRIM(cte.employeename)))
,[terminated emps] = (Select Count(empID) from terminate where termination date between @startdate AND @enddate)
FROM hrfile hr1
RIGHT JOIN CTE cte
ON hr1.employeename = cte.employeename
GROUP BY RTRIM(LTRIM(cte.employeename)),RTRIM(LTRIM(hr1.employeename)),cte.nes
ORDER BY RTRIM(LTRIM(cte.employeename)) ASC
我知道只有第1套則params的,我會做
string sql = "";;
using (SqlConnection connection = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(sql, connection))
{
var param1 = new SqlParameter("param1", SqlDbType.DateTime);
var param2 = new SqlParameter("param2", SqlDbType.DateTime);
param1.Value = txtOne.Text;
param2.Value = txtTwo.Text;
command.Parameters.Add(param1);
command.Parameters.Add(param2);
var results = command.ExecuteReader();
}
只要您的SQL字符串格式正確,它將處理讀取您的參數任意次數。然而,我會轉換爲存儲過程,無論如何。 – DaniDev
@DaniDev - 存儲過程會比直接的sql語句更快嗎?在我的測試實例中,直接的sql語句更快。 – BellHopByDayAmetuerCoderByNigh
2個原因: 1.如果您有一些複雜的查詢,則存儲過程更易於調試。 2.它更安全 – DaniDev