2012-04-02 51 views
2

如何動態地寫下面的查詢?如何動態地在SQL Server 2008中編寫查詢?

empid  designation  interestes 
1   developer,tester  cricket,chess 
1   developer    chess 
1   techlead    cricket 

條件:

IF empid = 1 
AND (designation LIKE '%developer%' OR designationLIKE '%techlead%') 
OR (interests LIKE '%cricket%'). 

如何動態地寫上面的查詢,如果指定要發送超過2個,也同樣對interstes。

請告訴我...

編輯存儲過程的代碼:

ALTER PROCEDURE [dbo].[usp_GetDevices] 
    @id INT, 
    @designation NVARCHAR (MAX) 
AS 
BEGIN 
    declare @idsplat varchar(MAX) 
    set @idsplat = @UserIds 
     create table #u1 (id1 varchar(MAX)) 
     set @idsplat = 'insert #u1 select ' + replace(@idsplat, ',', ' union select ') 
     exec(@idsplat) 
     Select 
     id FROM dbo.DevicesList WHERE [email protected] AND designation IN (select id1 from #u1) 
     END 
+0

請讓你的問題更清楚。你想寫動態SQL嗎? – Terry 2012-04-02 04:30:33

+0

我把所有的指定像UI中的複選框。用戶選擇no.of開發人員,測試人員,projectlead,techlead動態來查詢。如何查詢從數據庫獲取相關記錄... – user1237131 2012-04-02 04:32:50

+0

http://stackoverflow.com/questions/9970877/how-to-dynamic-write-the-query-in-sql-server-2008 – user2490832 2014-02-27 08:31:41

回答

0

那麼當你提交表單時,創建指定的字符串(應該真正的外鍵的列表,如果你有一對多關係)並將其傳遞給SQL。然後解析成使用許多open-source SQL user functions一個表:

-- @designations = 'developer,tester,techlead' 

select text_val 
from dbo.fn_ParseText2Table(@designations,',') 

/* results: 

text_val 
-------- 
developer 
tester 
techlead 

*/ 

一旦你有,你可以做任何標準表中的值加入或查詢操作。

+0

您好@Terry謝謝。但我得到完全匹配records.ie如果我發送id = 1和指定=「'開發人員'「只獲得第二條記錄。但第一條記錄也是開發者指定它是錯誤的。通過使用像獲取所有開發人員記錄,但我不能發送多個參數,如id = 1,指定=''%developer%','%如果子查詢遵循=,!=,<, <= , >,> =或者當子查詢用作表達式時,則不允許這樣做。「%test'%','%techlead%''」錯誤爲「子查詢返回多個值」。請檢查我的SP ... – user1237131 2012-04-02 05:27:10

相關問題