Tuesday, June 22, 2010

How to: Check whether SQL login exists?

Try some thing like this.

DECLARE @SqlStatement NVARCHAR(4000)
DECLARE @loginName VARCHAR (100)
SELECT @loginName = 'nagasai'
IF NOT EXISTS (SELECT loginname FROM master.dbo.syslogins WHERE NAME = @loginName)
BEGIN
SET @SqlStatement = 'CREATE LOGIN [' + @loginName + '] WITH PASSWORD=N''angel83'',DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]'
EXEC sp_executesql @SqlStatement
END
ELSE
BEGIN
PRINT 'login name ' + @loginName + ' already exists'
END

No comments:

Post a Comment