Skip to main content

Posts

Showing posts with the label script

Scripting ALL ForeignKeys At Once!

I have a pretty extensive ETL in place involving a ton of tables. To improve performance and keep the transaction log clean, I recently decided to TRUNCATE a bunch of tables instead of DELETE. Unfortunately, Now, I was unable to truncate data as these tables are a part of foreign key based referential integrity in MS SQL. No love lost. I started scripting one FK at a time and saving them in two separate files, DROP_FK.sql and RECREATE_FK.sql. After doing about five of them at 11pm, I realized that this was going to be a painful task. A light bulb went off - why not use the system tables; they surely have all of this information stored somewhere! After a bit of research, I came up with the below query. There are many other queries (probably more robust than mine) out there on the interwebs! Please do your research. Without further ado, here is my query. Database: any Tables: sys.tables       sys.schemas       sys.foreign_keys     ...

SQL 2005 - Easiest Way To Convert CSV To Table

Here is a function that will easily let you convert from a CSV (you can modify it to be ;sv or -sv... you get the idea!) to a Table using SQL's Table-valued Functions. SQL Function: set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go CREATE FUNCTION [dbo].[charlist_to_table] (@list ntext, @delimiter char(1) = N',') RETURNS @tbl TABLE (listpos int IDENTITY(1, 1) NOT NULL, str varchar(4000), nstr varchar(2000)) AS BEGIN DECLARE @pos int, @textpos int, @chunklen smallint, @tmpstr varchar(4000), @leftover varchar(4000), @tmpval varchar(4000) SET @textpos = 1 SET @leftover = '' WHILE @textpos BEGIN SET @chunklen = 4000 - datalength(@leftover) / 2 SET @tmpstr = @leftover + substring(@list, @textpos, @chunklen) SET @textpos = @textpos + @chunklen SET @pos = charindex(@delimiter, @tmpstr) WHILE @pos > 0 BEGIN SET @tmpval = ltrim(rtrim(left(@tmpstr, @pos - 1))) INSERT @tbl (str, nstr) VALUES(@tmpval, @tmpval) SET @tmpstr = substring(@tmpstr, @pos + 1, len(@tmpstr)) SET @pos = c...