Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem Importing data with imbedded single quotes.

Status
Not open for further replies.

LeonAtRC

Programmer
Nov 25, 2002
101
US
Here is the actual code I'm running to copy data from one set of tables to another. The table structures are identical.
Code:
SET @runCmd = 'INSERT INTO dbo.' + @dbTable + ' (' + @fldList + ') SELECT ' + @fldList + ' FROM dbo.' + @tmpTable
EXECUTE (@runCmd)
@dbTable is the new table
@fldList is the list of fields
@tmpTable is the old table.

I'm getting errors because of apostophes in the data.
This is the code used to build the field list:
Code:
SET @fldList = ''
WHILE (@@FETCH_STATUS = 0)
	BEGIN
		SET @fldList = @fldList +'['+ @colName+']' + ','
		FETCH NEXT FROM cols INTO @colName
	END
SET @fldList = LEFT(@fldList,LEN(@fldList)-1)
 
To accommodate single quotes, you need to double them. This means you'll need to create 2 separate field lists.

Code:
SET @ColumnList = ''
Set @DataList = ''

WHILE (@@FETCH_STATUS = 0)
    BEGIN
        SET @ColumnList = @ColumnList +'['+ @colName+']' + ','
        SET @DataList = @DataList + 'Replace([' + @colName + '], '''''',''''),'
        FETCH NEXT FROM cols INTO @colName
    END
SET @ColumnList = LEFT(@ColumnList ,LEN(@ColumnList )-1)
SET @DataList = LEFT(@DataList ,LEN(@DataList )-1)

And then....

Code:
SET @runCmd = 'INSERT INTO dbo.' + @dbTable + ' (' + @ColumnList + ') SELECT ' + @DataList + ' FROM dbo.' + @tmpTable
EXECUTE (@runCmd)

-George
Microsoft SQL Server MVP
My Blogs
SQLCop
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top