2013-08-07 59 views
0

我有兩個數據表 DT1及DT2如何在存儲過程中傳遞的數據表

和我的存儲過程如下所示

ALTER procedure [dbo].[Sp_ShowAllEmpLeaveSummary] 
@TableName1 nvarchar(128) , 
@TableName2 nvarchar(128) 
as 
begin 

DECLARE @Columns VARCHAR(MAX) 

SELECT @Columns = COALESCE(@Columns + ',' + name + '', '' + name + '') FROM (
    SELECT DISTINCT 
    'CAST(ISNULL('[email protected] +'.' + name + ',0) AS VARCHAR) + ''/'' + CAST('[email protected] +'.' + name + ' AS VARCHAR) AS ' + name + ' ' AS name 
FROM sys.columns 
WHERE NAME LIKE '%leave%' 
AND object_id IN (SELECT object_id FROM sys.tables WHERE name IN (''[email protected] +'', ''[email protected] +''))) LeaveColumns 

DECLARE @SQL NVARCHAR(MAX) 
SET @SQL = N' 
SELECT 
'[email protected] +'.empid, 
'[email protected] +'.empname, ' + @Columns + ' 
FROM dt1 
INNER JOIN '[email protected] +' ON '[email protected] +'.empid='[email protected] +'.empid'  


EXECUTE(@SQL) 
end 

,並在UI我通過這樣的

cmd4.Parameters.Add(new SqlParameter("@TableName1", SqlDbType.Structured)).Value = dt1; 
    cmd4.Parameters.Add(new SqlParameter("@TableName2", SqlDbType.Structured)).Value = dt2; 
參數

但顯示錯誤操作數類型衝突:表類型與nvarchar(128)不兼容。所以如果你想傳遞一個表我解決這個問題

感謝

+0

將數據錶轉換爲XML字符串並將其傳遞給Procedure更好。 –

回答

0

,你必須定義表爲一個自定義類型,並將其傳遞到程序。

http://technet.microsoft.com/en-us/library/bb510489.aspx

但它看起來像你只是想將名字傳下去。

所以C#的類型應該是SqlDbType.NVarChar

此外,您應該淨化你的輸入,以防止SQL注入,而不是與sp_

+0

但在我的數據表coloumns不能修復,所以我如何創建一個自定義表?謝謝 – user2516261

+0

我不知道。你究竟想要達到什麼目的? – podiluska

0

前綴存儲過程我不知道我是否完全瞭解你的SP和你如何調用它但你在你的SP構建SQL命令,還必須通過DataTable的名字作爲一個字符串,並把它放到命令這樣

ALTER procedure empl 
@tb1 nvarchar(128) , 
@tb2 nvarchar(128) 
as 
BEGIN 
DECLARE @Columns VARCHAR(MAX) 
SELECT @Columns = COALESCE(@Columns + ',' + name + '', '' + name + '') FROM (
    SELECT DISTINCT 
    'CAST(ISNULL('[email protected] +'.' + name + ',0) AS VARCHAR) + ''/'' + CAST(' 
        [email protected] +'.' + name + ' AS VARCHAR) AS ' + name + ' ' AS name 
    FROM sys.columns 
    WHERE NAME LIKE '%leave%' 
    AND object_id IN (SELECT object_id FROM sys.tables 
         WHERE name IN (@tb1,@tb2)) 
) LeaveColumns 

DECLARE @SQL NVARCHAR(MAX) 
SET @SQL = N' 
SELECT 
'[email protected] +'.empid, 
'[email protected] +'.empname, ' + @Columns + ' 
FROM '[email protected]+' 
INNER JOIN '[email protected] +' ON '[email protected] +'.empid='[email protected] +'.empid'  

-- SELECT @SQL; -- for debug purposes 
EXECUTE(@SQL) 
END 

你的意思是dt1是否是@tb1在SP?!? (爲了更好的可讀性,我縮短了變量名)

相關問題