まず、良い仕事をしようと手を差し伸べます非動的SQLの方法を見つける。
以下の「トリック」は、ルックアップテーブルのカウントを考慮することです。
IMHO、動的SQLの回答を含むすべての "試してください"を無視してください。問題が動的SQLなしで解決できる場合は、IMHOにする必要があります。ここでいくつかの問題について読むことができます:http://sqlmag.com/database-performance-tuning/don-t-fear-dynamic-sqlそれを使用しても、それを使用するためのまともな方法と馬鹿な方法があります。
IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
begin
drop table #TableOne
end
CREATE TABLE #TableOne
(
SurrogateKeyIDENTITY int not null IDENTITY (1,1) ,
MyLabel varchar(16)
)
Insert into #TableOne (MyLabel) select 'Clean Label' UNION ALL select 'Clean Label' UNION ALL select 'Key Interview' UNION ALL select 'Key Interview' UNION ALL select 'Special Report' UNION ALL select 'Special Report' UNION ALL select 'NotAMatch' UNION ALL select 'NotAMatch'
Declare @LookupMatchTable Table (KeyVal varchar(50))
if(1=1) /* use your bool flags here */
begin
Insert Into @LookupMatchTable (KeyVal) Select 'Clean Label'
end
if(1=1) /* use your bool flags here */
begin
Insert Into @LookupMatchTable (KeyVal) Select 'Key Interview'
end
if(1=1) /* use your bool flags here */
begin
Insert Into @LookupMatchTable (KeyVal) Select 'Special Report'
end
declare @LookupMatchTableCount int
select @LookupMatchTableCount = (select count(*) from @LookupMatchTable)
SELECT * FROM #TableOne t1 WHERE (@LookupMatchTableCount = 0 OR EXISTS (Select KeyVal from @LookupMatchTable lmt where lmt.KeyVal = t1.MyLabel))
/* now show if there are no entries in the look up table, everything comes back */
delete from @LookupMatchTable
select @LookupMatchTableCount = (select count(*) from @LookupMatchTable)
SELECT * FROM #TableOne t1 WHERE (@LookupMatchTableCount = 0 OR EXISTS (Select KeyVal from @LookupMatchTable lmt where lmt.KeyVal = t1.MyLabel))
/* now show that if there is something in the lookup table that doesn't match the "real" table......no rows returned */
delete from @LookupMatchTable
Insert Into @LookupMatchTable (KeyVal) Select 'No Match Whatsoever'
select @LookupMatchTableCount = (select count(*) from @LookupMatchTable)
SELECT * FROM #TableOne t1 WHERE (@LookupMatchTableCount = 0 OR EXISTS (Select KeyVal from @LookupMatchTable lmt where lmt.KeyVal = t1.MyLabel))
IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
begin
drop table #TableOne
end
あなたの@whereには、 ';'が含まれています。 SQLに追加する前にその最初のコンマを削除するロジックを記述してください – techspider
文字列の後ろに移動し、値の一部であってはなりません。 'を3回使用して、値を文字列で囲みます。例は、+ N '、Clean Label'のどこにあってはならない。 + '' 'クリーンラベル' '+'、 ''である必要があります。また、他の人が何かを削除すると言っている、かわいそうや終わりのどこから文字列。検索するにはCHARINDEXを使用し、文字列を切り取るにはSUBSTRINGを使用します。 –