Two table:
StoreInfo:
UserId uniqueidentifier
StoreNo nvarchar
UserName nvarchar
Password nvarchar
UserInfo:
UserId uniqueidentifier
UserName nvarchar
Password nvarchar
the UserId on StoreInfo is currently null. How do i update StoreInfo's UserId with UserInfo's UserId based on StoreInfo's UserName and Password is match to the UserName and Password from UserInfo.
the following is the query that i wrote which update the entire UserId in StoreInfo with the first UserId from UserInfo so i know it's wrong.
declare #UserName nvarchar(255)
declare #Password nvarchar(25)
declare #UserId uniqueidentifier
select #UserName = UserName, #Password = Password, #UserId = UserId
from UserInfo
select UserId, Password
from FranchiseInfo
where UserID = #UserName and Password = #Password
update FranchiseInfo
set UserI = #UserId
The update would look like this
update storeinfo
set userid = u.userid
from userinfo u
inner join storeinfo s on (s.username = u.username and s.password = u.password)
where userid is null
The most efficient way is the UPDATE ... FROM syntax, e.g.
UPDATE StoreInfo
SET
UserId = ui.UserId
FROM
StoreInfo si
INNER JOIN UserInfo ui ON ui.UserName = si.UserName AND ui.Password = si.Password;
UPDATE StoreInfo
set UserId = ui.UserId
from StoreInfo si
inner join UserInfo ui
on ui.UserName = si.UserName
and ui.Password = si.Password
where si.UserId is null
This will update all rows in the table where UserId is not set. Build out the where clause if you only want to update selected rows. (I haven't tested this, so watch for typos!)
Related
Trying to crypt mine function and get it back,need your help tell me please what i am doing wrong ?
SELECT user_id
FROM users
WHERE email = 'Natali#gmail.com' AND u_password = crypt(u_password, '#kjvfhjh88976');
// Null result
INSERT INTO users (user_id, nick_name, email, u_password)
VALUES
(87678655, 'Natali1990#', 'Natali#gmail.com', crypt('#kjvfhjh88976', gen_salt('bf')));
SELECT user_id FROM users WHERE email = 'Natali#gmail.com'; // Working
You are using the pgcrypto package incorrectly, and given that it is confusing, this is not a surprise. Your current insert seems fine:
INSERT INTO users (user_id, nick_name, email, u_password)
VALUES
(87678655, 'Natali1990#', 'Natali#gmail.com',
CRYPT('#kjvfhjh88976', GEN_SALT('bf')));
Then, to authenticate a user, use a SELECT looking something like the following:
SELECT u_password = CRYPT('#kjvfhjh88976', u_password)
FROM users
WHERE email = 'Natali#gmail.com';
This would return true if the user entered the correct password. You may read more about this in the Postgres documentation;
My [User] table which is having column [Email] encrypted using Always-Encrypt.
I need to limit [Email]'s length from max to MaxLength(250), I do this by add MaxLength(250) on the email property.
public class User
{
[Key, Required]
public Guid Id { get; set; }
[Required, **MaxLength(250)**]
public string Email { get; set; }
...
}
but when I run migration scripts, I got following exception:
Operand type clash: nvarchar(max) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK1', column_encryption_key_database_name = 'Identity') is incompatible with nvarchar
and the migration scripts is:
DECLARE #var0 nvarchar(128)
SELECT #var0 = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'dbo.User')
AND col_name(parent_object_id, parent_column_id) = 'Email';
IF #var0 IS NOT NULL
EXECUTE('ALTER TABLE [dbo].[User] DROP CONSTRAINT [' + #var0 + ']')
ALTER TABLE [dbo].[User] ALTER COLUMN [Email] [nvarchar](250) NOT NULL
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201804250659054_12345678', N'Concordya.PWC.Verify.DataAccess.Migrations.Configuration', 0x1F8... , N'6.2.0-61023')
I manually run the scripts in DB, same error.
Does that mean once the column is encrypted, the only way to change property is decrypt, modify, then encrypt?
Thanks,
Cheng
I came across a similar error when trying to increase the size of an Always Encrypted NVARCHAR column. The problem was that the ALTER COLUMN statement still needs to include the encryption parameters. So for example you could alter this -
ALTER TABLE [dbo].[User] ALTER COLUMN [Email] [nvarchar](250) NOT NULL
To this (or whatever you originally set the Always Encrypted parameters to) -
ALTER TABLE [dbo].[User] ALTER COLUMN [Email] [nvarchar](250) NOT NULL
ENCRYPTED WITH (
ENCRYPTION_TYPE = DETERMINISTIC
, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256'
, COLUMN_ENCRYPTION_KEY = [**YOUR KEY**]
) NULL
I have two tables for administrators and roles, connected vía the third table assignments (many-to-many relationship) with the fields role_id, administrator_id and some extra fields created_at and updated_at, which I would like to populate automatically:
assignments = db.Table('assignments',
db.Column('role_id', db.Integer, db.ForeignKey('roles.id')),
db.Column('administrator_id', db.Integer,
db.ForeignKey('administrators.id')),
db.Column('created_at', db.DateTime, server_default=db.func.now()),
db.Column('updated_at', db.DateTime, server_default=db.func.now(),
onupdate=db.func.now()),
db.ForeignKeyConstraint(['administrator_id'], ['administrators.id']),
db.ForeignKeyConstraint(['role_id'], ['roles.id'])
)
class Administrator(db.Model, UserMixin):
__tablename__ = 'administrators'
id = Column(Integer, primary_key=True, server_default=text("nextval('administrators_id_seq'::regclass)"))
email = Column(String(255), nullable=False, unique=True, server_default=text("''::character varying"))
name = Column(String(255))
surname = Column(String(255))
roles = db.relationship('Role', secondary=assignments,
backref=db.backref('users', lazy='dynamic'))
class Role(db.Model):
__tablename__ = 'roles'
id = Column(Integer, primary_key=True, server_default=text("nextval('roles_id_seq'::regclass)"))
name = Column(String(255))
But when I assign a role to an administrator
admin.roles = [role1]
db.session.add(admin)
db.session.commit()
it breaks with the following error:
IntegrityError: (psycopg2.IntegrityError) null value in column "created_at" violates not-null constraint
DETAIL: Failing row contains (1265, 19, 3, null, null).
[SQL: 'INSERT INTO assignments (role_id, administrator_id) VALUES (%(role_id)s, %(administrator_id)s)'] [parameters: {'administrator_id': 19, 'role_id': 3}]
Is there any way to set a default value for created_at and updated_at fields in assignments table?
It worked using default and onupdate parameters instead of server_default and server_onupdate:
db.Column('created_at', db.DateTime, default=db.func.now()),
db.Column('updated_at', db.DateTime, default=db.func.now(),
onupdate=db.func.now()),
Try this
db.Column('created_at', db.DateTime, server_default=text("now()"))
I am trying to update one field in db which is of type Boolean. This is the table structure
usr_id int False
usr_fname nvarchar(50)
usr_lname nvarchar(50)
usr_username nvarchar(50)
usr_password nvarchar(MAX)
usr_email nvarchar(50)
usr_pwdresetstatus bit
This is something I am trying
public int ForGotPassword(string username, string emailid)
{
var result = db.tm_usr_usermaster.Where(m => m.usr_username == username && m.usr_email==emailid).Select(m => m.usr_isactive).SingleOrDefault();
bool isactive = Convert.ToBoolean(result);
if(isactive==false)
{
//Update query
}
else
{
}
I am receiving parameters username and email id if both matches pwdresetstatus should be updated as true. I can write sql equivalent here
Update tablename set pwdresetstatus=true where usr_username==username && usr_email==emailed. I have difficult times to go ahead
I tried this
tm_usr_usermaster users = db.tm_usr_usermaster.FirstOrDefault(x => x.usr_email==emailid && x.usr_username==username);
users.usr_pwdresetstatus = true;
db.SaveChanges();
and working fine. Thank you stephen
I have an Account table:
table Account
(
UserId int identity(1, 1),
UserName nvarchar(20) not null unique,
Password nvarchar(20) not null
)
By using LINQ. Whether I can check exist UserName for an account then. And it's true then get UserId for that account
(I'm use ASP MVC 4 with Entity Framework)
When using Linq to query from DB, I prefer to use query expression, that is closer to SQL notation than Lambda notation.
Given that you have the username:
try {
int userId = (from x in context.Account
where x.UserName == username
select x.UserId).SingleOrDefault());
if (userId > 0){
// user exists
}
else {
// user does not exist
}
}
catch(InvalidOperationException ex){
// has more than one element
}
var user = Context.Accounts.SinlgeOrDefault(user => user.UserName=="yourValue");
if(user!=null)
{
// you can safely access the user properties here
}