Combine "delete query" - sql

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

Related

My INSERT statement conflicted with the FOREIGN KEY constraint

enter image description here
Those are my diagrams - I create procedure
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[hasta]
#Ad nchar(50),
#Soyadı nvarchar(100),
#TcKimlik nchar(11),
#DogumTarihi varchar(8),
#TelefonNo nvarchar(11)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].Hastalar ([Ad], [Soyadı], [TcKimlik], [DogumTarihi], [TelefonNo])
VALUES (#Ad, #Soyadı, #TcKimlik, #DogumTarihi, #TelefonNo)
END
After I want add data in Hastalar table, I write
exec hasta 'Emir','Yılmaz','35635993564','1995.11.19','05347331085'
but I get this error
Msg 547, Level 16, State 0, Procedure hasta, Line 13
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Hastalar_Testler". The conflict occurred in database "hastane", table "dbo.Testler", column 'TestID'. The statement has been terminated.
In your table [dbo].Hastalar, it has a foreign key reference to another table. The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table.
If you have SQL Server Management Studio, open it up and sp_help '[dbo].Hastalar'. See which column that FK is on, and which column of which table it references. You're inserting some bad data.
What part of the error do you not understand?
The message is saying that one of the columns -- "TestId" -- is referring to another table. And the value being inserted is not already in that table.
You are not explicitly inserting a value for TestId, so that value is being set using a default constraint or trigger. I would suggest that you explicit provide the value in the insert -- even if that value is NULL.

SQL query not executing as whole

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

SQL Server 2008 Script to Drop PK Constraint that has a System Generated Name

I am trying to add a clustered index to an existing table in SQL Server 2008, and it needs to be an automated script, because this table exists on several databases across several servers.
In order to add a clustered index I need to remove the PK constraint on the table, and then re-add it as unclustered. The problem is the name of the PK constraint is auto-generated, and there is a guid appended to the end, so it's like "PK_[Table]_D9F9203400."
The name is different across all databases, and I'm not sure how to write an automated script that drops a PK constraint on a table in which I don't know the name of the constraint. Any help is appreciated!
UPDATE:
Answer below is what I used. Full script:
Declare #Val varchar(100)
Declare #Cmd varchar(1000)
Set #Val = (
select name
from sysobjects
where xtype = 'PK'
and parent_obj = (object_id('[Schema].[Table]'))
)
Set #Cmd = 'ALTER TABLE [Table] DROP CONSTRAINT ' + #Val
Exec (#Cmd)
GO
ALTER TABLE [Table] ADD CONSTRAINT PK_Table
PRIMARY KEY NONCLUSTERED (TableId)
GO
CREATE UNIQUE CLUSTERED INDEX IX_Table_Column
ON Table (Column)
GO
You can look up the name of the constraint and write a bit of dynamic SQL to handle the drop.
SELECT name
FROM sys.key_constraints
WHERE parent_object_id = object_id('YourSchemaName.YourTableName')
AND type = 'PK';

Syntax error in stored procedure

I am trying to write one small stored procedure to clean up database programmatically.
For this,
First, I am dropping all Foreign key constraints
Second, I am dropping all primary key constraints,
Third, I am dropping all the tables.
I have written the following code to do above three steps (third step not yet started)
CREATE PROCEDURE usp_CleanupDB AS
BEGIN
--Begin: Code to drop FOREIGN KEY CONSTRAINTS in the database
DECLARE #ForeignKeyConstraint AS VARCHAR(100)
DECLARE #ForeignKeyContainedTableName AS VARCHAR(100)
DECLARE #ForeignKeyConstraintsTableCursor AS CURSOR
SET #ForeignKeyConstraintsTableCursor = CURSOR FOR
SELECT ForeignKeyName, TableName FROM dbo.GetDBForeignKeyConstraints()
OPEN #ForeignKeyConstraintsTableCursor
FETCH NEXT FROM #ForeignKeyConstraintsTableCursor INTO #ForeignKeyConstraint, #ForeignKeyContainedTableName
WHILE ##FETCH_STATUS = 0
BEGIN
--Drop FOREIGN KEY Constraint
ALTER TABLE #ForeignKeyContainedTableName DROP CONSTRAINT #ForeignKeyConstraint
FETCH NEXT FROM #ForeignKeyConstraintsTableCursor into #ForeignKeyConstraint, #ForeignKeyContainedTableName
END
CLOSE #ForeignKeyConstraintsTableCursor
DEALLOCATE #ForeignKeyConstraintsTableCursor
--End: Code to drop FOREIGN KEY CONSTRAINTS in the database
--Begin: Code to drop PRIMARY KEY CONSTRAINTS in the database
DECLARE #PrimaryKeyConstraint AS VARCHAR(100)
DECLARE #PrimaryKeyContainedTableName AS VARCHAR(100)
DECLARE #PrimaryKeyConstraintsTableCursor AS CURSOR
SET #PrimaryKeyConstraintsTableCursor = CURSOR FOR
SELECT PrimaryKeyName, TableName FROM dbo.GetDBPrimaryKeyConstraints()
OPEN #PrimaryKeyConstraintsTableCursor
FETCH NEXT FROM #PrimaryKeyConstraintsTableCursor INTO #PrimaryKeyConstraint, #PrimaryKeyContainedTableName
WHILE ##FETCH_STATUS = 0
BEGIN
--Drop PRIMARY KEY Constraint
ALTER TABLE #PrimaryKeyContainedTableName DROP CONSTRAINT #PrimaryKeyConstraint
FETCH NEXT FROM #PrimaryKeyConstraintsTableCursor INTO #PrimaryKeyConstraint, #PrimaryKeyContainedTableName
END
--End: Code to drop PRIMARY KEY CONSTRAINTS in the database
END
I am getting the following error:
Msg 102, Level 15, State 1, Procedure usp_CleanupDB, Line 15
Incorrect syntax near '#ForeignKeyContainedTableName'.
Msg 102, Level 15, State 1, Procedure usp_CleanupDB, Line 33
Incorrect syntax near '#PrimaryKeyContainedTableName'.
Can anybody please tell how to solve the problem?
You can't use variables for object names in DDL commands like ALTER TABLE.
Would you please use below way, also declare your variable at the top so that each variable is available to everywhere.
EXECUTE('ALTER TABLE ' + #PrimaryKeyContainedTableName + ' DROP CONSTRAINT '+ #PrimaryKeyConstraint)

A stored proc to copy table data including any default value or binding data via a SQL script running within SQL Server

I would like to be able to copy a table and it's data and also still have any default value or binding (as it is labelled within SQL Server Management console) constraints copied over.
The script below is a testing script to demonstrate the idea. The last line I assume needs to be replaced with a call to a custom stored proc?
Note: The source table (aSourceTbl) schema varies and can change over time.
--TEST SETUP
--Delete the prev tables so test script can be replayed
IF OBJECT_ID('aSourceTbl', 'U') IS NOT NULL
DROP TABLE aSourceTbl;
IF OBJECT_ID('aSourceCopyTbl', 'U') IS NOT NULL
DROP TABLE aSourceCopyTbl;
--Simple table to demonstrate table copying does not carry over the table constraits
CREATE TABLE [dbo].[aSourceTbl](
[aValue] [int] NOT NULL,
[DELETED] [int] NOT NULL
) ON [PRIMARY]
--Add some dummy data
INSERT INTO aSourceTbl (aValue, DELETED) VALUES (1,2);
INSERT INTO aSourceTbl (aValue, DELETED) VALUES (3,4);
--Add constraints of default values of 0 in this case
ALTER TABLE [dbo].[aSourceTbl] ADD CONSTRAINT [DF_aSourceTbl_aValue] DEFAULT ((0)) FOR [aValue]
ALTER TABLE [dbo].[aSourceTbl] ADD CONSTRAINT [DF_aSourceTbl_DELETED] DEFAULT ((0)) FOR [DELETED]
--Actual Required SQL script from here down
--The line below works nicely but does not copy the 2 constraints from the lines above into the new table.
--TODO QUESTION: Replace line below with the same functionaility + the constraints are also copied into new table
Select * INTO aSourceCopyTbl FROM aSourceTbl
Could you please help me by suggesting a suitable stored proc that can replace the last line in above SQL snippet? Any help greatly appreciated :)
References:
Similar SO Question however focuses on PK constraints. I am only interested in default value constraints in this case.
You can execute this code after the last row which will replicate the defauld constraints to the new table (replace the variables with your table names).
declare #table_name sysname, #new_table sysname, #cmd varchar(max)
select #table_name = 'SOURCE_TABLE', #cmd = '', #new_table = 'TEST_TABLE'
select #cmd = #cmd+'ALTER TABLE '+#new_table+' ADD CONSTRAINT [DF_' +#new_table+'_'+a.name+'] DEFAULT '+b.definition+' FOR['+a.name+'];
'
from sys.columns a
join sys.default_constraints b on a.object_id = b.parent_object_id and a.column_id = b.parent_column_id
where a.object_id = object_id(#table_name)
print #cmd
exec (#cmd)