Reputation: 23
I have two tables
student:
(student_id, student_name)
and
license:
(license_id, student_id)
And I have a list of student ids (for example "3,4,5")
I want to update 3(list size) rows in table license and change their student_id field from null to 3,4,5 respectively.
How do I do that? Running a loop of updates is not a suitable solution for me. Thanks in advance.
Upvotes: 1
Views: 249
Reputation: 10175
I have an MS SQL version of an id parser. You can use this to generate a table with a single column that contains your ids it takes a parameter of type varchar(max). you can use it on a select statement like
SELECT * FROM TABLENAME
WHERE COLUMNAME IN (SELECT value FROM parseIDs ('1,2,3'))
Here is the function:
CREATE FUNCTION parseIDs
(
@IDList VARCHAR(MAX)
)
RETURNS @IDs TABLE (value VARCHAR(80))
AS
BEGIN
IF @IDList is null
RETURN
DECLARE @Len INT,
@Pos INT,
@Cur INT
SELECT @Pos = 0,
@Len = 0,
@Cur = 1,
@IDList = CASE
WHEN SUBSTRING(@IDList, LEN(@IDList), 1) = ',' THEN @IDList
ELSE @IDList + ','
END
SELECT @Pos = CHARINDEX( ',', @IDList, @Cur)
WHILE (@Pos <> 0)
BEGIN
INSERT @IDs VALUES (LTRIM(SUBSTRING( @IDList, @Cur, (@Pos - @Cur))))
SELECT @Cur = @Pos + 1
SELECT @Pos = CHARINDEX( ',', @IDList, @Cur)
END
return
END
Upvotes: 1