简体   繁体   中英

How do I efficiently escape special characters in T-SQL?

IF NOT EXISTS (select * from sys.server_principals where lower([name]) =lower('DOMAIN\t''acct'))
BEGIN
  CREATE LOGIN [DOMAIN\t'acct] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
END

The above code works correctly. My question is, is there a way to efficiently use placeholders so that I can pass in the same account and use in both the places when I have special characters?

IF NOT EXISTS (select * from sys.server_principals where lower([name]) =lower('$(account)'))
BEGIN
  CREATE LOGIN [$(account)] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
END

where I would just replace $(account) with DOMAIN\\t''acct or DOMAIN\\t'acct?

replacing with the former works only for the first replacement and says

CREATE LOGIN [DOMAIN\t''acct] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
Windows NT user or group 'DOMAIN\t''acct' not found. Check the name again.

for the create login statement.

And for the latter, I cannot just replace with t'acct as that would be incorrectly escaped. Doing it with a box throws this error:

select * from sys.server_principals where lower([name]) = lower([DOMAIN\t'acct])
Invalid column name 'DOMAIN\t'acct'.

Any additional pointers to prevent sql injection would be helpful. I'm considering accounts such as DOMAIN\\'tacct as well (input is validated as valid windows user as well as domain format (contains \\ in the name)).

To prevent sql injection it is better to use parameterized query instead of using placeholders, I think.

To make CREATE LOGIN statement work with sql parameter you will have to use dynamic sql. Function QUOTENAME will help you escape login name properly. In this case your sql code could look like:

if not exists(select * from sys.server_principals where lower([name]) = lower(@loginName))
begin
    declare @sql nvarchar(max);
    set @sql =
        'CREATE LOGIN ' + quotename(@loginName) +
        ' FROM WINDOWS WITH DEFAULT_DATABASE = [master]';

    exec sp_executesql @sql;
end

where @loginName is the parameter that you should supply.

仅在选择查询中使用 SQL 替换功能在传递占位符时将 ' 替换为 ''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM