sqlserver存储过程中sql语句连接及datetime字段的处理
语句连接可以首先 declare @sql varchar(800) 声明一个新变量,然后中间用set重新给他赋值。
datetime类型字段可以用 CAST((@fxsj_bg as nvarchar(10)) 把日期变量传换为字符串然后再进行语句连接
示例:
ALTER PROCEDURE dbo.getFAULT
(
@id int,
@hbr nvarchar(10),
@lb nvarchar(10),
@fxsj_bg datetime,
@fxsj_ed datetime,
@bds nvarchar(15),
@sfycl nvarchar(2)
)
AS
/* SET NOCOUNT ON */
declare @sql varchar(800)
if @id!=0
BEGIN
set @sql = 'select * from FAULT where id = @id'
end
else
set @sql = 'select * from FAULT WHERE id>0 '
if @hbr!='全部'
BEGIN
set @sql = @sql+' AND hbr=''' +@hbr+ ''''
END
if @lb!='全部'
BEGIN
set @sql = @sql+' AND LB=''' +@lb+ ''''
END
if @bds!='全部'
BEGIN
set @sql = @sql+' AND bds=''' +@bds+ ''''
END
if @sfycl!='全部'
BEGIN
set @sql = @sql+' AND sfycl=''' +@sfycl+ ''''
END
set @sql = @sql+' AND fxsj Between ''' + CAST(@fxsj_bg as nvarchar(10))+ ''' and '''+ CAST(@fxsj_ed as nvarchar(10))+ ''''
print(@sql)
exec(@sql)
RETURN