Sql server 如何使用sp_executesql确定数据库中是否存在用户?
我试图使用Sql server 如何使用sp_executesql确定数据库中是否存在用户?,sql-server,tsql,stored-procedures,Sql Server,Tsql,Stored Procedures,我试图使用sp_executesql,但似乎无法正确使用语法。以下是我正在尝试的: DECLARE @userName1 varchar(20) DECLARE @userexists bit SET @userName1 = 'testUser' EXEC sp_executesql N'select @userexists = name FROM sys.database_principals WHERE name = ' + @userName1, N'@userexists bit
sp_executesql
,但似乎无法正确使用语法。以下是我正在尝试的:
DECLARE @userName1 varchar(20)
DECLARE @userexists bit
SET @userName1 = 'testUser'
EXEC sp_executesql N'select @userexists = name FROM sys.database_principals WHERE name = ' + @userName1, N'@userexists bit output', @userexists output
PRINT @userexists
这怎么行?谢谢你的帮助。试试这个
DECLARE @userName1 varchar(20)
DECLARE @userexists bit
SET @userName1 = 'testUser'
EXEC sp_executesql N'select @userexists = name FROM sys.database_principals WHERE name = ' + @userName1, N'@userexists bit output', @userexists output
PRINT @userexists
EXEC sp_executesql
N'select @userexists=1 FROM sys.database_principals WHERE name = @userName1',
N'@userName1 varchar(20), @userexists bit output',
@userName1,
@userexists output
在这种情况下,您将得到1
或空结果
DECLARE @userName1 varchar(20)
DECLARE @userexists bit
SET @userName1 = 'testUser'
EXEC sp_executesql N'select @userexists = name FROM sys.database_principals WHERE name = ' + @userName1, N'@userexists bit output', @userexists output
PRINT @userexists
因此,您可以尝试以下方法:
DECLARE @userName1 varchar(20)
DECLARE @userexists bit
SET @userName1 = 'testUser'
EXEC sp_executesql N'select @userexists = name FROM sys.database_principals WHERE name = ' + @userName1, N'@userexists bit output', @userexists output
PRINT @userexists
EXEC sp_executesql
N'SET @userexists = CASE WHEN EXISTS(SELECT 1
FROM sys.database_principals
WHERE name = @userName1)
THEN 1 ELSE 0
END',
N'@userName1 varchar(20), @userexists bit output',
@userName1,
@userexists output
您想在这个场景中使用它吗?非常好的thx,使用第二个解决方案来解决我的问题,我尝试添加“use DB\@name;”在集合\@userexists'之前,但它不解析\@name部分\@name是一个varchar(50),用于循环许多数据库。它返回的“DB\@name”不存在。你知道我能尝试什么吗。。。再次发送给你。我在@user1161137 Hello中发布了后续问题。很高兴能帮上忙。对不起,我刚看了评论,似乎太晚了