sqlserver stored procedure

  1. Combined use of cursors and stored procedures:

 
 
CREATE PROCEDURE test_p
AS
  BEGIN
    DECLARE @a VARCHAR(1000);--When defining variables, set the length as large as possible, otherwise it will result in incomplete data storage
    DECLARE @change VARCHAR (100);
    DECLARE c CURSOR FOR
      SELECT DISTINCT a FROM XXX WHERE aa = ''--Define the cursor
    OPEN c -- open the cursor
    FETCH NEXT FROM c INTO @a--read cursor
    WHILE @@fetch_status = 0--read successful
      BEGIN
        SET @newid = newid()--When multiple pieces of data are updated, newid will be regenerated. If you want to update multiple pieces of data to the same value, you can define variables to store them
        PRINT @a
        UPDATE XXX SET aa = @newid WHERE a= @a;
        FETCH NEXT FROM c INTO @a--read cursor (important, otherwise it will cause an infinite loop, repeating the first row)
      END
    CLOSE c--Close the cursor
    DEALLOCATE c--delete the cursor
  END
 
 

2. Call the stored procedure: EXEC test_p

3. Drop the stored procedure: DROP PROCEDURE  test_p

4. View the location and content of all stored procedures or views:

select a.name,a.[type],b.[definition] from sys.all_objects a,sys.sql_modules b
where a.is_ms_shipped=0 and a.object_id = b.object_id and a.[type] in ('P','V','AF')
order by a.[name] as
5. When concatenating strings, it appears: Failed to convert nvarchar value to data type int.
Solution 1: Convert a variable of non-string type to a string type, SET @a= @a + convert(nvarchar(10),100) ;
Solution 2: Define the parameter as a string type at the beginning of the stored procedure definition

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325491346&siteId=291194637