Sql ошибка 5170

  • Remove From My Forums
  • Question

  • Hi,

    Last month I created a database named _temp. I imported data into it and then renamed the database to something else. Now I’m trying to create another database named _temp, but MSSMS throws an error:

    Create failed for Database ‘_temp’. (Microsoft.SqlServer.Smo)

    Additional Information:

         An exception occurred while excuting a Transact-SQL statement or batch.
         (Microsoft.SqlServer.ConnectionInfo)

              Cannot create file ‘C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQDATA_temp.mdf’ because it already exists. Change the file path or the file name, and retry the operation. CREATE DATABASE
    failed. Some file names listed could not be created. Check related errors. (Microsoft SQL Server, Error: 5170)

     I can’t navigate to the file to delete it; the folder «MSSQL10.MSSQLSERVER» doesn’t appear. The ideal solution would be to be able to create another _temp database. Anyway I can delete the old files that are blocking
    me?

Answers

  • While you renamed the original database, the file names did not change.

    Two options:

    1) use different file names for this database:

    CREATE DATABASE _temp ON (NAME = ‘_temp’,
       FILENAME = ‘C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLDATA_temp_of_20130404.mdf’)
    LOG ON (NAME = ‘_temp_log’,
       FILENAME = ‘C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLDATA_temp_of_20130404.ldf’)

    2) Use ALTER DATABASE to change the name of the other databaseÖ

    ALTER DATABASE used_to_be_temp
       MODIFY (NAME = ‘_temp’, FILENAME = ‘C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLDATAuser_to_be_temp.mdf’)

    ALTER DATABASE used_to_be_temp
       MODIFY (NAME = ‘_temp_log’, FILENAME = ‘C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLDATAuser_to_be_temp.ldf’)


    Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

    • Proposed as answer by

      Thursday, April 4, 2013 10:21 PM

    • Marked as answer by
      Woojamon
      Friday, April 5, 2013 6:05 PM

The problem

I recently had, for the first time, to create a brand-new ASP.NET web application that made use of the built-in Membership/Roles functionality, using the default of SQL Server Express, NOT a full installation of SQL Server. I had previously wrestled with issues when upgrading an older application using Membership/Roles to ASP.NET 4.0, and blogged about it . However, this issue was specific to a brand-new ASP.NET 4.0 application, albeit with VS 2010 SP1 and SQL Server 2008 SP1 installed.

All was well until I fired up the Web Site Administration tool and clicked the Security tab. I was suddenly greeted with the following error message:


There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store.

The following message may help in diagnosing the problem: An error occurred during the execution of the SQL file ‘InstallCommon.sql’. The SQL error number is 5170 and the SqlException message is: Cannot create file ‘C:[Application_PATHAPP_DATAASPNETDB_TMP.MDF’ because it already exists. Change the file path or the file name, and retry the operation. CREATE DATABASE failed. Some file names listed could not be created. Check related errors. Creating the ASPNETDB_[app GUID] database…


I checked the App_Data directory, and, sure enough, the ASPNETDB_TMP.MDF file was there.

Googling didn’t turn up much that was specific to my issue.

The fix

The answer turned out to be simple, and hinted at in the error message: in the Web.config file in the root of your web app, find the roleManager element, and set it to true:

<roleManager enabled="true">

But—and this is what threw me—you must first delete the ASPNETDB_TMP.MDF file, and its companion log file with the .ldf extension, from the App_Data directory, before re-running the Web Site Administration tool . This can be done within Visual Studio. Once this is done, make sure you close the ASP.NET Development server, which will be in the system tray, aka the notification area. Then go back into Visual Studio and launch the Web Site Administration tool. You should now be able to click the Security tab and configure your Roles, etc.


This entry was posted on April 6, 2011, 1:28 pm and is filed under ASP.NET, SQL Server, Visual Studio. You can follow any responses to this entry through RSS 2.0.

You can leave a response, or trackback from your own site.

Перейти к содержимому раздела

TechnologiCS

Форумы TechnologiCS

Вы не вошли. Пожалуйста, войдите или зарегистрируйтесь.

Дерево сообщений Активные темы Темы без ответов

Не создаётся база данных

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

#1 3 октября 2006 12:04:00

  • Хмурый
  • Участник
  • Неактивен
  • На форуме с 3 октября 2006
  • Сообщений: 4

Re: Не создаётся база данных

е могу создать базу данных в ознакомительной версии. 

SQL Server Error: SQL State: 42000, SQL Error Code: 1802
CREATE DATABASE failed. Some file names listed could not be created. Check previous errors.
SQL State: 42000, SQL Error Code: 5170
Cannot create file ‘C:Program FilesMicrosoft SQL ServerMSSQLDataIndustriCS.mdf’ be

create database [IndustriCS] collate Cyrillic_General_CI_AS

Win XP SP2 
TechnologicCS v 4.6.3.0(8476)

#2 Ответ от Владимир Белов 3 октября 2006 12:25:00

  • Владимир Белов
  • Участник
  • Неактивен
  • На форуме с 2 декабря 2005
  • Сообщений: 62

Re: Не создаётся база данных

Хмурый писал(а):
Не могу создать базу данных в ознакомительной версии.

SQL Server Error: SQL State: 42000, SQL Error Code: 1802
CREATE DATABASE failed. Some file names listed could not be created. Check previous errors.
SQL State: 42000, SQL Error Code: 5170
Cannot create file ‘C:Program FilesMicrosoft SQL ServerMSSQLDataIndustriCS.mdf’ be
===
create database [IndustriCS] collate Cyrillic_General_CI_AS

Код ошибки говорит, что такой файл уже существует. Убедитесь, что вы устанавливаете новую копию базы данных, а не поверх существующей.

#3 Ответ от Хмурый 3 октября 2006 12:33:00

  • Хмурый
  • Участник
  • Неактивен
  • На форуме с 3 октября 2006
  • Сообщений: 4

Re: Не создаётся база данных

#4 Ответ от Митюгов Денис 3 октября 2006 14:44:00

  • Митюгов Денис
  • Участник
  • Неактивен
  • На форуме с 2 октября 2006
  • Сообщений: 14

Re: Не создаётся база данных

Хмурый писал(а):
е могу создать базу данных в ознакомительной версии.

SQL Server Error: SQL State: 42000, SQL Error Code: 1802
CREATE DATABASE failed. Some file names listed could not be created. Check previous errors.
SQL State: 42000, SQL Error Code: 5170
Cannot create file ‘C:Program FilesMicrosoft SQL ServerMSSQLDataIndustriCS.mdf’ be

create database [IndustriCS] collate Cyrillic_General_CI_AS

Win XP SP2
TechnologicCS v 4.6.3.0(8476)

На сайте описаны оптимальные настройки MS для работы с ТКС
см. СВОЙСТВА создаваемой БД.
В менеджере MS_SQL надо-бы ее создать ручками с требуемым именем.
Для «SA» поставить «OWNER»
В таблице мастер идентичные настройки — она уже создана при установке MS_SQL …
Я так делаю !!!

#5 Ответ от Владимир Белов 3 октября 2006 14:51:00

  • Владимир Белов
  • Участник
  • Неактивен
  • На форуме с 2 декабря 2005
  • Сообщений: 62

Re: Не создаётся база данных

Митюгов Денис писал(а):
Я так делаю !!!

Не надо руками лазить в базу данных, она по умолчанию создается с правильными настройками. Эти настройки не просто оптимальные, а необходимые для правильной работы!

#6 Ответ от Владимир Белов 3 октября 2006 14:59:00

  • Владимир Белов
  • Участник
  • Неактивен
  • На форуме с 2 декабря 2005
  • Сообщений: 62

Re: Не создаётся база данных

Митюгов Денис писал(а):
На сайте описаны оптимальные настройки MS для работы с ТКС
см. СВОЙСТВА создаваемой БД.
В менеджере MS_SQL надо-бы ее создать ручками с требуемым именем.

База данных IndustriCS создается только(!) программой установки TCS, существующая база данных будет удалена, а на ее месте создана новая, с правильными настройками. После установки можно только проверить, что все ОК в соответствии с документацией.

Митюгов Денис писал(а):
Для «SA» поставить «OWNER»
В таблице мастер идентичные настройки — она уже создана при установке MS_SQL …

База данных master может иметь много отличий от БД IndustriCS, хотя бы тот же collation order! Их ни в коем случае нельзя подстраивать друг под друга, потому что это совершенно разные вещи (master — это уровень сервера MSSQL, а IndustriCS — только БД TCS), особенно, если вы не уверены в том, для чего это делается.

Сообщения 6

Тему читают: 1 гость

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

I’m not really sure why you are doing this (instead of removing the old files if the database is no longer attached) but anyway…..

This will just generate new filenames base don the current date/time then build a sql statement up to create a new database. Obviously you can edit the sizes and/or paths as you wish.

DECLARE @dt varchar(14) = format(getdate(), 'yyyyMMddHHmmss')

declare @dbf varchar(256) = CONCAT('c:program filesmicrosoft sql servermssqldataexampledat', @dt, '.mdf')
declare @logf varchar(256) = CONCAT('c:program filesmicrosoft sql servermssqldataexamplelog', @dt, '.ldf')

declare @sql varchar(max) = CONCAT(

'CREATE DATABASE example
ON
( NAME = example_dat,
   FILENAME = ''', @dbf, ''',
   SIZE = 20MB,
   FILEGROWTH = 5MB )
LOG ON
( NAME = example_log,
   FILENAME = ''', @logf, ''',
   SIZE = 10MB,
   FILEGROWTH = 5MB )');

print @sql
EXEC (@sql)

Я столкнулся с проблемой, когда я получаю сообщение об ошибке SQL Server Error Msg 5170 — Невозможно создать файл «%ls», поскольку он уже существует. Измените путь к файлу или имя файла и повторите операцию.

IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'example') BEGIN CREATE DATABASE [example] END

Но я получаю сообщение об ошибке 5170, говорящее, что оно уже существует, когда я смотрю в пути: …MSSQLDATA, что example.mdf и example_log.mdf уже существуют. Я пытаюсь, чтобы он каждый раз генерировал новое имя, например, пример 123456 и пример 1547886_log. Как я должен сгенерировать новое имя, если файл пути уже существует, я безуспешно искал по всему Интернету.

Я попытался добавить. `используйте разные имена файлов для этой базы данных:

CREATE DATABASE _temp ON (NAME = ‘_temp’, FILENAME = ‘C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLDATA_temp_of_20130404.mdf’) LOG ON (NAME = ‘_temp_log’, FILENAME = ‘C: Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLDATA_temp_of_20130404.ldf’)`

1 ответ

Я не совсем уверен, почему вы это делаете (вместо того, чтобы удалять старые файлы, если база данных больше не подключена), но в любом случае…..

Это просто создаст новую базу имен файлов с текущей датой/временем, а затем создаст оператор sql для создания новой базы данных. Очевидно, вы можете редактировать размеры и/или пути по своему усмотрению.

DECLARE @dt varchar(14) = format(getdate(), 'yyyyMMddHHmmss')

declare @dbf varchar(256) = CONCAT('c:program filesmicrosoft sql servermssqldataexampledat', @dt, '.mdf')
declare @logf varchar(256) = CONCAT('c:program filesmicrosoft sql servermssqldataexamplelog', @dt, '.ldf')

declare @sql varchar(max) = CONCAT(

'CREATE DATABASE example
ON
( NAME = example_dat,
   FILENAME = ''', @dbf, ''',
   SIZE = 20MB,
   FILEGROWTH = 5MB )
LOG ON
( NAME = example_log,
   FILENAME = ''', @logf, ''',
   SIZE = 10MB,
   FILEGROWTH = 5MB )');

print @sql
EXEC (@sql)


0

Alan Schofield
28 Мар 2023 в 02:05

Понравилась статья? Поделить с друзьями:
  • Sql server ошибка 258
  • Sql server ошибка 17113
  • Sql server ошибка 15407
  • Sql server ошибка 15401
  • Sql server ошибка 15105