No, you will need to use dynamic SQL for this, e.g.
DECLARE @sql NVARCHAR(MAX);
SELECT @sql = N'SELECT CAST(emp_id AS ' + Data_Type
+ ') FROM dbo.emp;'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'emp'
AND TABLE_SCHEMA = 'dbo' -- this might be important!
AND COLUMN_NAME = 'emp_id';
PRINT @sql;
-- EXEC sp_executesql @sql;
However, this seems wrong to me. Why don't you know the data types of your columns?
And in addition, you will need a much more complex query as you will want to take precision / scale / max length into account. If emp_id
is a varchar
, for example, all of the results will be truncated to one character.
And finally, I strongly recommend sys.columns
over INFORMATION_SCHEMA
.