2010-10-31 34 views
-1


我想自动增加字母数字字段(例如productidproduct表中)。使用字母数字自动递增值

但我收到一个错误(见下文)。 有人可以看看这个错误或任何其他方法来完成这项任务?

我的表的详细信息:

create table tblProduct 
(
id varchar(15) 
) 

create procedure spInsertInProduct 
AS 
Begin 
    DECLARE @PId VARCHAR(15) 
    DECLARE @NId INT 
    DECLARE @COUNTER INT 
    SET @PId = 'PRD00' 
    SET @COUNTER = 0 
    --This give u max numeric id from the alphanumeric id 
    SELECT @NId = cast(substring(id, 3, len(id)) as int) FROM tblProduct group by left(id, 2) order by id 
    --here u increse the vlaue to numeric id by 1 
    SET @NId = @NId + 1 
    --GENERATE ACTUAL APHANUMERIC ID HERE 
    SET @PId = @PId + cast(@NId AS VARCHAR) 
    INSERT INTO tblProduct(id)values (@PId) 
END 

我刚开了以下错误:

Msg 8120, Level 16, State 1, Procedure spInsertInProduct, Line 10 Column 'tblProduct.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. Msg 8120, Level 16, State 1, Procedure spInsertInProduct, Line 10 Column 'tblProduct.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.**

+0

这是否意味着要求帮助? “创建表”语句是一个很长的行,因此无法读取,与错误消息相同。此外,没有提供关于使用的数据库和数据库版本的信息。 – vog 2010-10-31 15:10:03

+0

我的第一个问题是无法格式化问题的可读格式。数据库版本是SQL Server 2005 – sunit 2010-10-31 15:12:00

+0

我试图重新格式化问题并将您的数据库版本添加为标记。 – 2010-10-31 15:13:11

回答

0

你行

SELECT @NId = cast(substring(id, 3, len(id)) as int) 
    FROM tblProduct 
    group by left(id, 2) 
    order by id 

是不是做你希望它是什么。它失败了,因为你不能直接在选择中包含id,因为你正在按左(id,2)分组,而不是id本身。分组时,除非它是分组的一部分,否则不能将某些东西放入select语句中,除非它是分组依据的一部分或集合(例如SUM和MAX)。

(编辑:校正,左和子字符串不是0基于 - 让珠三角标签和这样的,我们需要串4,左3)

这样做的正确的方法是:

SELECT @NId = cast(substring(MAX(id), 4, len(MAX(id))) as int) 
    FROM tblProduct 
    group by left(id, 3) 
    order by left(id, 3) 
+0

Hi先生Brisbe,你可以用正确的方式在行下面重新格式化,因为我没有得到你所说的... – sunit 2010-10-31 15:17:54

+0

SELECT @ NId = cast(substring(id,3,len(id))as int)FROM tblProduct group by left(id,2)order by ID – sunit 2010-10-31 15:18:21

+0

group by语句中的引用不需要位于查询中的select语句中 – JeffO 2010-10-31 15:19:36

0
SELECT @NId = max(
        cast(substring(id, 4, len(id)) as int) 
       ) 
FROM tblProduct; 

这里假设你的字符串函数返回的数字部分你的ID。因为在其他例子中你的编号是以PRD开头的,所以我做了修改。

备注:没有理由让您的产品ID以数据库中的PRD开头。如果这是一个标识字段,您可以将其设置为1递增,并且在任何显示中只有'PRD'+ Cast(标识为varchar25))作为ProductID。也许这并不是所有ID的简单都不是以相同的三个字母开头。

+0

嗨先生杰夫,现在我是获取此会话错误:消息245,级别16,状态1,过程spInsertInProduct,行12 将varchar值“D00”转换为数据类型int时转换失败。 – sunit 2010-10-31 15:50:37

+0

请给出一个ID的例子,我们可以帮助你的子字符串。我猜你在某些情况下不应该从3个角色开始。 – JeffO 2010-10-31 17:38:00

0

我已经在SQL Server 2000和查询分析器中测试过你的存储过程,它工作得很好。只是我已经从中删除了创建表代码。

+0

创建proc后,你运行?因为它给出空值 – sunit 2010-10-31 15:45:23

+0

我的意思是你得到exptected结果? – sunit 2010-10-31 15:45:51

+0

@Sunit,不,我没有运行它。但只测试它。 – mahesh 2010-10-31 16:17:14