2012-02-27 46 views
-4

可能重複:
Parameterizing an SQL IN clause?在SQL Server中傳遞參數 「IN子句」 2008年

我使用的是下面的過程 這裏我使用 「條款」 爲attendancecodeid它接受inetger的價值,我怎麼可以從vb.net傳遞參數給我的「sql程序中的子句」,我試過很多東西沒有爲我尋找解決方案,

alter procedure MPEX_SP_ActivityException_Select 
@startDate date,@endDate date,@AttCode nvarchar(max) 
as 
begin 
set nocount on 
select e.employeeId,e.Badge,e.LastName,e.FirstName,a.Date,ac.code 
from employee e join attendance a on a.fkEmployee=e.employeeId 
join attendancecodes ac on ac.attendancecodesid=a.fkattendancecode 
where a.Date between @startDate and @endDate and ac.code in (@AttCode) 
end 
go 

在此先感謝

Arasu

+0

嗨你能告訴我@AttCode的價值 – 2012-02-27 15:28:16

+2

重複[參數化SQL IN子句?](http://stackoverflow.com/questions/337704/parameterizing-an-sql-in-clause)或http://stackoverflow.com/questions/2944511/sql-server-in-clause-with-a-declared-variable或其他100人 – gbn 2012-02-27 15:34:27

回答

1

這可能是重複的,但我不能找到相應的建議爲存儲過程的表值參數可能是一個可行的解決方案類似的問題的任何答案,並且消除了對動態SQL和SQL注入風險的需求(並非所有黑客都與此風險相關)。表值參數也應該提供更好的性能,因爲執行計劃可以存儲,而不是動態解決方案,其中計劃必須在運行中創建。

CREATE TYPE dbo.AttCodeTableType AS TABLE (AttCode VARCHAR(MAX)) 
GO 
CREATE PROCEDURE PEX_SP_ActivityException_Select (@startDate DATE, @EndDate DATE, @AttCodes dbo.AttCodeTableType READONLY) 
AS 
BEGIN 
    SELECT e.EmployeeID, e.Badge, e.LastName, e.FirstName, a.Date, ac.Code 
    FROM Employee e 
      INNER JOIN Attendance a 
       ON a.FKEmployee = e.EmployeeID 
      INNER JOIN AttendanceCodes ac 
       ON ac.AttendanceCodesID = a.FKAttendanceCode 
      INNER JOIN @AttCodes act 
       ON act.AttCode = ac.Code 
    WHERE a.Date BETWEEN @StartDate AND @EndDate 

END 
GO 

然後執行,你可以使用類似的過程:在vb.net

DECLARE @Table AS dbo.AttCodeTableType 
INSERT @Table VALUES ('Code1'), ('Code2'), ('Code3') 

EXEC PEX_SP_ActivityException_Select @Table 

要創建一個SQL參數從數據表,你會使用類似以下內容:

dim sqlParam as new SqlParameter("@Table", DataTable) 
sqlParam.SqlDbType = SqlDbType.Structured 
sqlParam.TypeName = "dbo.AttCodeTableType" 

閱讀here瞭解更多信息。

最後,接受您的接受率!