In order to avoid injection and escaping problems, dynamic SQL queries should be executed with parameters, e.g.:
SET @sql = N'SELECT COUNT(*) FROM AppUsers WHERE Username = @user AND Password = @pass
EXEC sp_executesql @sql, '@user nvarchar(50), @pass nvarchar(50)', @username, @password
Second parameter is a list of parameters used in query with their types, after this list are provided variables that will be used as parameter values.
sp_executesql will escape special characters and execute sql query.