如何在表sql server中检查列数据

时间:2014-05-24 09:53:17

标签: sql sql-server stored-procedures

我需要检查产品是否在表中

如果不在表中我需要为产品分配productId并插入它,所以我尝试下面的代码....它运行成功不插入值...

我的代码

create proc spr_tbl_ProductNameId_insert

@productName VARCHAR(30)

as

DECLARE @key VARCHAR(5), @i int,@name varchar(30)


SET @i = 1
SET @name = (select [Product Name]  from tbl_ProductNameId where [Product Name] =@productName)

WHILE @i > 0

BEGIN

SET @key = (SELECT ABS(Checksum(NewID()) % 467) + 1000)
SET @i = (SELECT count(*) FROM tbl_ProductNameId WHERE [Product Id] = @key)

if(@name !=@productName)
insert into tbl_ProductNameId ([Product Name],[Product Id]) values (@productName,@key) 

end

我犯了错误...谢谢

1 个答案:

答案 0 :(得分:0)

我读了你的代码,看来你的未定义循环,因为你设置了While @i > 0

并将i值设置为唯一随机数。所以永远不要结束循环。

我做了一些评论改变。请检查

create proc spr_tbl_ProductNameId_insert

@productName VARCHAR(30)

as
BEGIN  --start always with begin end keyword
    DECLARE @key VARCHAR(5), @i int,@name varchar(30)

    SET @i = 1
    SET @name = (select [Product Name]  from tbl_ProductNameId where [Product Name] =@productName)

    WHILE @i > 0

    BEGIN

        SET @key = (SELECT ABS(Checksum(NewID()) % 467) + 1000)

        --always give isnull function for default value, it good to set when result is null 
        SET @i = isnull( (SELECT count(*) FROM tbl_ProductNameId WHERE [Product Id] = @key),0) 

        if(@name !=@productName)
        insert into tbl_ProductNameId ([Product Name],[Product Id]) values (@productName,@key) 

    END

END --end always with end keyword