我正在尝试创建一个 tsql 存储过程,它将根据一些参数输出行。最终目标是将行移动到另一个表,这就是为什么我有计数 - 我想跟踪我移动了多少行。有两个表 -Notes
和ExtraNotes
。ExtraNotes
保存来自第一个表的溢出信息。
我正在使用该if
语句根据调用的参数选择正确的行,NoteType
但我不知道如何在if
. 我知道每个中的选择语句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))