我想根据列值生成序列号。我希望有这种输出。我将在c#.net winform中使用它作为GridView输出
TABLE1
ID Name NoStub
1 arte 3
2 gonzake 2
TABLE2
ID Name StubNumberStart StubNumberEnd
1 arte 0001 0003
2 gonzake 0004 0005
答案 0 :(得分:0)
尝试此查询..它将从表2到表1给出结果
DECLARE @T1 AS TABLE (ID INT, NAME VARCHAR(50), STUBNUMBER VARCHAR(10))
INSERT INTO @T1 VALUES ( 1, 'ARTE', '001')
INSERT INTO @T1 VALUES ( 1, 'ARTE', '002')
INSERT INTO @T1 VALUES ( 1, 'ARTE', '003')
INSERT INTO @T1 VALUES ( 1, 'GONZAKE', '004')
INSERT INTO @T1 VALUES ( 1, 'GONZAKE', '005')
SELECT * FROM @T1
SELECT DISTINCT ID ,NAME, COUNT(*) AS NOSTUB FROM @T1
GROUP BY ID, NAME
如果您的要求与表1至表2不同,请告知我们......您将获得新的查询......
答案 1 :(得分:0)
ALTER PROCEDURE ExpandIt
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Id int;
DECLARE @name varchar(50);
DECLARE @noStub int;
DECLARE @stubNumber char(8);
DECLARE @count as int = 0;
DECLARE @continuedID as int = 0;
DECLARE t1 CURSOR FAST_FORWARD FOR
SELECT ID, Name,NoStub from Table1
OPEN t1
FETCH NEXT FROM t1 INTO @Id, @name, @noStub
WHILE @@FETCH_STATUS = 0
BEGIN
WHILE (@count < @noStub)
BEGIN
SET @count = @count + 1;
SET @stubNumber = ('0000' + CONVERT (CHAR, @continuedID + @count));
SET @stubNumber = SUBSTRING (@stubNumber,LEN(@stubNumber)-4+1, 4);
INSERT INTO Table2 (ID, Name, StubNumber)
VALUES (@Id, @name,@stubNumber);
END
SET @continuedID = @count;
SET @count = 0;
FETCH NEXT FROM t1 INTO @Id, @name, @noStub
END
CLOSE t1 ;
DEALLOCATE t1
END