Dropping a constraint in MS SQL Server
Hi All,
Does anybody know if there's a way to check if a constraint
exists before dropping it?
In other words, how do I check if constraint
"FK_Products1_ID" exists before dropping it (see below) so I won't
get the error " 'FK_Products1_ID' is not a constraint. Could not
drop constraint"
ALTER TABLE Products2_Table DROP CONSTRAINT FK_Products1_ID
Thanks in advance!
Thank you very much, Ken. It works.
The correct syntax:
IF EXISTS (select * from dbo.sysobjects where name =
'FK_Products1_ID')
BEGIN
ALTER TABLE Products2_Table DROP CONSTRAINT FK_Products1_ID
END
Sorry about not mentioning what version of sql server.
Yes, I'm using version 2k.
Similar Messages
-
How to delete/drop all the tables from SQL Server Database without using Enterprise Manager?
I tried using DROP Tables, Truncate Database, Delete and many more but it is not working. I want to delete all tables using Query Analyzer, i.e. through SQL Query.
Please help me out in this concern.
Nishith ShahInformative thread indeed. Wish I saw it early enough. Managed to come up with the code below before I saw this thread.
declare @TTName Table
(TableSchemaTableName
varchar
(500),
[status] int
default 0);
with AvailableTables
(TableSchemaTableName)
as
(select
QUOTENAME(TABLE_SCHEMA)
+
+
QUOTENAME(TABLE_NAME)
from
INFORMATION_SCHEMA.TABLES)
insert into @TTName
(TableSchemaTableName)
select *
from AvailableTables
declare @TableSchemaTableName varchar
(500)
declare @sqlstatement nvarchar
(1000)
while 1=1
begin
set @sqlstatement
=
'DROP TABLE '
+ @TableSchemaTableName
exec
sp_executeSQL
@sqlstatement
print
'Dropped Table : '
+ @TableSchemaTableName
update @TTName
set [status]
= 1
where TableSchemaTableName
= @TableSchemaTableName
if
(select
count([Status])
from @TTName
where [Status]
= 0)
= 0
break
end -
Drop Transation Log Files in SQL server
Hi friends,
I am useing sql server 2005 , in my databse transation log file is increased up to 20 GB ,so i am adding one more transation file , so i want delete pervious unused transation log file,so what is the procedure for drop the transation log file from my databse any one can help me....
Thanks,
NageswarHi,
Check SAP Note 363018
also check MSSQL Transaction Log full
Re: space problem
regards,
kaushal -
Hi,
We have Sql Server 2008R2 clustered instance running in 2 nodes with Windows 2008R2 SP1 operating system. I would like to know how I could clear the existing names in the USER NAME drop down list in the Sql Server Management studio.
Thanking in you advance,
Binny Mathew,SQL Server Management Studio 2008 delete the file:
C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin
http://dynamicsgpland.blogspot.in/2012/04/clearing-remembered-default-login-for.html -
SQL Server 2008 File Stream On Existing Table
Hi Folks,
I have enabled the SQL Server File Stream option on a Existing table.
1. Created a GUID Column
2. Created a File Stream Column
3. Swapped the Blob Column information into file Stream column.
4. Dropped the BLOB Column.
I could evidence, The above Step 3 Process moved out all the Blob Data into an configured Network File Group.
Ex:
Existing BLOB Data Size --> 10 GB
Once after the completion of above step 4, SQL Server is not freeing up the BLOB occupied Space 10 GB. It should have only few MB's pointer address to the network file Group?
If we create a new table with File Stream data type and insert the existing BLOB data ,Will result few MB pointer Address occupied in the newly created table. We except the similar behaviour for updating BLOB to File Stream in existing table.
Please advice me.
Thanks
Narendran
NarendranWhen you drop a column, SQL Server only mark the column as dropped, but does not reclaim the space, as that requires data to be shuffled around. You need to rebuild the clustered index (and any other index with the column) to reclaim the space. See repro
below:
CREATE TABLE myblobbie (id int NOT NULL PRIMARY KEY,
name sysname NOT NULL,
blob varchar(MAX) NOT NULL)
go
INSERT myblobbie(id, name, blob)
SELECT object_id, name, replicate(convert(varchar(MAX), name), 1000)
FROM sys.objects
go
EXEC sp_spaceused myblobbie
go
ALTER TABLE myblobbie DROP COLUMN blob
go
EXEC sp_spaceused myblobbie
go
ALTER INDEX ALL ON myblobbie REBUILD
go
EXEC sp_spaceused myblobbie
go
DROP TABLE myblobbie
Erland Sommarskog, SQL Server MVP, [email protected] -
Data Modeler EA1: Importing SQL Server Data Dictionary issue
I am using the Data Dictionary Import Wizard to import the Schema of a SQL Server 2005 database (JDBC connection has "SQL Server 2005" as the Type) into the Oracle SQL Developer Data Modeler. In step 4 of the import, under the "Import to:" section, there is only SQL Server 2000 available in the drop down.
Database Name: Microsoft SQL Server
Database Version 10.00.2531
I assumed that a SQL Server 2008 DB would be handled as a SQL Server 2005 DB (that is until 2008 is supported). Currently the db is not using any SQL Server 2008 specific features.
In Oracle Developer Data Model 2, the tables with xml data type would not import. This time, those tables did import. -
Cannot set up data source for SQL Server 2005
Is it possible to use Microsoft's Beta 2 version of the SQL Server 2005 JDBC driver with WebLogic 9.0? I've downloaded the driver and added it to my server classpath, but when I try to create a new data source using the admin console, the drop-down list for Microsoft SQL Server only contains drivers for the 2000 version. If I select "Other" from the list and try to move on, I get a cryptic, page-long error on the admin console. If I just select the 2000 driver and try to manually modify the parameters on the next set of screens, I still get errors when I try to test the configuration. I've successfully used a third-party driver before, but this one does not seem to be working. Any help would be greatly appreciated.
Regards,
SabrinaSabrinaL wrote:
Is it possible to use Microsoft's Beta 2 version of the SQL Server 2005 JDBC driver with WebLogic 9.0? I've downloaded the driver and added it to my server classpath, but when I try to create a new data source using the admin console, the drop-down list for Microsoft SQL Server only contains drivers for the 2000 version. If I select "Other" from the list and try to move on, I get a cryptic, page-long error on the admin console. If I just select the 2000 driver and try to manually modify the parameters
on the next set of screens, I still get errors when I try to test the configuration. I've successfully used a third-party driver before, but this one does not seem to be working. Any help would be greatly appreciated.
Regards,
SabrinaHere I describe the steps I took to bypass the console in making a new pool.
1 - Edit the script %DOMAIN_HOME%\bin\startWebLogic.cmd to add a line like this:
set CLASSPATH=%CLASSPATH%;\new_ms_driver\beta2\sqljdbc_1.0\enu\sqljdbc.jar
In other words, you have to explicitly add a third party driver's classes to
the CLASSPATH that will be in effect for the server. Just adding the driver
to your window's class path will do nothing.
2 - Go to the directory %DOMAIN_HOME%\config\jdbc, where you will find
files of the name *-jdbc.xml. Each of these represents a DataSource.
Copy one of them, perhaps either examples-demo-jdbc.xml, or
examples-demoXA-jdbc.xml depending on whether you want to make an XA
or non-XA pool. Make you new file's name like the name of the DataSource,
still ending in -jdbc.xml. Eg: MS_Beta-jdbc.xml
3 - Edit this file to change as much as would be clear for the
driver you want. Eg: change the driver class to the class you want,
the user name, URL, test table etc. Also, change the pool's initial
capacity to 0. This is so the pool can be created without making a
connection. We need that because the password is encrypted, and
there is no manual way for you to add the correct one yet.
4 - go one directory up, and edit the config.xml. Find a
jdbc-system-resource entry corresponding to the original
resource file you copied. Make a new entry in the config file,
like the original, but change the Datasource name to your new one.
5 - If this all went well, reboot your server and go to your data
source in the console, and edit it. Alter the password to what it
really should be, and you can also change whatever else you might
want.
6 - shut down again, and reboot, and you should then be able to go to
your data source in the console and test a connection.
That's it. Here is an example of a jdbc.xml file I made, and
the entry I made in the config.xml:
config/jdbc/newpool-jdbc.xml:
<?xml version='1.0' encoding='UTF-8'?>
<jdbc-data-source xmlns="http://www.bea.com/ns/weblogic/90" xmlns:sec="http://www.bea.com/ns/weblogic/90/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wls="http://www.bea.com/ns/weblogic/90/security/wls"
xsi:schemaLocation="http://www.bea.com/ns/weblogic/90/domain.xsd">
<name>newpool</name>
<jdbc-driver-params>
<url>jdbc:sqlserver://frogger:1433</url>
<driver-name>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-name>
<properties>
<property>
<name>user</name>
<value>joe</value>
</property>
</properties>
<password-encrypted>{3DES}cPpx2Z6faqY=</password-encrypted>
</jdbc-driver-params>
<jdbc-connection-pool-params>
<initial-capacity>1</initial-capacity>
<max-capacity>5</max-capacity>
<capacity-increment>1</capacity-increment>
<shrink-frequency-seconds>900</shrink-frequency-seconds>
<test-connections-on-reserve>true</test-connections-on-reserve>
<test-table-name>SQL select 1</test-table-name>
<profile-type>0</profile-type>
</jdbc-connection-pool-params>
<jdbc-data-source-params>
<jndi-name>newpool</jndi-name>
<global-transactions-protocol>TwoPhaseCommit</global-transactions-protocol>
</jdbc-data-source-params>
<jdbc-xa-params></jdbc-xa-params>
</jdbc-data-source>
config.xml entry:
<jdbc-system-resource>
<name>newpool</name>
<target>examplesServer</target>
<descriptor-file-name>jdbc/newpool-jdbc.xml</descriptor-file-name>
</jdbc-system-resource> -
Encoding character type in sql server column
Hello,
I am having troubles during REPLACE character in sql server column due to fact that, it seems to me, SQL Server does not recognize two "the same" characters i.e., some of them it translates into another encoding system correctly while, some of
them, keeps untouched, as entered. Obviously, according to my understanding, they "look the same shape" but, obviously, belong to different encoding systems. How to change encoding system for some of them?
Namely, this UPDATE statement:
UPDATE TOP (4000000) tblName
SET FirstName = N'Đ' + SUBSTRING(FirstName, 2, 8000)
WHERE (FirstName LIKE N'Ð%')
works fine for my case but, as you see, it replaces just the first occurrence. Could it be possible to expand this pattern to all occurrences?I'm not sure that I have fully understood what you want to achieve, but it seems that you want to replace occurrances of Latin Captial Letter Edh with Latin Capital Letter D with Stroke, which looks virtually identical in uppercase (but are entirely different
in lowercase). Or vice versa.
Using the glyphs is certainly bound to cause confusion, and I think the best for clarity is to use the nchar function. Or possibly upper in combination with the lowercase glyphs. As for entering the characters, the Character Map utility, which you find in
the folder Accessories/System Tools folder in the Start Menu is useful.
Below is a script that demonstrates the techniques above. You can also see that the characters are considered equal in a accent-insensitive collation. (Well, at least Latin1_General. They are of course unequal in Icelandic and Croatian AI collations.)
CREATE TABLE tblName(FirstName nvarchar(20) NOT NULL)
INSERT tblName(FirstName)
VALUES(upper('eðh'))
SELECT FirstName, lower(FirstName)
FROM tblName
UPDATE dbo.tblName
SET FirstName = REPLACE(FirstName, nchar(208), nchar(272))
WHERE FirstName LIKE N'%' + nchar(208) + '%';
SELECT FirstName, lower(FirstName)
FROM tblName
SELECT CASE WHEN nchar(208) = nchar(272) COLLATE Latin1_General_CI_AI THEN 1 ELSE 0 END AS Equal
go
DROP TABLE tblName
Erland Sommarskog, SQL Server MVP, [email protected] -
Pre-Populating Text fields from a Data drop down list using SQL Server
I'm currently trying to update some of our internal forms which are word based or a basic PDF form you fill in by yourself.
I'm connecting to our SQL server as there are databases stored there for an internal bit of software that hold information
I can use to fill in parts the form.
I have a data drop down list that is dynamically linked to the SQL databass and allows you to select a Project Number from that database, what
I want to do after this is selected is to automatically populate some text fields with the Project name, Account handler and other fields held in the
database.
I've had a look online to see if there is a solution but haven't really found anythig that is similar (although I am new to LC so may have seen it
and not realised) and my Java is non existant.
Has anyone tried this and able to point me in the right directions?
I'm using LiveCycle ES2 version 9.0.0.2 from Creative Suit 5.5 on Windows 7
CheersHi,
Actually this error does not cause any harm except a presentation inconvenience. In my multi-select prompt I am using variable expression with dynamic repository variable. Dashboard results are correct. Just variable's value does not appear on page (error Error Codes: G689FFB3:SDKE4UTF
Expression: @{biServer.variables['CUR_CAL_PER_MONTH_NAME']}). Pushing "GO" button on the prompt fixing the error but it's actually second execution of the dashboard.
Any ideas ?? -
SQL Server 2012 - Dropping Snapshots takes hours
We recently did a SQL Server upgrade from 2005 to 2012. We have a nightly job that drops a snapshot of an active database. The snapshots gets created again later in the day. Before upgrading, in SQL 2005 the Job that drops the snapshots used to finish in few
seconds. But once the server has been upgraded to 2012, the same job takes close to an hour to complete.
The log files for the job contains a message "Nonqualified transactions are being rolled back. Estimated rollback completion: 0%. [SQLSTATE 01000] (Message 5060) Nonqualified transactions are being rolled back. Estimated rollback completion: 100%."
This message is repeated several times. While monitoring the underlying database, we have found some blocking on the database during that time. But if I am correct, a blocking on the underlying database should not delay a statement to drop its snapshot. May
I know if I am correct? If so, what could be the reasons for this delay after upgrading to 2012? Any missing settings at the server or database level? Thanks.Hi, Please check fot eh entire errors from the error log file. the error: "Nonqualified transactions are being rolled back. Estimated rollback completion: 100%." usually come with another statement like "Database 'MyDB' is already
open and can only have one user at a time.", Another option might be right after the message that you post that you get "Cannot open backup device '<some path to a file> Not Found'". In short, we are missing part
of the error massage :-)
In the example above when you see "Database 'MyDB' is already open and can only have one user at a time." then the problem is pretty clear.
Ronen Ariely
[Personal Site] [Blog] [Facebook] -
SQL Server 2014 Snapshot agent duplicating constraints
Hello,
We are upgrading our server from SQL Server 2008 R2 Std. Ed. to SQL Server 2014 Std. Ed.
Our server works with Merge and Transactional publications.
Our current problem happens when trying to generate the first snapshot using the snapshot agent. Since this is the first time, the snapshot will create all the system tables related with replication and the error happens when creating the table MSmerge_conflict_<publication>_<article>
because now the snapshot agent is trying to create the constraints from the <article> (a table in our case) with the same name, so it brings the conflict of having duplicated constraints names and because of that the snapshot agent fails.
This didn't happen on 2008 because the snapshot agent didn't try to create the constraints before.
This is the error that we see on the Snapshot Agent Status: There is already an object named"NewAccountPermission" in the database. Could not create constraint or index. See previous errors.
The exact T-sql statement that is failing is shown on the replication monitor:
Error messages:
Message: There is already an object named 'NewAccountPermission' in the database.
Could not create constraint or index. See previous errors.
Command Text: CREATE TABLE [dbo].[MSmerge_conflict_Roster_AccountPermissions](
[AccountPermissionID] [int] NOT NULL CONSTRAINT [NewAccountPermission] DEFAULT ([dbo].[getNewAccountPermissionID]()),
[PermissionName] [varchar](255) NULL,
[Description] [varchar](255) NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL
Digging a bit further I searched and compared the snapshot files that creates this table. Here it can be seen that the snapshot files only differ on the creation or not of the constraint.
Here is an extract o f the 2014 file called AccountPermissions_3.cft
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MSmerge_conflict_Roster_AccountPermissions](
[AccountPermissionID] [int] NOT NULL CONSTRAINT [NewAccountPermission] DEFAULT ([dbo].[getNewAccountPermissionID]()),
[PermissionName] [varchar](255) NULL,
[Description] [varchar](255) NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL
Here is the 2008 version of the same file:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MSmerge_conflict_Roster_AccountPermissions](
[AccountPermissionID] [int] NOT NULL,
[PermissionName] [varchar](255) NULL,
[Description] [varchar](255) NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL
Any ideas on what is going on? Do I have to configure some properties on the publication now to disallow creating the constraints on the msmerge_conflict table?
Thank you,
Alejandro RiveraHi Hilary,
1) There is an user table called dbo.AccountPermissions. The problem happens when the snapshot agent tries to create MSmerge_conflicts_Roster_AccountPermissions (system table). The database is called Roster.
2) We use the default dbo schema. Here is the create script for that table (just in case):
USE [Roster]
GO
/****** Object: Table [dbo].[AccountPermissions] Script Date: 11/17/2014 7:48:27 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AccountPermissions](
[AccountPermissionID] [int] NOT NULL CONSTRAINT [NewAccountPermission] DEFAULT ([dbo].[getNewAccountPermissionID]()),
[PermissionName] [varchar](255) NULL,
[Description] [varchar](255) NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL CONSTRAINT [MSmerge_df_rowguid_13B9434FF11A44ACB63F5D2927C053FD] DEFAULT (newsequentialid()),
CONSTRAINT [pk_accountpermissions] PRIMARY KEY CLUSTERED
[AccountPermissionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
I'd put a screenshot too, but sadly the forum doesn't allow me until it verifies my account.
Let me know if you any more info.
Thank you, -
4.0 EA3 -- SQL Server Drag and drop still not working
My clients love SQLD D because they can access SQL Server and Access as well as Oracle of course.
Drag and Drop of tables from the table view have not worked in a while.
appear to only see things in the Master Database. Even if you retrieve the list of databases and set you still en up only in the MASTER.
You then have to fully qualify to retrieve a table.What exactly is your question here?
-
Does SQL Server remember dropped databases?
Hi!,
I need to create reports that will tell me the number of databases that are created and dropped across our estate on a daily basis. I don't need to recover the databases, just report their name and the date created & dropped.
Is that info stored in SQL Server anywhere?
Thanks,
ZoeThat information is available in the default trace (if enabled):
http://www.sqlusa.com/bestpractices/default-trace/
https://www.simple-talk.com/sql/performance/the-default-trace-in-sql-server---the-power-of-performance-and-security-auditing/
Kalman Toth Database & OLAP Architect
Free T-SQL Scripts
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
I have migrated my SCCm 2007 environment to SCCM 2012 SP1 CU4.
I noticed in the System Status\Component Status\SMS_STATE_SYSTEM a lot of errors like the one below:
Microsoft SQL Server reported SQL message 2627, severity 14: [23000][2627][Microsoft][SQL Server Native Client 11.0][SQL Server]Violation of PRIMARY KEY constraint 'DeploymentSummary_PK'. Cannot insert duplicate key in object 'dbo.DeploymentSummary'. The duplicate key value is (1, 0, S0220438, 0). : spUpdateClassi
Please refer to your Configuration Manager documentation, SQL Server documentation, or the Microsoft Knowledge Base for further troubleshooting information.
When looking up the deployment ID and recreate the Deployment the problem is solved. But I have 700 packages and don't want to manually do this action on all packages. I think it is related to the migration i did and something went wrong there :-(
Besides it will retriggers the deployment to the clients which is also not preferred.
Is there another way to solve this by e.e.g do something directly in the SQL database tables ?Hi,
It is not supported by Microsoft that do something directly in SQL database.
If you want to do that, you could make a call to CSS.
Best Regards,
Joyce
We
are trying to better understand customer views on social support experience, so your participation in this
interview project would be greatly appreciated if you have time.
Thanks for helping make community forums a great place. -
I am provisioning for automated database schema upgrades in a Windows Forms Application (VS2010/VB) which uses SQL Server Compact 3.5 SP2. A portion of the schema upgrade procedure uses TSQL commands passed to SQLCE like the following:
cmd.CommandText = "DROP INDEX [SaleComps$ProjID]"
cmd.ExecuteNonQuery()
However, when this command is processed by the SQLCE engine, I get the following error:
Command: DROP INDEX [SaleComps].[ProjID]
Error: The specified index does not exist. [ ProjID ]
But, if I try to recreate the index (or try to change the index column) I get the following errors which indicate that the index is still there:
Command: ALTER TABLE [SaleComps] ALTER COLUMN [ProjID] nvarchar(20) NULL
Error: Cannot alter a column that is part of a key or an index. [ Index Name = SaleComps$ProjID,Column = ProjID ]
Command: CREATE INDEX "SaleComps$ProjID" ON "SaleComps" ("ProjID" ASC)
Error: The specified index already exists. [ SaleComps$ProjID ]
Any ideas why this would not be working? Thanks!
-BGoodNo, I was guessing at the syntax from reviewing other web postings, some of which were in different SQL dialects.
While your SQLCE Toolbox did not provide the DROP INDEX command, it did provide most of the "Schema Diff" scripting commands. In hindsight, maybe SQLCE Toolbox should recognize when schema differences involve a Column which is used in an index, and
DROP the index before executing the ALTER COLUMN command, then re-CREATE the index with the modified column.
Despite this shortcoming, I am very thankful for the help provided by SQLCE Toolbox, and learned a little more about SQL scripting in the process.
Thanks, ErikEJ!
-BGood
Maybe you are looking for
-
Mail - Empty PDF Attachments when moved from 'Junk' (Hotmail)
Hi I've been using Mail with Hotmail (IMAP) for some time; a recent update resolved the constant errors you'd get when deleting or moving emails between folders. However, if I receive a PDF attachement from an unknown sender, this goes into Junk.. I
-
Removing mail for exchange but keeping contacts
Is there any way to remove my Mail for Exchange account, but keep the contacts? Everytime I remove the mail for exchange account, the contacts get deleted, but I want them to stay on the phone. If not, I have VCards of the contacts, can I import thos
-
Gc_analyze.pl errors using JDK 1.4.1_01
There seem to be 2 versions of the perl script gc_analyze.pl; http://wireless.java.sun.com/midp/articles/garbage/gc_analyze.pl http://wireless.java.sun.com/midp/articles/garbagecollection2/gc_analyze.pl I have tried both and had no success, one has i
-
I would like the users to hold the mouse on a component such as a label with an icon. Then i would like him to be able to drag the actual label around on the screen and register where he drops it and what label it is? A tutorial would be best if posi
-
CS3 will not print color pictures
Photo Shop will not print color pictures. It printed fine for over a year then just quit printing in color a few months ago. A work around was given by our Higher head Quarters but when printing this way the pictures do not print properly and the pi