Как поменять server collection ms sql

Обновлено: 04.07.2024

Thanks for your help.

I tried with the command you given but still getting the problem.

start /wait Z:\setup.exe /qn INSTANCENAME=MSSQLSERVER REINSTALL=SQL_Engine REBUILDDATABASE=1 SAPWD=MyPassword211 SQLCOLLATION=Latin1_General_CI_AS

Here, Z:\ is a map drive which contains sql server 2008 setup files.

It shows me following error:

The Syntax of argument "/QN" is incorrect. Either the delimiter '=' is missing or there is one or more space characters befor the delimiter '='.

According to the link that Joe posted, the switch should be /QB, not /QN.

I also tried with /QB, but with this switch it's showing me same problem.

I hope /QB parameter no more exits in SQL 2008 for silent installation, you need to use /Q parameter for the same.

I tried /Q option too, but it was also not working.

Have you managed to get this to work with the RTM version? AFAIK, changing collation settings post install was not available until after RC0.

See the following blog with the correct syntax for rebuilding system databases in SQL Server 2008. Also covers the syntax for changing the server collation.

i uninstalled sqlexpress 2008 and re-installed it again to change the collation to Latin1_General_CS_AS, but how must now change my actual DATABASE's collation. i must rebuild it yes, but how do i do that. i need to use setup.exe , i only have: SQLEXPR_x86_ENU. this is the application i used to install sqlexpress 2008. i got this application off microsoft site.

i rebuilt my db with a different collation. when i check the summary log it says collation is Latin1_General_CS_AS(correct), but when i open my db and check the field collation of a table it is still the old one?? how does that work i dont understand. can someone please xplain?

Yes, its possible. Either you've done one of two things.

1) Took the backup of database which was having old collation and restore it on database with new collation.

2) Detached the database on old collation and attached on database with new collation.

In either of case, the table field collation will show old collation.

I had same problem, I fixed it with the following ways.

1) Create a empty database on new collation

2) Restored the back up of old collation on new collation with diff database name

3) Import table data from old to new one, making use of Import/Export data wizard.

In this way what will happen is when you create an empty database, it will have new collation and when you import table data it will have new collation as well.

Hope this helps

Hi,

you can change the collation by using the MS SQL Server 2008 Management Studio too.
This would be the corresponding command, which runs -quiet- for a comparingly long time (4min) since the DOS Window is closed:

E:\setup.exe /Quiet /ACTION=REBUILDDATABASE /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=x \Administrator /SAPWD=x /SQLCOLLATION=SQL_Latin1_General_CP850_BIN2

Axel Arnold Bangert - Herzogenrath 2009

i rebuilt my db with a different collation. when i check the summary log it says collation is Latin1_General_CS_AS(correct), but when i open my db and check the field collation of a table it is still the old one?? how does that work i dont understand. can someone please xplain?

helloise

SQL Server and database collations are DEFAULT collations. Actual collations in tables maybe quite different.

A shocker: COLLATION is not table-level, rather column-level property. Therefore, text columns in a table must individually be rebuilt to the desired collation.

Work around: just place COLLATE DATABASE_DEFAULT to the right side of an expression giving collation error.

I have always used the below command. This has to be done after inserting the setup disk. Hope this works for you.

Setup /QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=InstanceName
/SQLSYSADMINACCOUNTS=accounts /[ SAPWD= StrongPassword ]
/SQLCOLLATION=CollationName

The above will work, but it's important to keep checking the log file:

C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\Summary.txt

As you may have to overcome any errors in there before it will let you apply the change. If you're trying to apply this change to a cluster, good luck, because i haven't been able to do it yet! . Looking like a reinstall!

It was a very healthy discussion. I would like to know the exact soultion to fix this issue.

can anyone post the answer?

It should be this one:

However this is true only for microsoft SQL server 2008. The express version has a lot of bugs (varying from automaticly choosing collation according to language or regional option (depends on what OS), or a major bug in bootstrapped setup.exe or even on new installer which does not allow direct access to setup.exe).

There are a several workarounds (But these do not help you to make your DB clean and neat):

1. change the collation of the database, and not the collation of the server.

2. install SQL server express 2005 WHICH ALLOWS YOU TO CHOOSE COLLATION IN THE INSTALLER! (jesus. what were they thinking in microsoft when they released MSSQLEXPRESS 2008?)

hi, i had a similar challenge and not wanting to re-install the instnace, i looked around the management studio control and found the "FACETS" in the sql 2008 express. Do this by right-clicking on the db in question and select FACETS. You will find a editable field for Collation. There isn't a drop down list of all the types, so you wil have to know the name in advnaced.

hope this helps.

1. change the collation of the database, and not the collation of the server.

It should be noted that the references are to SQL Server default collation and database default collation. Actual column collations will not change by changing the defaults. You have to perform ALTER TABLE. ALTER COLUMN. to change column collation. Alternative is rebuilding (CREATE TABLE & populate) the table with the desired collation. See articles in my previous post.

will it work in cluster also ?? or we having some different way to implement in Cluster Env. india

For cluster environemnt you just need to take the resource(SQL server service) offline from cluster admin and follow the same process. Check this one.

  • Предложено в качестве ответа MSSQL DBA 4 августа 2011 г. 8:39
  • Помечено в качестве ответа Olaf Helper MVP 7 апреля 2013 г. 18:15

It rebuilds all the system database, so you will loose any data stored in the system databases like logins, linked servers, jobs, etc. You need to attach your user databases so that you could use them.

Can you explain more detailed, what happens, please?

At the time of installation, I'd specified the collation as LATIN1_GENERAL_BIN, and now I want to change this collation to LATIN1_GENERAL_CI_AS.

Please note that I don't want to change the collation of specific db but need to change the sql server 2008 server's settings.

How to accomplish this requirement with minimum efforts?

Hi there. I realize this is a rather old question, but for anyone looking for info on changing the collation of a SQL Server instance (especially after it's been in use for any amount of time), please see the following post of mine that provides a detailed description of the undocumented "sqlservr.exe -q" option:

That approach is definitely less effort than rebuilding and reconfiguring the instance. To leave one DB unmodified, just detach it first, do the update, then re-attach it (this is also noted in the post itself).

Take care,
Solomon.

A shocker: COLLATION is not table-level, rather column-level property. Therefore, text columns in a table must individually be rebuilt to the desired collation.

Work around: just place COLLATE DATABASE_DEFAULT to the right side of an expression giving collation error.

Hello Kalman. The DATABASE_DEFAULT option is not a universal fix for collation errors. It is intended mainly to resolve issues in temporary tables when:

  1. the database the code is executing in has a default collation that is different than the instance-level collation, and
  2. the database's default collation was used in permanent tables and/or table variables, and
  3. joins are being done between the local and temporary tables on string columns, and
  4. the local database's default collation is not guaranteed to be a particular collation

Essentially, the dynamic nature of DATABASE_DEFAULT allows one to deploy code to any DB on any instance, not knowing what the default collation will be, yet still wanting to work with whatever that collation happens to be. The most common use case I can think of is 3rd party software that will work with whatever collation you prefer.

The reason that DATABASE_DEFAULT is not a universal fix is that the column causing a collation conflict error might not be using the database's default collation. The database could be using Latin1_General_100_CI_AS but the column might be using Latin1_General_100_BIN2. In that case, assuming that the instance is not also using Latin1_General_100_BIN2, then it doesn't matter if the instance is using Latin1_General_100_CI_AS or anything else, if the error is coming from a temp table. The local column is using Latin1_General_100_BIN2 so in most cases you want the predicate to also use Latin1_General_100_BIN2, and using DATABASE_DEFAULT would equate to Latin1_General_100_CI_AS, which would not behave as expected. For scenarios like that, you would actually want to specify COLLATE <column's_collation> to maintain the column's intended behavior.

The server collation acts as the default collation for all system databases that are installed with the instance of SQL Server, and also any newly created user databases. You should carefully choose server-level collation because it affects:

  • Sorting and comparison rules in = , JOIN , ORDER BY and other operators that compare textual data.
  • Collation of the CHAR , VARCHAR , NCHAR , and NVARCHAR columns in system views, system functions, and the objects in TempDB (for example, temporary tables).
  • Names of the variables, cursors, and GOTO labels. Variables @pi and @PI are considered as different variables if the server-level collation is case-sensitive, and the same variables if the server-level collation is case-insensitive.

Changing the server collation in SQL Server

Changing the default collation for an instance of SQL Server can be a complex operation and involves the following steps:

Make sure you have all the information or scripts needed to re-create your user databases and all the objects in them.

Export all your data using a tool such as the bcp Utility. For more information, see Bulk Import and Export of Data (SQL Server).

Drop all the user databases.

Rebuild the master database specifying the new collation in the SQLCOLLATION property of the setup command. For example:

Create all the databases and all the objects in them.

Import all your data.

Instead of changing the default collation of an instance of SQL Server, you can specify a default collation for each new database you create via the COLLATE clause of the CREATE DATABASE and ALTER DATABASE statements. For more information, see Set or Change the Database Collation.

Setting the server collation in Managed Instance

Server-level collation in Azure SQL Managed Instance can be specified when the instance is created and cannot be changed later. You can set server-level collation via Azure portal or PowerShell and Resource Manager template while you are creating the instance. Default server-level collation is SQL_Latin1_General_CP1_CI_AS. If you are migrating databases from SQL Server to Managed Instance, check the server collation in the source SQL Server using SERVERPROPERTY(N'Collation') function and create a Managed Instance that matches the collation of your SQL Server. Migrating a database from SQL Server to Managed Instance with the server-level collations that are not matched might cause several unexpected errors in the queries. You cannot change the server-level collation on the existing Managed Instance.

В этом разделе описано, как задать и изменить параметры сортировки базы данных с помощью SQL Server Management Studio или Transact-SQL. Если параметры сортировки не указаны, используются параметры сортировки сервера.

Инструкция ALTER DATABASE COLLATE в Базе данных SQL Azure не поддерживается.

В этом разделе

Перед началом работы

Задание и изменение параметров сортировки базы данных с помощью:

Перед началом

Ограничения

Параметры сортировки Windows только для Юникода могут использоваться лишь с предложением COLLATE для применения параметров сортировки к данным типов nchar, nvarchar и ntext на уровне столбца и на уровне выражения. Их нельзя использовать с предложением COLLATE для изменения параметров сортировки базы данных или экземпляра сервера.

Если указанные или используемые объектом по ссылке параметры сортировки используют кодовую страницу, не поддерживаемую Windows, то компонент Компонент Database Engine выдаст ошибку.

Рекомендации

Если изменяются параметры сортировки базы данных, то изменяется следующее:

Все столбцы типа char, varchar, text, nchar, nvarchar или ntext в системных таблицах заменяются новым параметром сортировки.

Все существующие параметры типа char, varchar, text, nchar, nvarchar или ntext и возвращаемые скалярные значения для хранимых процедур и определяемых пользователем функций заменяются новым параметром сортировки.

Системные типы данных char, varchar, text, nchar, nvarchar или ntext и все определяемые пользователем типы данных, основанные на этих системных типах данных, заменяются новым параметром сортировки по умолчанию.

Вы можете изменить параметры сортировки любых новых объектов, созданных в пользовательской базе данных, с помощью предложения COLLATE инструкции ALTER DATABASE. Эта инструкция не изменяет параметры сортировки столбцов в любых существующих пользовательских таблицах. Они могут быть изменены с помощью предложения COLLATE инструкции ALTER TABLE.

Изменение параметров сортировки базы данных или отдельных столбцов не изменяет базовых данных, уже хранящихся в существующих таблицах. Если приложение явным образом не обрабатывает преобразование и сравнение данных с различными параметрами сортировки, рекомендуется перевести существующие в базе данных данные в новые параметры сортировки. Это устранит риск того, что приложения могут неправильно изменять данные, что приведет к возможным неправильным результатам или незамеченной потере данных.

По умолчанию при изменении параметров сортировки базы данных только новые таблицы наследуют параметры сортировки новой базы данных. Существует несколько способов преобразования существующих данных в новые параметры сортировки.

Преобразование данных на месте. Сведения о преобразовании параметров сортировки для столбца в существующей таблице см. в разделе Задание или изменение параметров сортировки столбца. Эта операция проста в реализации, но может стать блокирующей проблемой для больших таблиц и нагруженных приложений. Приведем следующий пример преобразования столбца MyString в новые параметры сортировки на месте.

Копирование данных в новые таблицы, в которых используются новые параметры сортировки, и замена исходных таблиц в той же базе данных. Создайте новую таблицу в текущей базе данных, которая будет наследовать параметры сортировки базы данных, скопируйте данные из старой таблицы в новую, удалите исходную таблицу и переименуйте новую таблицу в имя исходной таблицы. Эта операция выполняется быстрее, чем преобразование на месте, но может стать сложной задачей при обработке сложных схем с зависимостями, такими как ограничения внешнего ключа, ограничения первичного ключа и триггеры. Кроме того, перед окончательным удалением потребуется финальная синхронизация исходной и новой таблиц в случае, если данные будут продолжать изменяться приложениями. Приведем следующий пример преобразования "копирование и замена" столбца MyString в новые параметры сортировки.

Копирование данных в новую базу данных, в которой используются новые параметры сортировки, и замена исходной базы данных. Создайте новую базу данных, используя новые параметры сортировки, и перенесите данные из исходной базы данных с помощью таких средств, как Службы Integration Services или мастер импорта и экспорта в SQL Server Management Studio. Это более простой подход для сложных схем. Здесь также перед окончательным удалением потребуется финальная синхронизация исходной и новой баз данных в случае, если данные будут продолжать изменяться приложениями.

безопасность

Permissions

Чтобы создать базу данных, требуется разрешение CREATE DATABASE в базе данных master, разрешение CREATE ANY DATABASE либо ALTER ANY DATABASE .

Чтобы изменить параметры сортировки имеющейся базы данных, требуется разрешение ALTER в базе данных.

Использование среды SQL Server Management Studio

Задание и изменение параметров сортировки базы данных

В обозревателе объектов подключитесь к экземпляру компонента Компонент SQL Server Database Engine, разверните его, а затем разверните узел Базы данных.

При создании новой базы данных щелкните правой кнопкой мыши Базы данных и выберите пункт Создать базу данных. Если использовать параметры сортировки по умолчанию не нужно, то перейдите на страницу Параметры и выберите нужный вариант в раскрывающемся списке Параметры сортировки .

Если база данных уже существует, щелкните правой кнопкой мыши нужную базу данных и выберите пункт Свойства. Перейдите на страницу Параметры , а затем выберите нужный вариант в раскрывающемся списке Параметры сортировки .

По завершении нажмите кнопку ОК.

Setting the server collation in SQL Server

The server collation is specified during SQL Server installation. The default server-level collation is based upon the locale of the operating system. For example, the default collation for systems using US English (en-US) is SQL_Latin1_General_CP1_CI_AS. Unicode-only collations cannot be specified as the server-level collation. For more information, including the list of OS locale to default collation mappings, see the "Server-level collations" section of Collation and Unicode Support.

The server-level collation for SQL Server Express LocalDB is SQL_Latin1_General_CP1_CI_AS and cannot be changed, either during or after installation.

Использование Transact-SQL

Задание параметров сортировки базы данных

Установите соединение с компонентом Компонент Database Engine.

На панели «Стандартная» нажмите Создать запрос.

Скопируйте следующий пример в окно запроса и нажмите кнопку Выполнить. В этом примере показано задание параметров сортировки с помощью предложения COLLATE . В примере создается база данных MyOptionsTest , в которой используются параметры сортировки Latin1_General_100_CS_AS_SC . Чтобы проверить параметр, после создания базы данных выполните инструкцию SELECT .

Изменение параметров сортировки базы данных

Установите соединение с компонентом Компонент Database Engine.

На панели «Стандартная» нажмите Создать запрос.

Скопируйте следующий пример в окно запроса и нажмите кнопку Выполнить. В этом примере показано изменение имени параметров сортировки с помощью предложения COLLATE в инструкции ALTER DATABASE . Выполните инструкцию SELECT , чтобы проверить изменение.

Вопрос: каким образом можно изменить collation всех уже существующих структур БД ?

Чем руководствовался разработчик, когда принимал решение написать код, который вываливается с ошибкой, если коллейшены при установке сервера и при создании базы не совпадают? Он хотел получить профит по производительности? Ещё что то? Я даже не представляю, что можно полезного получить.
У меня она версия - он лабал по принципу: "скопипастил из инета, ошибка, пять случайных правок, заработало на моём компе, таск закрываем". А у вас? :-)

Но это в общем неважно, синтаксис можно и в хелпе посмотреть. Главное, что ИМХО правильно так, а не приведение коллейтов в запросе.

Читайте также: