sp_executesql with ISNUMERIC(@ColumnName) not working with column name passed as parameter
0
votes
1
answer
52
views
**Question**: Why example 1 does not work while example 2 works:
**SQL Table to check for non-numeric values in varchar column**:
CREATE TABLE #t(Mycol varchar(15))
INSERT #t VALUES ('123.86'),('4a5.67'),('45.68'),('45r8.78')
Query to check the NON-NUMERIC values in the table:
SELECT Mycol from #t WHERE ISNUMERIC(Mycol) = 0
**Output**:
| Mycol |
|---------------------|
| 4a5.67 |
| 45r8.78 |
**GOAL**: Achieve the same by using dynamic SQL
**Example 1**: Did not work, why? How can we improve this code without declaring variables outside EXECUTE sp_executesql statement; or is it even possible?
EXECUTE sp_executesql N'SELECT @colName as Mycol from #t WHERE ISNUMERIC(@colName) = 0', N'@colName varchar(15)', @colName = N'Mycol';
**Output**:
| Mycol |
|---------------------|
| Mycol |
| Mycol |
| Mycol |
| Mycol |
**Example 2**: Works - but required more variable declarations.
DECLARE @Qry nvarchar(150), @colName varchar(15) = 'Mycol'
SET @Qry = N'SELECT ' + @colName + ' FROM #t WHERE ISNUMERIC(' + @colName + ') = 0'
EXECUTE sp_executesql @Qry, N'@colName varchar(15)', @colName = N'Mycol';
Output:
| Mycol |
|---------------------|
| 4a5.67 |
| 45r8.78 |
Asked by nam
(515 rep)
Jul 14, 2025, 08:00 PM
Last activity: Jul 16, 2025, 10:16 PM
Last activity: Jul 16, 2025, 10:16 PM