sqlserver 存储过程问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlserver 存储过程问题相关的知识,希望对你有一定的参考价值。
create procedure [dbo].[ReportMarkShow]
(
@BusinessId bigint,
@order nvarchar(20),
@UserId nvarchar(20)
)
as
BEGIN
declare @str varchar(5000)
declare @sql varchar(5000)
if @UserId = '0'
set @str = @str + ' and 1=1 '
else
set @str = @str + ' and Send_UserId = ' + convert(nvarchar,@UserId)
if @order = 'year'
set @str = @str + ' and Post_Date between Dateadd(yy,datediff(yy,0,getdate()),0) and Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) '
else if @order = 'month'
set @str = @str + ' and Post_Date between Dateadd(mm,datediff(mm,0,getdate()),0) and Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) '
else if @order = 'week'
set @str = @str + ' and Post_Date between Dateadd(wk,datediff(wk,0,getdate()),-1) and Dateadd(wk,datediff(wk,0,getdate()),6)'
else if @order = 'day'
set @str = @str + ' and (DATEDIFF(d, fn NOW() , Post_Date) = 0)'
else
set @str = @str + ''
set @str = @str + ' order by Post_Date desc'
set @sql = 'SELECT Report_Id, Business_Id, Send_UserID, Receive_UserId, State_Msg, Subject_Msg, Content_Msg, Post_Date,Is_Open
FROM ReportMsg where State_Msg=1 and Business_Id='+convert(nvarchar,@BusinessId)
exec(@sql+@str)
END
自己写的,不报错,但返回的结果根本不对,我加上
@str = @str + ' and 1=2 ' 它也能给我返回结果,好像根本不知道有@str的存在,请高手指点,先谢谢了
错误1 @str 定义后没有初始化。
如果只是定义,不初始化,那么它就是null。
set @str = @str + ' and 1=1 ' 这句话运行后,@str的值还是null,因为null型的varchar ‘+’运算后还是null。
如果将@str初始化后,以以下的引数运行你的存储过程:
@BusinessId = '0',
@order = 'year',
@UserId = '0'
得到的sql语句(@sql+@str)是:
SELECT Report_Id, Business_Id, Send_UserID,
Receive_UserId, State_Msg, Subject_Msg,
Content_Msg, Post_Date,Is_Open
FROM ReportMsg
where State_Msg=1 and Business_Id=0
and 1=1 and
Post_Date between Dateadd(yy,datediff(yy,0,getdate()),0)
and Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0))
order by Post_Date desc
楼主看看是不是想要的结果,不知道字段类型不好说,因为:where State_Msg=1 and Business_Id=0中,如果State_Msg,Business_Id是varchar类型的,那么1 和 0 就的加单引号,楼主在拼sql语句的时候得手动拼上单引号。
不知道这样写够不够明白。本回答被提问者采纳
关于sqlserver存储过程的问题
我想将某一张表的某一列中的数据(都是字符串的)收集起来 再返回 求解怎么写存储过程
创建带游标Cursor的存储过程CREATE PROCEDURE PT @t_cursor CURSOR VARYING OUTPUT AS
SET @t_cursor=CURSOR FOR
Select tid,tname FROM Teacher OPEN @t_cursor
接下来,执行一个批处理,声明局部游标变量,执行上述过程以将游标赋值给局部变量,然后从该游标提取行。
Declare @gh char(4),@xm varchar(50), @MyCursor CURSOR
EXEC PT @MyCursor OUTPUT
WHILE (@@FETCH_STATUS =0)
BEGIN
FETCH NEXT FROM @MyCursor INTO @gh,@xm
PRINT @gh+\' \'+@xm
END
DEALLOCATE @MyCursor 参考技术A 用游标循环就行了
以上是关于sqlserver 存储过程问题的主要内容,如果未能解决你的问题,请参考以下文章