2009-09-21 159 views
0

我有一個動態查詢其內容是這樣SQL SERVER 2008動態查詢問題

Alter PROCEDURE dbo.mySP 
    -- Add the parameters for the stored procedure here 
    (
     @DBName varchar(50), 
     @tblName varchar(50) 

    ) 

AS 
BEGIN 
-- SET NOCOUNT ON added to prevent extra result sets from 
-- interfering with SELECT statements. 
SET NOCOUNT ON; 

-- Insert statements for procedure here 
declare @string as varchar(50) 
declare @string1 as varchar(50) 

set @string1 = '[' + @DBName + ']' + '.[dbo].' + '[' + @tblName + ']' 

set @string = 'select * from ' + @string1 

exec @string 

END

我打電話這樣

dbo.mySP 'dbtest1','tblTest' 

而且我遇到一個錯誤

"Msg 203, Level 16, State 2, Procedure mySP, Line 27 
The name 'select * from [dbtest1].[dbo].[tblTest]' is not a valid identifier." 

什麼是wr翁?和如何克服?提前

感謝

+1

我真希望你正在檢查SQL注入的地方... – GilaMonster 2009-09-21 12:39:51

+1

我不願意認爲任何人都會考慮寫這樣的sp。請閱讀: http://www.sommarskog.se/dynamic_sql.html – HLGEM 2009-09-21 14:37:57

回答

5

它認爲的@string內容請參閱存儲過程名稱。你需要把

EXEC (@string) 

或更好的使用存儲過程sp_executesql

你也應該設置一些後衛代碼來檢查要傳遞的價值觀是真正的表格和數據庫的名稱。您可以查詢INFORMATION_SCHEMA中的視圖以驗證輸入。

您可以在我的博客上閱讀safer dynamic SQL的更多信息。

4

變化

exec @string 

exec(@string) 

這裏有一個工作SP我只是測試:

CREATE PROCEDURE [dbo].[test] 
    @DBName varchar(50), 
    @tblName varchar(50) 
AS 
BEGIN 
    SET NOCOUNT ON; 

    DECLARE @string AS VARCHAR(50) 
    DECLARE @string1 AS VARCHAR(50) 

    SET @string1 = '[' + @DBName + '].[dbo].[' + @tblName + ']' 
    SET @string = 'select * from ' + @string1 

    EXEC(@string) 
END 
1

如果你使用EXEC爲:

EXEC @String 

它試圖運行與包含在@String變量中的名稱的過程。嘗試一下:

create procedure TestProc 
as 
print 'you called TestProc!' 
go 

declare @string varchar(20) 
set @string='TestProc' 

exec @string 

如果你使用EXEC爲:

EXEC (@Query) 

運行@Query變量中的SQL語句,嘗試一下:

DECLARE @Query varchar(50) 
set @Query='Print ''just ran it!''' 

EXEC (@Query) 
0
ALTER PROCEDURE test_sp 
    -- Add the parameters for the stored procedure here 
    (
     @DBName varchar(50), 
     @tblName varchar(50) 

    ) 

AS 
BEGIN 
-- SET NOCOUNT ON added to prevent extra result sets from 
-- interfering with SELECT statements. 
SET NOCOUNT ON 

-- Insert statements for procedure here 
declare @string as varchar(100) 
declare @string1 as varchar(50) 

set @string1 = '[' + @DBName + ']' + '.[dbo].' + '[' + @tblName + ']' 
Print @string1 
set @string = 'select * from' + @string1  
Print @string 
exec (@string) 
SET NOCOUNT OFF 
END 
+0

你有什麼改變?爲什麼這回答這個問題? – yhw42 2012-11-11 15:31:05