问题
I am trying to add a claim to an existing User, but the query I wrote (and am running in SSQL Management Studio) below doesn't work. Is the query wrong, or is this just not possible?
update [test_MIM].[dbo].[AspNetUserClaims]
set ClaimType = 'EmployeeNumber',
ClaimValue = '1',
--Id = f.Id,
UserId = f.UserName
from (select Id,UserName FROM [test_MIM].[dbo].[AspNetUsers] where UserName='abc@gmail.com') as f
I commented out the Id column because when I included it the query failed (possibly because Id was auto-generated)
回答1:
Instead use a update-join
construct like
update a
set ClaimType = 'EmployeeNumber',
ClaimValue = '1',
UserId = f.UserName
from [test_MIM].[dbo].[AspNetUserClaims] a
join [test_MIM].[dbo].[AspNetUsers] f
on a.id = f.id
where f.UserName = 'abc@gmail.com'
回答2:
What you can do is use join
in your update statement,what join
does is it joins two or multiple tables together in one statement :
UPDATE NameHere SET ClaimType = 'EmployeeNumber',ClaimValue = '1', UserId f.UserName FROM [test_MIM].[dbo].[AspNetUserClaims] NameHere JOIN [test_MIM].[dbo].[AspNetUsers] f on NameHere.id = f.id where f.UserName = 'abc@gmail.com'
But it is not ideal,rather pass parameters for each column , then not only that you can save your app from SQL-Injection but also will be able to set column's data-type which might get rid of other problems. A sample :
UPDATE NameHere SET ClaimType = @ClaimType,ClaimValue = @claimValue, UserId = @Uname FROM [test_MIM].[dbo].[AspNetUserClaims] NameHere JOIN [test_MIM].[dbo].[AspNetUsers] f on NameHere.id = @NewID where f.UserName = @NewUserName
If you are using SqlCommand
,then you can use the parameters as follows :
cmd.Parameters.Add("@ClaimType", SqlDbType.VarChar).Value = "claimingTyoeString" ////Assuming 'cmd' is the SqlCommand
.......
cmd.ExecuteNonQuery();
来源:https://stackoverflow.com/questions/49564340/update-asp-net-claims-via-sql-statement