我想創建一個tsql存儲過程,它將根據某些參數輸出行。最終目標是將行移動到另一個表,這就是爲什麼我要計數 - 我想跟蹤我正在移動的行數。有兩個表格 - Notes
和ExtraNotes
。 ExtraNotes
保存來自第一個表的溢出信息。使用IF語句後無法從數據庫輸出正確的行
我正在使用if
語句根據名爲NoteType
的參數選擇正確的行,但我不知道如何在if
內輸出正確的select語句。我知道每個if
內的選擇是錯誤的說法
select *
from dbo.Notes
left join dbo.ExtraNotes on Notes.NoteID = dbo.ExtraNotes.NoteID
where NoteDate <= @Date
任何人都可以提供輸出怎麼可以正確的行和可能重組這個更好一些指針?
完整的代碼在這裏。
alter proc selectrows
--external variables
@Date datetime,
@NoteType varchar(2)
as
--internal variables
--Count variables, before any changes
declare @count_rowsBefore int
declare @count_Extra_rowsBefore int
--Count variables of selected rows to be moved
declare @count_SelectedRows int
declare @count_Extra_SelectedRows int
select @count_rowsBefore = count(*)
from dbo.Notes
select @count_Extra_SelectedRows = count(*)
from dbo.ExtraNotes
if(@NoteType= 'B')
begin
select @count_SelectedRows = count(dbo.Notes.NoteID), @count_Extra_SelectedRows = count(dbo.ExtraNotes.NoteID)
from dbo.Notes
left join dbo.ExtraNotes on
Notes.NoteID = dbo.ExtraNotes.NoteID
where NoteDate <= @Date
select *
from dbo.Notes
left join dbo.ExtraNotes on
Notes.NoteID = dbo.ExtraNotes.NoteID
where NoteDate <= @Date
end
else if(@NoteType = 'S')
begin
select @count_SelectedRows = count(dbo.Notes.NoteID),
@count_Extra_SelectedRows = count(dbo.ExtraNotes.NoteID)
from dbo.Notes
left join dbo.ExtraNotes on
Notes.NoteID = dbo.ExtraNotes.NoteID
where NoteDate <= @Date
and NoteType = 'S'
select *
from dbo.Notes
left join dbo.ExtraNotes on
Notes.NoteID = dbo.ExtraNotes.NoteID
where NoteDate <= @Date
end
else if (@NoteType = 'M')
begin
select @count_SelectedRows = count(dbo.Notes.NoteID),
@count_Extra_SelectedRows = count(dbo.ExtraNotes.NoteID)
from dbo.Notes
left join dbo.ExtraNotes on
Notes.NoteID = dbo.ExtraNotes.NoteID
where NoteDate <= @Date
and NoteType = 'M'
select *
from dbo.Notes
left join dbo.ExtraNotes on
Notes.NoteID = dbo.ExtraNotes.NoteID
where NoteDate <= @Date
end
else
begin
raiserror('Please enter a valid Note Read Type= M, S or B',16,1)
end
Print 'Total Number of rows: ' + cast(@count_rowsBefore as varchar(10))
Print 'Total Number of "Extra" rows: ' + cast(@count_Extra_RowsBefore as varchar(10))
Print '-----------------------------------------------'
Print 'Total Number of rows to Move: ' + cast(@count_SelectedRows as varchar(10))
Print 'Total Number of "Extra" Rows to Move: ' + cast(@count_Extra_SelectedRows
as varchar(10))
我覺得使用返回表的函數會比這裏的存儲過程更好地爲您服務。 Checkout表值函數:http://msdn.microsoft.com/en-us/library/ms191165。aspx – Zugwalt 2012-04-19 18:52:13
目前還不清楚你在這裏做什麼,你現在有什麼問題以及你要求我們做什麼? – RBarryYoung 2012-04-19 18:58:05
當我用M的參數運行這個例如我得到的行與Notetype M和S是錯誤的。 – karmaplus 2012-04-19 19:00:22