Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 光标在学生表中自动插入卷号_Sql Server_Sql Server 2008 - Fatal编程技术网

Sql server 光标在学生表中自动插入卷号

Sql server 光标在学生表中自动插入卷号,sql-server,sql-server-2008,Sql Server,Sql Server 2008,如何从1,2,3开始按升序自动填充学生卷号列。。。在表单中单击分配按钮等 桌子 如何调用游标? 我对所有数据库操作都使用存储过程 示例代码 如果你想要一个学生ID,只要写在你的过程中 -- Where @StudendId will be parameter to your stored procedure SELECT * FROM TESTING WHERE StudId = @StudendId 下面是如何使用游标。但请注意,游标存在性能问题。所以少用它 DECLARE @Stud

如何从1,2,3开始按升序自动填充学生卷号列。。。在表单中单击分配按钮等

桌子

如何调用游标? 我对所有数据库操作都使用存储过程

示例代码


如果你想要一个学生ID,只要写在你的过程中

 -- Where @StudendId will be parameter to your stored procedure
 SELECT * FROM TESTING
 WHERE StudId = @StudendId
下面是如何使用游标。但请注意,游标存在性能问题。所以少用它

DECLARE @StudId INT
DECLARE @FName VARCHAR(50)
DECLARE @ROLL INT

-- Here you declare which all columns you need to loop in Cursor
DECLARE rollCursor CURSOR FOR 
select * from TESTING
WHERE StudId = @StudendId
ORDER BY StudId;

OPEN rollCursor

-- Loop starts from here 
FETCH NEXT FROM rollCursor
INTO @StudId,@FName,@ROLL

WHILE @@FETCH_STATUS = 0
BEGIN

     -- Select studentid one by one from the table
     SELECT * FROM TESTING
     WHERE StudId = @StudId

    -- Fetches next record and increments the loop
    FETCH NEXT FROM rollCursor
    INTO @StudId,@FName,@ROLL
END 

CLOSE rollCursor;
DEALLOCATE rollCursor;
编辑:1获取表的行号

如果您需要滚动的结果,请使用下面的查询

-- This will bring you the records with roll number in ascending order
-- If you want in descending order just change ASC to DESC
SELECT studid,Fname,ROW_NUMBER() OVER(ORDER BY roll ASC) roll 
FROM StudId
编辑:2创建标识字段

您需要将“卷号”列设置为标识字段,即具有整数值的列,该整数值在新插入时自动递增

将“卷号”列设置为“标识”字段后,请尝试以下插入

INSERT INTO TESTING(StudId,Fname)VALUES(10,'A')
INSERT INTO TESTING(StudId,Fname)VALUES(10,'A')
您不会在“插入”中选择或包括“卷号”列。它将自动递增

查看有关标识字段的详细信息
@Sarath我已经重新定义了这个问题,你不应该在第一时间使用光标。我想这一定是学校用的。告诉你的教授,基于集合的方法更好。您可以使用ROW_NUMBER在一条语句中完成此操作。当然,这看起来有点傻,因为您的studID中已经有升序数字。@SarathNo我想在数据库中按按钮的升序自动将值插入roll number列中单击表单studentid不是必需的,我猜如果您从所问的问题中得到结果,请标记为正确答案@索拉布64
INSERT INTO TESTING(StudId,Fname)VALUES(10,'A')
INSERT INTO TESTING(StudId,Fname)VALUES(10,'A')