我正在使用动态sql.here是我的sp.I想检查null.Hhich approch是好的。
ALTER procedure [dbo].[proc_insertsample]
@pname varchar(10),
@rdatetime varchar(10),
@fromcountry int,
@fromoperatorid int
as
begin
declare @query nvarchar(4000)
declare @fromcountry2 varchar(10)
declare @fromoperatorid2 varchar(10)
set @fromcountry2 = CAST(@fromcountry as varchar(10))
set @fromcountry2 = isnull(@fromcountry2,0)
set @fromoperatorid2 = cast (@fromoperatorid as varchar(10))
set @fromoperatorid2 = isnull(@fromoperatorid2,0)
set @query = 'insert into sample1 (pname,rdatetime,fromcountry,fromoperatorid) values ('''+@pname+''','''+@rdatetime+''','''+@fromcountry2+''','''+@fromoperatorid2+''')'
print @query
end
或
ALTER procedure [dbo].[proc_insertsample2]
@pname varchar(10),
@rdatetime varchar(10),
@fromcountry varchar(10),
@fromoperatorid varchar(10)
as
begin
declare @query nvarchar(4000)
set @fromcountry = ISNULL(@fromcountry,'')
set @fromoperatorid = ISNULL(@fromoperatorid,0)
set @query = 'insert into sample1 (pname,rdatetime,fromcountry,fromoperatorid) values ('''+@pname+''','''+@rdatetime+''','''+@fromcountry+''','''+@fromoperatorid+''')'
print @query
end
。我正在修改sp.Previously para是int,改为varchar。可以设置一个值来输入para.I不想再创建变量到isnull结果。我直接在动态字符串中放入isnull我打印并执行。但没用。
答案 0 :(得分:0)
我不完全确定你在问什么,但是如果你可以通过给出你想要的默认值默认值的参数来定义存储过程中参数的默认值:
@fromcountry VARCHAR(10) = ''
所以你的第二个sp看起来像这样:
ALTER procedure [dbo].[proc_insertsample](@pname VARCHAR(10) = '',
@rdatetime VARCHAR(10) = '',
@fromcountry VARCHAR(10) = '',
@fromoperatorid VARCHAR(10) = ''
AS
BEGIN
DECLARE @query AS NVARCHAR(4000)
SET @query = 'INSERT INTO sample1 (pname,rdatetime,fromcountry,fromoperatorid) VALUES ('''+@pname+''','''+@rdatetime+''','''+@fromcountry+''','''+@fromoperatorid+''')'
PRINT @query
END
如果您在没有参数的情况下致电proc_insertsample1
,那么您的@query
变量将如下所示:
INSERT INTO sample1 (pname,rdatetime,fromcountry,fromoperatorid)
VALUES ('', '', '', '', '')
或者,您可以将ISNULL检查权限放在动态SQL中:
SET @query = 'INSERT INTO sample1 (pname,rdatetime,fromcountry,fromoperatorid) VALUES (''' + @pname + ''',''' + @rdatetime + ''',''' + ISNULL(@fromcountry,'') + ''',''' + ISNULL(@fromoperatorid,'') + ''')'
在这种情况下,您的@query
变量将(假设您的pname为'John',rdatetime为'10 / 01/2007'),如下所示:
INSERT INTO sample1 (pname,rdatetime,fromcountry,fromoperatorid)
VALUES ('John','10/01/2007','','')
这有帮助吗?
答案 1 :(得分:0)
处理数据完整性问题的最佳方法是对要插入的表中的字段设置DEFAULT和NOT NULL约束。这样您就可以将验证逻辑从存储过程移动到表本身。
它还将帮助您在未来构建强大的数据库设计。
给你一个真实的例子,你所做的就是每次将硬币插入一个适当大小的硬币和浪费时间的停车计时器时检查你的口袋,而不是仅仅在停车场里制作硬币槽小到足以只接受某些硬币大小并拒绝未知硬币。