Solved

SQL Exec Dynamic Insert Statement Error on Commas?

Posted on 2014-01-22
5
390 Views
Last Modified: 2014-01-23
I'm not sure if this is possible, but I need to build an Insert statement with added variable column names. I'm testing with only one column name here. I get this error message but don't see how the commas are the problem. Help!

 Error: " Incorrect syntax near ',' "

Declare @Columns    varchar(30) = '[Test - Column]';
Declare @State           varchar(10) = 'NV';
Declare @ListName   varchar(10) = 'List1';
Declare @Updated    datetime = null;
Declare @Price           decimal(18,2) = 2.00;

Exec('Insert Into dbo.MyInsertTest ( [State], ListName, Updated,' + @Columns +')
 	Values(' + @State + ', ' + @ListName + ', ' + @Updated + ',' + @Price);

Open in new window

0
Comment
Question by:WorknHardr
  • 2
  • 2
5 Comments
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 200 total points
ID: 39801968
The varchar values need to be enclosed in quotes in the resulting sql string to be executed. Date field's a bit tricky. It usually helps to build a string and display it first.
Declare @sql varchar(max) = 'Insert Into dbo.MyInsertTest ( [State], ListName, Updated,' + @Columns +')
	Values(''' + @State + ''', ''' + @ListName + ''', ' + 
	case when @Updated is null then 'null' else '''' + convert(varchar, @updated, 126) + '''' end + ', ' + 
	convert(varchar, @Price) + ')';

print @sql;

Exec(@sql);

Open in new window

0
 
LVL 3

Assisted Solution

by:smilieface
smilieface earned 200 total points
ID: 39801996
Try this.

When concatenating strings you have to convert the data types explicitly.

This will also handle putting NULL in the date properly, but not for any other column.

Declare @Columns    varchar(30) = '[Test - Column]';
Declare @State      varchar(10) = 'NV';
Declare @ListName   varchar(10) = 'List1';
Declare @Updated    datetime    = NULL;
Declare @Price      decimal(18,2) = 2.00;

DECLARE @Cmd        varchar(max)

SET @Cmd = 'Insert Into dbo.MyInsertTest ( [State], ListName, Updated,' + @Columns 
   + ') Values(''' + @State + ''', ''' + @ListName + ''', '
   + ISNULL('''' + CONVERT(VARCHAR(25), @Updated, 121) + '''', 'NULL') + ','
   + CONVERT(VARCHAR(20), @Price) + ')';

--PRINT @Cmd

EXEC (@Cmd)

Open in new window


Edit - Bah! Beaten to the punch!
0
 

Author Comment

by:WorknHardr
ID: 39803534
Curious if any advantage between these two statements other than one is slightly shorter in statement length?

1) case when @Updated is null then 'null' else '''' + convert(varchar, @updated, 126) + '''' end + ', ' +
      convert(varchar, @Price) + ')';

2) ISNULL('''' + CONVERT(VARCHAR(25), @Updated, 121) + '''', 'NULL') + ','
   + CONVERT(VARCHAR(20), @Price) + ')';
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 39803576
mine (1) is longer but avoids concatenation into a NULL value and checking only afterwards.

Another difference is the date format. I used 126 because that should work with any regional settings. If 121 is US date (I didn't check) it could fail on other systems like UK.
0
 

Author Closing Comment

by:WorknHardr
ID: 39804627
thx a million + 1
0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question