I was tasked to validate the decimal and integer values of the columns from a list of tables. I have around 10-12 tables having different column names.
I created a lookup table which has the table name and the column names of decimal and integer as shown below. for example 'Pricedetails' and 'Itemdetails' tables have many columns of which only the ones mentioned in the Lookup table are required.
lkpTable
| TableName | requiredcolumns |
|---|---|
| Pricedetails | sellingPrice,RetailPrice,Wholesaleprice |
| Itemdetails | ItemID,Itemprice |
Pricedetails
| Priceid | Mafdate | MafName | sellingPrice | RetailPrice | Wholesaleprice |
|---|---|---|---|---|---|
| 01 | 2020-01-01 | Americas | 25.00 | 43.33 | 33.66 |
| 02 | 2020-01-01 | Americas | 43.45 | 22.55 | 11.11 |
| 03 | 2021-01-01 | Asia | -23.00 | -34.00 | 23.00 |
Itemdetails
| ItemID | ItemPrice | Itemlocation | ItemManuf |
|---|---|---|---|
| 01 | 45.11 | Americas | SA |
| 02 | 25.00 | Americas | SA |
| 03 | 35.67 | Americas | SA |
I have created a stored procedure with table name as input parameter, and able to pull the required column names of the tables (input parameter) from the lookup table and store that resultset into a table variable, below is the code.
declare @resultset Table
(
id INT identity(1,1),
tablename varchar(200) ,
ColumnNames varchar(max)
)
declare @tblname varchar(200),@sql varchar(max),@cols varchar(max),
INSERT INTO @resultset
select tablename,ColumnNames
from lkptable where tablename ='itemdetails'
select @cols = ColumnNames from @resultset;
select @tblname = TableName from @resultset;
----- Split the comma separated columnnames
Create table ##splitcols
(
ID int identity(1,1),
Name varchar(50)
)
Insert into ##splitcols
select value from string_split(@cols,',')
set @sql = 'select ' +@cols + ' from ' +@tblname
--print (@cols)
exec (@sql)
select * from ##splitcols
On executing the above code i get the below result sets, similarly what ever table name i provide i can get the required columns and its relevant data, now i am stuck at this point on how to validate whether the columns are decimal or int. I tried using while loop and cursor to pass the Name value from Resultset2, to the new dynamic query, somehow i don't find any way on how to validate.
| ItemID | ItemPrice |
|---|---|
| 01 | 45.11 |
| 02 | 25.00 |
| 03 | 35.67 |
Resultset2
| ID | Name |
|---|---|
| 01 | ItemID |
| 02 | ItemPrice |