cjhaas.com Basically a place that Chris can post solutions to problems so he can easily find them later

November 6, 2010

Generate INSERT statements from SQL Server

Filed under: Uncategorized — Tags: , — Chris Haas @ 5:23 pm

The original version of this code comes from here. That version, however, didn’t handle NULLs and just inserted empty strings or zeros. In the comments there was an updated version by spider_pat that supported NULL values but had a couple of problems, namely it only had one column to INSERT into (due to placing code inside of a loop instead of outside) and it didn’t enclose columns in brackets. The first was really easy to fix and the second most people probably don’t care about unless you have some system that automatically creates table names and you can’t rename them. Also, I took a little bit of time to clean up the code to make it more readable. Yes, I removed BEGIN/END blocks from single-statement IFs which I generally recommend against but this made it much easier to read.

CREATE PROC InsertGenerator
(
@tableName varchar(100)
)
AS
/*
Code from  http://www.codeproject.com/KB/database/InsertGeneratorPack.aspx
*/
--Declare a  cursor to retrieve column specific information for the specified table
DECLARE cursCol CURSOR FAST_FORWARD FOR
SELECT column_name,data_type,table_schema FROM information_schema.columns WHERE table_name = @tableName
OPEN cursCol
DECLARE @string         nvarchar(max) --for storing the first  half of INSERT statement
DECLARE @stringData     nvarchar(max) --for storing the data  (VALUES) related statement
DECLARE @dataType nvarchar(max) --data types returned for  respective columns
DECLARE @schemaType     nvarchar(max) --table schema value for  correct schema execution
SET @stringData=''
DECLARE @colName nvarchar(max)
FETCH NEXT FROM cursCol INTO @colName, @dataType, @schemaType
IF @@fetch_status<>0
BEGIN
      PRINT 'Table  '+@tableName+' not found, processing skipped.'
      CLOSE curscol
      DEALLOCATE curscol
      RETURN
END
SET @string='INSERT ['+@schemaType+'].['+@tableName+']('
WHILE @@FETCH_STATUS=0
BEGIN
      IF @dataType in ('varchar','char','nchar','nvarchar')
            SET @stringData = @stringData + ''''' + ISNULL('''''''' + REPLACE([' + @colName + '],'''''''','''''''''''') + '''''''', ''NULL'') + '',''+'
      ELSE IF @dataType in ('text','ntext')
            SET @stringData = @stringData + '''''''''+ISNULL(cast([' + @colName + '] as  varChar(max)),'''')+'''''',''+'
      ELSE IF @dataType = 'money'
            SET @stringData = @stringData+'''CONVERT(money,''''''+ISNULL(CAST([' + @colName + '] as varChar(max)),''0.0000'')+''''''),''+'
      ELSE IF @dataType='datetime'
            SET @stringData = @stringData + '''CONVERT(datetime,' + '''+ISNULL(''''' + '''''+CONVERT(varChar(max),[' + @colName + '],121)+''''' + ''''',''NULL'')+'',121),''+'
      ELSE IF @dataType='image'
            SET @stringData = @stringData + '''''''''+ISNULL(CAST(CONVERT(varBinary,[' + @colName + ']) as varChar(6)),''0'')+'''''',''+'
      ELSE
            SET @stringData = @stringData + '''' + '''+ISNULL(''''' + '''''+CONVERT(varChar(max),[' + @colName + '])+''''' + ''''',''NULL'')+'',''+'
      SET @string=@string + '[' + REPLACE(@colName,'''','''''') + '],'
      FETCH NEXT FROM cursCol INTO @colName,@dataType,@schemaType
END
DECLARE @Query nvarchar(4000)
SET @query ='SELECT '''+substring(@string,0,len(@string)) + ') VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' FROM '+@schemaType+'.'+@tableName
PRINT @query
EXEC sp_executesql @query
--select @query
CLOSE cursCol
DEALLOCATE cursCol
GO

UPDATE 12/21/2010

Fixed a bug where content with single quotes was breaking.

August 6, 2010

SQL Server 2008 Express Asymmetric Encryption

Filed under: Uncategorized — Tags: , , — Chris Haas @ 2:54 pm

First off, if you’ve got SQL Server 2008 Enterprise Edition I’d recommend that you look at TDE. SQL Server 2008 Express Edition doesn’t support TDE so instead we need to find another way to encrypt our data. The method that I’m talking about here is asymmetric encryption using a password (instead of certificate). I’m just going to drop the code below any maybe elaborate at a later date.

UPDATED 2010-08-09
Found a slight problem, my original code worked great in the Management Studio but failed on the web with a Cannot insert NULL message. The problem was that the user that the user account listed in my web.config didn’t have permission to access the private key. The solution was simple, just GRANT that CONTROL permission on they key. The code below reflects this. I’m not 100% sure that there isn’t a permission with less privileges than CONTROL but it does work at least.

--Create a test database
CREATE DATABASE [Test]
GO

--Select the test database
USE [Test]
GO

--Create the database master key
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'really awesome password here'
GO

--Create a single asymmetric key, this password is one that we're going to be using later actually
CREATE ASYMMETRIC KEY KEY_SuperAwesomeKey WITH ALGORITHM = RSA_2048 ENCRYPTION BY PASSWORD = N'some other really awesome password'
GO

--Give the user account "YourUserAccountHere" permission to use the key
GRANT CONTROL ON ASYMMETRIC KEY::[KEY_SuperAwesomeKey] TO YourUserAccountHere

--Create a test table.
--Very important, the encryption and decryption functions max out at 8000 bytes
CREATE TABLE SampleTable
(
PlainText varChar(8000),
EncText varBinary(8000)
)
GO

DECLARE @PlainText varChar(8000)
DECLARE @EncText varBinary(8000)

--Plain text variable
SET @PlainText	= 'Hello world'
--EncryptByAsymKey(KeyId, PlainText), use AsymKey_Id(KeyName) to find the Id of the key
SET @EncText	= ENCRYPTBYASYMKEY(ASYMKEY_ID('KEY_SuperAwesomeKey'), @PlainText)

--Insert into our table
INSERT INTO SampleTable (PlainText, EncText) VALUES (@PlainText, @EncText)

--Show what the encrypted form looks like
SELECT * FROM SampleTable

--DecryptByAsymKey(KeyId, EncryptedText, AsymetricKeyPassword), returns byte array that needs to be re-cast to original type
--Also, very important, the password MUST be passed in as nvarchar
SELECT *, CONVERT(varchar, DECRYPTBYASYMKEY(ASYMKEY_ID('KEY_SuperAwesomeKey'), EncText, N'some other really awesome password')) FROM SampleTable

Powered by WordPress