I'm starting a new SQL Server Azure DB from scratch. I want to establish a strong source control so I want to be careful in how I create all my tables.
What is the best method to check if the table exists and only execute my CREATE TABLE statement if it does not exist yet? I'm working with passing dynamic SQL to a stored procedure that checks for the tables existence, but that is so limiting. There has to be a preferred way to do this out there. I mean I could preface every query with:
IF NOT EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].j[myTable]') AND type in(N'U'))
BEGIN
CREATE TABLE myTable(....)
END
But that's pretty repetitive.
More simply:
IF NOT EXISTS (SELECT * FROM sys.tables WHERE Name = N'myTable')
CREATE TABLE myTable .......
Idea: use the more focused sys.tables catalog view, instead of the all-encompassing sys.objects - then you don't have to remember those rather unintuitive type values..... - but yes, that is the safest way to do this kind of code.
As of SQL Server 2016, you can also use the
DROP TABLE IF EXISTS myTable;
CREATE TABLE myTable .......
command (which is new - see here: https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/)
Related
In MySQL you can do SELECT CREATE TABLE .... and it will return the CREATE statement that was used to create this table. I need to do the same in SQL Server.
Is there any similar functionality in SQL Server? I have a table name test_table.
I need to run a SELECT statement that would return the CREATE TABLE string that was used to create this table. I tried this but it didn't work. How can I achieve this result in SQL Server?
You could try SELECT INTO and specify the name of a temporary table (prefixed with #). It also works with physical tables (although I've not found a use for this). Something like this
select '123' as colName into #newTable;
select * from #newTable;
colName
123
If I create a view such as:
create view View1 as
select Table1.Column1 from Table1
Is there a way to find Table1 given only the name View1. It's easy enough to find the columns within View1 by querying sys.columns where the object_id is equal to the object_id of the view name from sys.objects but how can you tell what is the underlying table that the column within the view came from?
Execute sp_describe_first_result_set with #browse_information_mode = 1. This will return a result set with the underlying table name and column name of each view column along with other meta-data. Source information will be NULL for view columns derived from expressions but other meta-data (e.g. data type information) will be included.
EXEC sp_describe_first_result_set
#tsql=N'SELECT * FROM dbo.YourView;'
, #params = NULL
, #browse_information_mode = 1;
Note that sp_describe_first_result_set was introduced in SQL Server 2012 so this will not work in prior versions of SQL Server.
I need to create a temp table (which is a copy of Employees table) in a SQLite database, provided the table by the name of 'Employees' exists. There are only 2 columns in Employees table - EmployeeId (integer) and EmployeeName (varchar(100)).
Is there any way to implement the above using SQLite SQL?
Pseudo-code for intended SQL, which does not work in SQlite is as below. I hope there was something as powerful as the pseudo-code below in SQLite.
--if Employees table exists then create a temp table and populate it with all
--rows from Employees table
CREATE TEMP TABLE tempEmployees if exists Employees as select * from Employees;
SQLite has almost no control logic; as an embedded database, it is designed to be used together with a 'real' programming language.
You could just try to copy the data, and ignore the errors:
try:
c.execute("CREATE TEMP TABLE tempEmployees AS SELECT * FROM Employees")
except:
pass
However, this would also suppress any other errors.
A better idea is to check explicitly whether the table exists:
c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Employees'")
if c.fetchone():
c.execute("CREATE TEMP TABLE tempEmployees AS SELECT * FROM Employees")
I've been using the entities framework with ASP.NET MVC and I'm looking for an easy and fast way to drop all of the information in the database. It takes quite a while to delete all of the information from the entities object and then save the changes to the database (probably because there are a lot of many-to-many relationships) and I think it should be really fast to just remove all of the information with a stored procedure but I'm not sure how to go about this. How do I create and use a stored procedure for SQL-Sever which will delete the data in all tables in a database with VS 2010? Also if I do this will the command be compatible with other version of SQL-Server? (I'm using 2008 on my testing comptuer, but when I upload it I not sure if my hosting company uses 2008 or 2005).
Thanks!!
This solution will work well in terms of deleting all your data in your database's tables.
You can create this stored proc right within Visual Studio on your SQL Server 2008 development server. It'll work well in any version of SQL Server (2000+).
CREATE PROC NukeMyDatabase
AS
--order is important here. delete data in FK'd tables first.
DELETE Foo
DELETE Bar
TRUNCATE TABLE Baz
I prefer TRUNCATE TABLE, as it's faster. It'll depend on your data model, as you can't issue a TRUNCATE TABLE on a table referenced by a foreign key constraint (i.e. parent tables).
You could then call this stored proc using Entity Framework after adding it to your .edmx:
myContext.NukeMyDatabase();
I recently faced a similar problem in that I had to clear over 200+ tables that were interlinked through many foreign key constraints.
The critical issue, as p.campbell pointed out, is determining the correct order of DELETE statements.
The foreign key constraints between tables essentially represent a hierarchy. If table 3 is dependent on table 2, and table 2 is dependent on table 1, then table 1 is the root and table 3 is the leaf.
In other words, if your going to delete from these three tables, you have to start with the table that has no dependencies and work your way up. That is the intent of this code:
DECLARE #sql VARCHAR(MAX)
SET #sql = ''
;WITH c AS
(
SELECT
parent_object_id AS org_child,
parent_object_id,
referenced_object_id,
1 AS Depth
FROM sys.foreign_keys
UNION ALL
SELECT
c.org_child,
k.parent_object_id,
k.referenced_object_id,
Depth + 1
FROM c
INNER JOIN sys.foreign_keys k
ON c.referenced_object_id = k.parent_object_id
WHERE c.parent_object_id != k.referenced_object_id
),
c2 AS (
SELECT
OBJECT_NAME(org_child) AS ObjectName,
MAX(Depth) AS Depth
FROM c
GROUP BY org_child
UNION ALL
SELECT
OBJECT_NAME(object_id),
0 AS Depth
FROM sys.objects o
LEFT OUTER JOIN c
ON o.object_id = c.org_child
WHERE c.org_child IS NULL
AND o.type = 'U'
)
SELECT #sql = #sql + 'DELETE FROM ' + CAST(ObjectName AS VARCHAR(100))
+ ';' + CHAR(13) + CHAR(10) /** for readability in PRINT statement */
FROM c2
ORDER BY Depth DESC
PRINT #sql
/** EXEC (#sql) **/
exec sp_MSForEachTable 'truncate table ?';
But I would recommend a different approach: take a backup of the empty database and simply restore this backup before each run. Even better, have no database at all and have your application be capable of deploying the database itself, using a schema version upgrade set of scripts.
How would I figure out what type of sql code such as procs, functions, views etc. are interacting with my table called TABLE1 through out a given database. Sample code would be very helpful for me.
thanks
select so.name, so.xtype
from sysobjects so (nolock)
inner join syscomments sc (nolock) on sc.id = so.id
where sc.text like '%tablename%'
This code will search all SQL Server objects for a reference to your table. You have to run this query for each database.
If a stored procedure uses your table it will appear in this query. The same is true of functions, views, and triggers.
xtype tells you the type of object.
Here are the possible xtype values:
D = Field names
F = Foreign Key
FN = Function
P = Stored Procedures
PK = Primary Key
S = System Tables
U = User tables
V = Hidden tables
Not enough info in your question, but one thing you can do is use SQL Profiler to profile where INSERTs, UPDATEs, and DELETEs are coming from.
I assume you are talking about how an app is interacting with data and what name (of say a sproc) is doing the insert / update / delete.
Look at SQL Profiler, it comes with your client tools install. Filter it to only show connections to your database (either db name or ID).
If you've been good and created your SPs/views/functions after your table was created, sp_depends will tell you evertyhing referencing the table. Exept for dynamic sql that is.