The command EXEC sp_msforeachtable 'TRUNCATE TABLE ?' returns the following error:
The EXEC SQL construct or statement is not supported.
I execute the query like this:
Question
How do I erase all data, but keep existing tables, relationships, keys, and indexes settings?
Turn off all constraints, delete all records, turn constraints back on:
EXEC sp_MSForEachTable ‘ALTER TABLE ? NOCHECK CONSTRAINT ALL’
GO
EXEC sp_MSForEachTable ‘DELETE FROM ?’
GO
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL';
GO
Related
So I have a query that should add Primary Key to the Id field:
IF NOT EXISTS(SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'CAL')
BEGIN
DROP INDEX IF EXISTS CAL$01 ON dbo.CAL;
ALTER TABLE BTS.dbo.CAL
ALTER COLUMN Intern INT NOT NULL;
ALTER TABLE BTS.dbo.CAL
ADD CONSTRAINT PK_CAL_Intern PRIMARY KEY (Intern);
CREATE INDEX CAL$01
ON CAL (Intern);
END
The problem is that when I chose all this code and execute (F5), I get this error:
Whereas when I'm choosing every statement one by one it works as expected:
I am sure that the IF works as expected
I tried to use GO between statements, it's not allowed.
I should execute this code on a large number of tables
Maybe I don't know something about how SQL Server Management Studio executes statements
Before a query is run it is parsed. This is why what you're doing is failing. SQL server is checking the details of the Intern before the script is run. At the point you start to try to run the script, Intern in the table BTS.dbo.CAL is NULLable, and so the script fails.
You can get around this by running the statement to create the primary key cosntraint in a separate scope:
IF NOT EXISTS(
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'CAL'
)
BEGIN
DROP INDEX IF EXISTS CAL$01 ON dbo.CAL;
ALTER TABLE
BTS.dbo.CAL
ALTER COLUMN
Intern
INT NOT NULL;
EXEC sys.sp_executesql N'ALTER TABLE BTS.dbo.CAL ADD CONSTRAINT PK_CAL_Intern PRIMARY KEY (Intern);';
CREATE INDEX [CAL$01]
ON CAL (Intern);
END'
Even though question is answer, I just wanted to add one more option.
You can separate statments into two separate batches, so that your change is available to the subsequent batch
CREATE TABLE #test(a int null);
-- DDL Changes
if exists(SELECT 1)
BEGIN
ALTER TABLE #test ALTER COLUMN a int not null;
END
GO
-- Index changes
if exists(SELECT 1)
BEGIN
ALTER TABLE #test ADD CONSTRAINT PK_test PRIMARY KEY(a)
END
GO
I am getting the error in my sproc and I cannot figure out why. I have looked at other, almost identical questions like this Here and the answers aren't doing the trick for me. the syntax error is at the 'Go' right after the database creation.
USE [DATABASENAME]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Sproc]
#Id int
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name =
N'Name')
create database Name;
GO
CREATE TABLE [Name].[dbo].[Account](
[Id] [int] IDENTITY(1,1) NOT NULL,
[AccountId] [int] NOT NULL
);
GO is not allowed in stored procedures. It separates batches and a procedure itself is one batch which cannot be separated.
You could use one procedure to create the database, then a second procedure to create the table.
Edit
Actually you could do it in one procedure:
CREATE PROCEDURE [dbo].[Sproc]
AS
BEGIN
EXEC ('USE [Master]; CREATE DATABASE [name]')
EXEC ('USE [Name]; CREATE TABLE [name].dbo.[Account] (id int)')
END
I'm making a stored procedure but the query doesn't work.
create proc deleteUser
#username varchar(50)
as
begin
DECLARE #sql NVARCHAR(MAX) = 'delete from lars.userInformation where username='+#username;
'delete from lars.userAcces where username='+#username
EXEC sp_executeSQL #sql,N'
#username
',#username
end
How could I do this without using joins?
You don't need dynamic sql:
create proc deleteUser
#username varchar(50)
as
begin
delete from lars.userInformation where username=#username;
delete from lars.userAcces where username=#username;
end
Why do you need to use the EXEC statement. Can you not just perform the DELETE statements directly, preferably using a TRANSACTION?
The optimum solution is to add a constraint to the table so when the parent record is deleted, child records are automatically deleted.
This will ensure the data has integrity no matter how the parent row is deleted.
Example:
-- foreign key constraint
ALTER TABLE [dbo].[OrderDetail] WITH CHECK
ADD CONSTRAINT [FK_OrderDetail_Order] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Order] ([OrderID])
ON DELETE CASCADE
There are ten entries in the table and primary key id is set to autoincrement. If I delete all entries and insert one more its id will be 11, is it possible to reset ids to 1 again?
Try truncate table command like below :
TRUNCATE TABLE tablename
it will reset auto increment id to 1.
If your table is refrenced with other table using foreign key then you can enable/disable contraint using below commands :
To Enable constraint:
EXEC sp_msforeachtable #command1="print '?'",
#command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all";
To Disable constraint:
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all";
DBCC CHECKIDENT("table", RESEED, 1);
You can read more at msdn, DBCC CHECKIDENT (Transact-SQL).
ALTER TABLE table AUTO_INCREMENT = 1;
You can set any value for "1"
How do I drop all foreign-key constraints on a table in SQL Server 2000 using T-SQL?
If simply disabling constraints is an option here, you can use:
ALTER TABLE myTable NOCHECK CONSTRAINT all
then you can switch them back on simply using:
ALTER TABLE myTable WITH CHECK CHECK CONSTRAINT all
If you want to disable constrains in all tables you can use:
-- disable all constraints
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
-- enable all constraints
exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
More in the question: Can foreign key constraints be
temporarily disabled using TSQL?
But if you need to drop constraints permanently you can use this script posted on databasejurnal.com.
Just modify it slightly to only drop the foreign keys
create proc sp_drop_fk_constraints
#tablename sysname
as
-- credit to: douglas bass
set nocount on
declare #constname sysname,
#cmd varchar(1024)
declare curs_constraints cursor for
select name
from sysobjects
where xtype in ('F')
and (status & 64) = 0
and parent_obj = object_id(#tablename)
open curs_constraints
fetch next from curs_constraints into #constname
while (##fetch_status = 0)
begin
select #cmd = 'ALTER TABLE ' + #tablename + ' DROP CONSTRAINT ' + #constname
exec(#cmd)
fetch next from curs_constraints into #constname
end
close curs_constraints
deallocate curs_constraints
return 0
Here you go: (not tested on SQL2000, but should be ok)
Generates 'disables':
SELECT 'IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N''[dbo].' + FK +''')
AND parent_object_id = OBJECT_ID(N''[dbo].' + PT + '''))
ALTER TABLE ' + PT + ' NOCHECK CONSTRAINT ' + FK + ';'
FROM
(SELECT
OBJECT_NAME(constraint_object_id) as FK,
OBJECT_NAME(parent_object_id) as PT
FROM [sys].[foreign_key_columns] ) T
ORDER BY FK
Generates 'enables':
SELECT 'ALTER TABLE ' + PT + ' WITH CHECK CHECK CONSTRAINT ' + FK + ';'
FROM
(SELECT
OBJECT_NAME(constraint_object_id) as FK,
OBJECT_NAME(parent_object_id) as PT
FROM [sys].[foreign_key_columns] ) T
ORDER BY FK
Update: Oops, I thought you wanted it for all tables :) You can just modify above for your single table.
I think you'll find that there is no easy way to drop constraints on a table in SQL Server 2000. That said, there are plenty of people who have written scripts that can identify and remove/disable/recreate foreign key constraints. One example is at http://www.mssqltips.com/tip.asp?tip=1376 - but I haven't tested it on SQL Server 2000.
EDIT: Here is another example that generates drop/create scripts for you.