How to add desired column in pl/sql parser? - oracle

The following code shows no syntax error but in report it rise an error which is:
ORA-01722: invalid number
select line_number, col002 , case when exists (select null from cdr_personal_info c where c.phone_no=col002 ) then 'Yes' else null end as cdr
from apex_application_temp_files f,
table( apex_data_parser.parse(
p_content => f.blob_content,
p_add_headers_row => 'Y',
p_xlsx_sheet_name => :P31_XLSX_WORKSHEET,
p_max_rows => 500,
p_store_profile_to_collection => 'FILE_PARSER_COLLECTION',
p_file_name => f.filename ) ) p
where f.name = :P31_FILE

If you are on Oracle 12, then you can try explicitly converting the values to a number with the DEFAULT NULL ON CONVERSION ERROR option:
select line_number,
col002,
case
when exists (select null
from cdr_personal_info c
where TO_NUMBER(c.phone_no DEFAULT NULL ON CONVERSION ERROR)
= TO_NUMBER(col002 DEFAULT NULL ON CONVERSION ERROR)
)
then 'Yes'
else null
end as cdr
from apex_application_temp_files f,
table( apex_data_parser.parse(
p_content => f.blob_content,
p_add_headers_row => 'Y',
p_xlsx_sheet_name => :P31_XLSX_WORKSHEET,
p_max_rows => 500,
p_store_profile_to_collection => 'FILE_PARSER_COLLECTION',
p_file_name => f.filename ) ) p
where f.name = :P31_FILE
If that works then you know that either c_phone_no or col002 is not actually a number but is probably a string and there is at least one row where the string value cannot be parsed as a number.
You can then find it using:
select line_number,
col002
from apex_application_temp_files f,
table( apex_data_parser.parse(
p_content => f.blob_content,
p_add_headers_row => 'Y',
p_xlsx_sheet_name => :P31_XLSX_WORKSHEET,
p_max_rows => 500,
p_store_profile_to_collection => 'FILE_PARSER_COLLECTION',
p_file_name => f.filename ) ) p
where f.name = :P31_FILE
and TO_NUMBER(col002 DEFAULT NULL ON CONVERSION ERROR) IS NULL;
or:
select *
from cdr_personal_info c
where TO_NUMBER(c.phone_no DEFAULT NULL ON CONVERSION ERROR) IS NULL;

Related

Find session of locked row

I am experiencing row lock contention in my oracle DB. I tried to kill some session to unlock them, but this rows are still locked.
I know exact which row are locked.
Can I find the session ID that has locked this row. I can get the ROWID of that row.
As the good folks on AskTom say, we don't maintain a list of locked rows
But, if you want to try this - it'll show you locks by USER in your database, including Row locks.
SELECT
p.username username,
p.pid pid,
s.sid sid,
s.serial# serial,
p.spid spid,
s.username ora,
DECODE(l2.type, 'TX', 'TRANSACTION ROW-LEVEL', 'RT', 'REDO-LOG', 'TS', 'TEMPORARY SEGMENT ', 'TD', 'TABLE LOCK', 'TM', 'ROW LOCK'
, l2.type) vlock,
DECODE(l2.type, 'TX', 'DML LOCK', 'RT', 'REDO LOG', 'TS', 'TEMPORARY SEGMENT', 'TD', DECODE(l2.lmode + l2.request, 4, 'PARSE '
|| u.name || '.' || o.name, 6, 'DDL', l2.lmode + l2.request), 'TM', 'DML ' || u.name || '.' || o.name, l2.type) type,
DECODE(l2.lmode + l2.request, 2, 'RS', 3, 'RX', 4, 'S', 5, 'SRX', 6, 'X', l2.lmode + l2.request) lmode,
DECODE(l2.request, 0, NULL, 'WAIT') wait
FROM
gv$process p,
gv$_lock l1,
gv$lock l2,
gv$resource r,
sys.obj$ o,
sys.user$ u,
gv$session s
WHERE
s.paddr = p.addr
AND s.saddr = l1.saddr
AND l1.raddr = r.addr
AND l2.addr = l1.laddr
AND l2.type <> 'MR'
AND r.id1 = o.obj# (+)
AND o.owner# = u.user# (+)
--AND u.name = 'GME'
AND ( :user_name IS NULL
OR s.username LIKE upper(:user_name) )
ORDER BY
p.username,
p.pid,
p.spid,
ora,
DECODE(l2.type, 'TX', 'TRANSACTION ROW-LEVEL', 'RT', 'REDO-LOG', 'TS', 'TEMPORARY SEGMENT ', 'TD', 'TABLE LOCK', 'TM', 'ROW LOCK'
, l2.type)
This is a report in SQL Developer.

Laravel query not binding values correctly

My query is returning the wrong results and I think it is because the final parameter (minutes) is not being binded to the query. when I get the querylog everything seems fine but the wrong results are being returned. If I putthe minutes parameter directly into the query it returns the right results as expected but this value needs to be a variable.
To explain the query it is counting all records until the total minutes hit a set number, in my example im using 500.
This query works and returns results as expected:
DB::select('SELECT NULL AS session_total_charges, NULL AS call_date, NULL AS inbound_duration, NULL AS total
FROM dual
WHERE #total := 0
UNION ALL
SELECT session_total_charges, call_date, inbound_duration, #total := #total + inbound_duration AS total
FROM (SELECT * FROM records ORDER BY call_date) C where calling_user =:user and call_date LIKE :date AND outbound_zone_id IN ("UKX","UKM","UKLR","UKNR") and #total < 500', ["user"=>$user, "date"=>$date]);
This query does not work and only returns one row
DB::select('SELECT NULL AS session_total_charges, NULL AS call_date, NULL AS inbound_duration, NULL AS total
FROM dual
WHERE #total := 0
UNION ALL
SELECT session_total_charges, call_date, inbound_duration, #total := #total + inbound_duration AS total
FROM (SELECT * FROM records ORDER BY call_date) C where calling_user =:user and call_date LIKE :date AND outbound_zone_id IN ("UKX","UKM","UKLR","UKNR") and #total < :minutes', ["user"=>$user, "date"=>$date, "minutes"=>$minutes]);
[query] => SELECT NULL AS session_total_charges, NULL AS call_date, NULL AS inbound_duration, NULL AS total
FROM dual
WHERE #total := 0
UNION ALL
SELECT session_total_charges, call_date, inbound_duration, #total := #total + inbound_duration AS total
FROM (SELECT * FROM records ORDER BY call_date) C where calling_user =:user and call_date LIKE :date AND outbound_zone_id IN ("UKX","UKM","UKLR","UKNR") and #total < :minutes
[bindings] => Array
(
[user] => T-M000005251-009
[minutes] => 500
[date] => 2016-12-%%
)
//Result using bindings (only one row returned)
[0] => stdClass Object
(
[session_total_charges] => 0.014125
[call_date] => 2016-12-01 09:12:39
[inbound_duration] => 113
[total] => 113
)
//Result with values inserted directly into query(correct result returned)
[0] => stdClass Object
(
[session_total_charges] => 0.014125
[call_date] => 2016-12-01 09:12:39
[inbound_duration] => 113
[total] => 113
)
[1] => stdClass Object
(
[session_total_charges] => 0.04733333
[call_date] => 2016-12-01 09:18:16
[inbound_duration] => 142
[total] => 255
)
[2] => stdClass Object
(
[session_total_charges] => 0.03866667
[call_date] => 2016-12-01 09:22:21
[inbound_duration] => 116
[total] => 371
)
[3] => stdClass Object
(
[session_total_charges] => 0.012625
[call_date] => 2016-12-01 09:29:24
[inbound_duration] => 101
[total] => 472
)
[4] => stdClass Object
(
[session_total_charges] => 0.0505
[call_date] => 2016-12-01 12:03:16
[inbound_duration] => 404
[total] => 876
)

Changing SQL Server query to pure ANSI SQL query

I am working on a database system that uses SQL syntax. However I am unable to use the cross apply in the code below. Is there a way to rewrite this without applies?
declare #rsBuildDetails table(dt datetime, build varchar(255), val varchar(255));
insert into #rsBuildDetails (dt, build, val)
values ('20100101', '1', 'pass')
,('20100102', '2', 'fail')
,('20100103', '3', 'pass')
,('20100104', '4', 'fail')
,('20100105', '5', 'fail')
,('20100106', '6', 'fail')
,('20100107', '7', 'pass')
,('20100108', '8', 'pass')
,('20100109', '9', 'pass')
,('20100110', '10', 'fail');
with passed as
(
select *
from #rsBuildDetails
where val='pass'
)
select distinct
preFail.dt AS FailedDt,
postFail.dt AS SecondFailedDt
from
passed
cross apply
(select top 1
pre.*
from
#rsBuildDetails as pre
where
pre.dt < passed.dt
and pre.val = 'fail'
order by
pre.dt desc) as preFail
cross apply
(select top 1
post.*
from
#rsBuildDetails as post
where
post.dt > passed.dt
and post.val = 'fail'
order by
post.dt asc) as postFail
You might try to transfer the CTE and all applies to inlined sub-selects:
declare #rsBuildDetails table(dt datetime, build varchar(255), val varchar(255));
insert into #rsBuildDetails (dt, build, val) values
('20100101', '1', 'pass')
,('20100102', '2', 'fail')
,('20100103', '3', 'pass')
,('20100104', '4', 'fail')
,('20100105', '5', 'fail')
,('20100106', '6', 'fail')
,('20100107', '7', 'pass')
,('20100108', '8', 'pass')
,('20100109', '9', 'pass')
,('20100110', '10', 'fail');
select *
from
(
select distinct
(
select top 1 pre.Dt
from #rsBuildDetails as pre
where pre.dt<passed.dt
and pre.val='fail'
order by pre.dt desc
) as FailedDt
,(
select top 1 post.Dt
from #rsBuildDetails as post
where post.dt>passed.dt
and post.val='fail'
order by post.dt asc
) AS SecondFailedDt
from
(
select *
from #rsBuildDetails
where val='pass'
) AS passed
) AS tbl
where tbl.FailedDt IS NOT NULL
AND tbl.SecondFailedDt IS NOT NULL

How to generate model from database using Dapper?

I am coming from PetaPoco camp. PetaPoco has a T4 template which generates model from the database. Is anything similar available for Dapper?
I installed Dapper using NuGet and added SqlHelper.cs, but I didn't find anything which generates model from the database.
I've just recently written a sql query to do the job for myself. And updating it with extra types when i need. Just replace the table name where it says ####.
To make alot of tables i created a temp stored procedure to call. eg.
exec createTablePOCO(#tableName)
SELECT
'public ' + a1.NewType + ' ' + a1.COLUMN_NAME + ' {get;set;}'
,*
FROM (
/*using top because i'm putting an order by ordinal_position on it.
putting a top on it is the only way for a subquery to be ordered*/
SELECT TOP 100 PERCENT
COLUMN_NAME,
DATA_TYPE,
IS_NULLABLE,
CASE
WHEN DATA_TYPE = 'varchar' THEN 'string'
WHEN DATA_TYPE = 'datetime' AND IS_NULLABLE = 'NO' THEN 'DateTime'
WHEN DATA_TYPE = 'datetime' AND IS_NULLABLE = 'YES' THEN 'DateTime?'
WHEN DATA_TYPE = 'int' AND IS_NULLABLE = 'YES' THEN 'int?'
WHEN DATA_TYPE = 'int' AND IS_NULLABLE = 'NO' THEN 'int'
WHEN DATA_TYPE = 'smallint' AND IS_NULLABLE = 'NO' THEN 'Int16'
WHEN DATA_TYPE = 'smallint' AND IS_NULLABLE = 'YES' THEN 'Int16?'
WHEN DATA_TYPE = 'decimal' AND IS_NULLABLE = 'NO' THEN 'decimal'
WHEN DATA_TYPE = 'decimal' AND IS_NULLABLE = 'YES' THEN 'decimal?'
WHEN DATA_TYPE = 'numeric' AND IS_NULLABLE = 'NO' THEN 'decimal'
WHEN DATA_TYPE = 'numeric' AND IS_NULLABLE = 'YES' THEN 'decimal?'
WHEN DATA_TYPE = 'money' AND IS_NULLABLE = 'NO' THEN 'decimal'
WHEN DATA_TYPE = 'money' AND IS_NULLABLE = 'YES' THEN 'decimal?'
WHEN DATA_TYPE = 'bigint' AND IS_NULLABLE = 'NO' THEN 'long'
WHEN DATA_TYPE = 'bigint' AND IS_NULLABLE = 'YES' THEN 'long?'
WHEN DATA_TYPE = 'tinyint' AND IS_NULLABLE = 'NO' THEN 'byte'
WHEN DATA_TYPE = 'tinyint' AND IS_NULLABLE = 'YES' THEN 'byte?'
WHEN DATA_TYPE = 'char' THEN 'string'
WHEN DATA_TYPE = 'timestamp' THEN 'byte[]'
WHEN DATA_TYPE = 'varbinary' THEN 'byte[]'
WHEN DATA_TYPE = 'bit' AND IS_NULLABLE = 'NO' THEN 'bool'
WHEN DATA_TYPE = 'bit' AND IS_NULLABLE = 'YES' THEN 'bool?'
WHEN DATA_TYPE = 'xml' THEN 'string'
END AS NewType
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '####'
ORDER BY ORDINAL_POSITION
) as a1
Calling the stored procedure from a cursor
If you combine the sp mattritchies mentioned (see answer above) and call it from a cursor you can generate the poco class for every table in your database
USE YourDataBaseName
GO
DECLARE #field1 nvarchar(400)
DECLARE cur CURSOR LOCAL for
SELECT TABLE_NAME FROM information_schema.tables
OPEN cur
FETCH NEXT FROM cur INTO #field1 --, #field2
WHILE ##FETCH_STATUS = 0 BEGIN
exec Helper_CreatePocoFromTableName #field1 -- , #field2
fetch next from cur into #field1 -- , #field2
END
close cur
deallocate cur
Stored Procedure mattritchies mentioned
I took the sql from mattritchies answer (see above) and created the stored procedure he mentioned and modified it a bit so that it adds the class name as well. If you put Management Studio into Text-Output-Mode and remove the output of the column names you get copy paste text for all classes:
CREATE PROCEDURE [dbo].[Helper_CreatePocoFromTableName]
#tableName varchar(100)
AS
BEGIN
SET NOCOUNT ON;
-- Subquery to return only the copy paste text
Select PropertyColumn from (
SELECT 1 as rowNr, 'public class ' + #tableName + ' {' as PropertyColumn
UNION
SELECT 2 as rowNr, 'public ' + a1.NewType + ' ' + a1.COLUMN_NAME + ' {get;set;}' as PropertyColumn
-- ,* comment added so that i get copy pasteable output
FROM
(
/*using top because i'm putting an order by ordinal_position on it.
putting a top on it is the only way for a subquery to be ordered*/
SELECT TOP 100 PERCENT
COLUMN_NAME,
DATA_TYPE,
IS_NULLABLE,
CASE
WHEN DATA_TYPE = 'varchar' THEN 'string'
WHEN DATA_TYPE = 'nvarchar' THEN 'string'
WHEN DATA_TYPE = 'datetime' AND IS_NULLABLE = 'NO' THEN 'DateTime'
WHEN DATA_TYPE = 'datetime' AND IS_NULLABLE = 'YES' THEN 'DateTime?'
WHEN DATA_TYPE = 'smalldatetime' AND IS_NULLABLE = 'NO' THEN 'DateTime'
WHEN DATA_TYPE = 'datetime2' AND IS_NULLABLE = 'NO' THEN 'DateTime'
WHEN DATA_TYPE = 'smalldatetime' AND IS_NULLABLE = 'YES' THEN 'DateTime?'
WHEN DATA_TYPE = 'datetime2' AND IS_NULLABLE = 'YES' THEN 'DateTime?'
WHEN DATA_TYPE = 'int' AND IS_NULLABLE = 'YES' THEN 'int?'
WHEN DATA_TYPE = 'int' AND IS_NULLABLE = 'NO' THEN 'int'
WHEN DATA_TYPE = 'smallint' AND IS_NULLABLE = 'NO' THEN 'Int16'
WHEN DATA_TYPE = 'smallint' AND IS_NULLABLE = 'YES' THEN 'Int16?'
WHEN DATA_TYPE = 'decimal' AND IS_NULLABLE = 'NO' THEN 'decimal'
WHEN DATA_TYPE = 'decimal' AND IS_NULLABLE = 'YES' THEN 'decimal?'
WHEN DATA_TYPE = 'numeric' AND IS_NULLABLE = 'NO' THEN 'decimal'
WHEN DATA_TYPE = 'numeric' AND IS_NULLABLE = 'YES' THEN 'decimal?'
WHEN DATA_TYPE = 'money' AND IS_NULLABLE = 'NO' THEN 'decimal'
WHEN DATA_TYPE = 'money' AND IS_NULLABLE = 'YES' THEN 'decimal?'
WHEN DATA_TYPE = 'bigint' AND IS_NULLABLE = 'NO' THEN 'long'
WHEN DATA_TYPE = 'bigint' AND IS_NULLABLE = 'YES' THEN 'long?'
WHEN DATA_TYPE = 'tinyint' AND IS_NULLABLE = 'NO' THEN 'byte'
WHEN DATA_TYPE = 'tinyint' AND IS_NULLABLE = 'YES' THEN 'byte?'
WHEN DATA_TYPE = 'char' THEN 'string'
WHEN DATA_TYPE = 'timestamp' THEN 'byte[]'
WHEN DATA_TYPE = 'varbinary' THEN 'byte[]'
WHEN DATA_TYPE = 'bit' AND IS_NULLABLE = 'NO' THEN 'bool'
WHEN DATA_TYPE = 'bit' AND IS_NULLABLE = 'YES' THEN 'bool?'
WHEN DATA_TYPE = 'xml' THEN 'string'
END AS NewType
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #tableName
ORDER BY ORDINAL_POSITION
) AS a1
UNION
SELECT 3 as rowNr, '} // class ' + #tableName
) as t Order By rowNr asc
END
P.S.: I would have done it as an edit suggestion to his answers but my experience is that often edit suggestions get rejected.
Update
User chris-w-mclean suggested the following changes (see his suggested-edit) which i have not tried myself:
Replace SELECT 1 as rowNr, 'public class ' with SELECT 1.0 as rowNr, 'public class '
Replace SELECT 2 as rowNr, 'public ' with SELECT 2 + a1.ORDINAL_POSITION/1000 as rowNr, 'public '
Replace SELECT TOP 100 PERCENT COLUMN_NAME, with SELECT COLUMN_NAME,
add between IS_NULLABLE, CASE this line cast(ORDINAL_POSITION as float) as ORDINAL_POSITION,
remove ORDER BY ORDINAL_POSITION
change SELECT 3 as to SELECT 3.0 as
Try this version I optimized a bit, so that the result doesn't need to be piped to Text output. Instead, the PRINT statement allows the output to be copy/pasted easily. I've also removed the subquery and added declarations for nvarchar/ntext types.
This is for a single table, but it can be converted to a stored proc to use one of the cursor suggestions above.
SET NOCOUNT ON
DECLARE #tbl as varchar(255)
SET #tbl = '####'
DECLARE #flds as varchar(8000)
SET #flds=''
SELECT -1 as f0, 'public class ' + #tbl + ' {' as f1 into #tmp
INSERT #tmp
SELECT
ORDINAL_POSITION,
' public ' +
CASE
WHEN DATA_TYPE = 'varchar' THEN 'string'
WHEN DATA_TYPE = 'nvarchar' THEN 'string'
WHEN DATA_TYPE = 'text' THEN 'string'
WHEN DATA_TYPE = 'ntext' THEN 'string'
WHEN DATA_TYPE = 'char' THEN 'string'
WHEN DATA_TYPE = 'xml' THEN 'string'
WHEN DATA_TYPE = 'datetime' AND IS_NULLABLE = 'NO' THEN 'DateTime'
WHEN DATA_TYPE = 'datetime' AND IS_NULLABLE = 'YES' THEN 'DateTime?'
WHEN DATA_TYPE = 'int' AND IS_NULLABLE = 'YES' THEN 'int?'
WHEN DATA_TYPE = 'int' AND IS_NULLABLE = 'NO' THEN 'int'
WHEN DATA_TYPE = 'smallint' AND IS_NULLABLE = 'NO' THEN 'Int16'
WHEN DATA_TYPE = 'smallint' AND IS_NULLABLE = 'YES' THEN 'Int16?'
WHEN DATA_TYPE = 'decimal' AND IS_NULLABLE = 'NO' THEN 'decimal'
WHEN DATA_TYPE = 'decimal' AND IS_NULLABLE = 'YES' THEN 'decimal?'
WHEN DATA_TYPE = 'numeric' AND IS_NULLABLE = 'NO' THEN 'decimal'
WHEN DATA_TYPE = 'numeric' AND IS_NULLABLE = 'YES' THEN 'decimal?'
WHEN DATA_TYPE = 'money' AND IS_NULLABLE = 'NO' THEN 'decimal'
WHEN DATA_TYPE = 'money' AND IS_NULLABLE = 'YES' THEN 'decimal?'
WHEN DATA_TYPE = 'bigint' AND IS_NULLABLE = 'NO' THEN 'long'
WHEN DATA_TYPE = 'bigint' AND IS_NULLABLE = 'YES' THEN 'long?'
WHEN DATA_TYPE = 'tinyint' AND IS_NULLABLE = 'NO' THEN 'byte'
WHEN DATA_TYPE = 'tinyint' AND IS_NULLABLE = 'YES' THEN 'byte?'
WHEN DATA_TYPE = 'timestamp' THEN 'byte[]'
WHEN DATA_TYPE = 'varbinary' THEN 'byte[]'
WHEN DATA_TYPE = 'bit' AND IS_NULLABLE = 'NO' THEN 'bool'
WHEN DATA_TYPE = 'bit' AND IS_NULLABLE = 'YES' THEN 'bool?'
END + ' ' + COLUMN_NAME + ' {get;set;}'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #tbl
INSERT #tmp SELECT 999, '}'
SELECT #flds=#flds + f1 +'
' from #tmp order by f0
DROP TABLE #tmp
PRINT #flds
Dapper itself provides few extension methods (Query, Execute) for the connection object and does not have "model generator." Perhaps some other framework can be used to generate POCO's based on the db schema.
Update:
Database tables to C# POCO classes T4 template
<## template language="C#" debug="True" #>
<## assembly name="System" #>
<## assembly name="System.Data" #>
<## assembly name="System.Core" #>
<## assembly name="System.Xml" #>
<## assembly name="Microsoft.SqlServer.ConnectionInfo" #>
<## assembly name="Microsoft.SqlServer.Management.Sdk.Sfc" #>
<## assembly name="Microsoft.SqlServer.Smo" #>
<## import namespace="System" #>
<## import namespace="System.Text" #>
<## import namespace="System.Xml" #>
<## import namespace="Microsoft.SqlServer.Management.Smo" #>
<## import namespace="System.Data.SqlClient" #>
<## import namespace="Microsoft.SqlServer.Management.Common" #>
namespace Namespace
{
<#
var databaseName = "testDb";
var serverConnection = new SqlConnection(
#"Data Source=.\SQLEXPRESS; Integrated Security=true; Initial Catalog=" + databaseName);
var svrConnection = new ServerConnection(serverConnection);
Server srv = new Server(svrConnection);
foreach (Table table in srv.Databases[databaseName].Tables)
{
#>
class <#= table.Name #>
{
<#
foreach (Column col in table.Columns)
{
#>
public <#= GetNetDataType(col.DataType.Name) #> <#= col.Name #> { get; set; }
<#
}
#>
}
<# }
#>
}
<#+
public static string GetNetDataType(string sqlDataTypeName)
{
switch (sqlDataTypeName.ToLower())
{
case "bigint":
return "Int64";
case "binary":
return "Byte[]";
case "bit":
return "bool";
case "char":
return "char";
case "cursor":
return string.Empty;
case "datetime":
return "DateTime";
case "decimal":
return "Decimal";
case "float":
return "Double";
case "int":
return "int";
case "money":
return "Decimal";
case "nchar":
return "string";
case "numeric":
return "Decimal";
case "nvarchar":
return "string";
case "real":
return "single";
case "smallint":
return "Int16";
case "text":
return "string";
case "tinyint":
return "Byte";
case "varbinary":
return "Byte[]";
case "xml":
return "string";
case "varchar":
return "string";
case "smalldatetime":
return "DateTime";
case "image":
return "byte[]";
default:
return string.Empty;
}
}
#>
My approach is to:
Use <dynamic> to fetch some rows without type
Serialize these rows to JSON
Copy the JSON string from the console (or using the debugger)
Paste this into a JSON to C# model generator (e.g. https://app.quicktype.io/).
I.e.:
var persons = connection.Query<dynamic>("SELECT * FROM Persons");
var serializedPerson = JsonConvert.Serialize(persons.First());
Console.WriteLine(serializedPerson);
This one is for Oracle. It's probably not complete, but it's worked for me thus far.
SELECT
'public ' || A.NewType || ' ' || REPLACE(INITCAP(REPLACE(A.COLUMN_NAME, '_', ' ')), ' ', '') || ' {get;set;}' GET_SET
, A.*
FROM
(
SELECT
COLUMN_NAME,
DATA_TYPE,
NULLABLE,
CASE
WHEN DATA_TYPE = 'VARCHAR2' THEN 'string'
WHEN DATA_TYPE = 'VARCHAR' THEN 'string'
WHEN DATA_TYPE = 'DATE' AND NULLABLE = 'N' THEN 'DateTime'
WHEN DATA_TYPE = 'DATE' AND NULLABLE = 'Y' THEN 'DateTime?'
WHEN DATA_TYPE = 'INT' AND NULLABLE = 'N' THEN 'int?'
WHEN DATA_TYPE = 'INT' AND NULLABLE = 'Y' THEN 'int'
WHEN DATA_TYPE = 'DECIMAL' AND NULLABLE = 'N' THEN 'decimal'
WHEN DATA_TYPE = 'DECIMAL' AND NULLABLE = 'Y' THEN 'decimal?'
WHEN DATA_TYPE = 'NUMBER' AND NULLABLE = 'N' THEN 'decimal'
WHEN DATA_TYPE = 'NUMBER' AND NULLABLE = 'Y' THEN 'decimal?'
WHEN DATA_TYPE = 'NUMBER2' AND NULLABLE = 'N' THEN 'decimal'
WHEN DATA_TYPE = 'NUMBER2' AND NULLABLE = 'Y' THEN 'decimal?'
WHEN DATA_TYPE = 'CHAR' THEN 'string'
WHEN DATA_TYPE = 'CHAR2' THEN 'string'
WHEN DATA_TYPE = 'timestamp' THEN 'byte[]'
WHEN DATA_TYPE = 'CLOB' THEN 'byte[]'
ELSE '??'
END AS NewType
FROM USER_TAB_COLUMNS
WHERE TABLE_NAME = 'FIN_GLOBAL_CR_NUM_A'
ORDER BY COLUMN_ID
) A
Here's dapper-pocos I made for generating POCOs for Dapper. The solution uses SQL Server's "sp_HELP" and "sp_describe_first_result_set". Give it the name of a stored procedure, or give it a select statement, and it will generate the related POCOs for use with Dapper. The app just passes the stored procedure or select statement to sp_Help and sp_describe_first_result_set, and maps the results to C# data types.
I know it is an old topic,but there is another simple option can choose.
You can use PocoClassGenerator: Mini Dapper's POCO Class Generator (Support Dapper Contrib)
Support current DataBase all tables and views generate POCO class code
Support Dapper.Contrib
Support mutiple RDBMS : sqlserver,oracle,mysql,postgresql
mini and faster (only in 5 seconds generate 100 tables code)
Use appropriate dialect schema table SQL for each database query
DEMO
POCOGenerator Generate Class By Dynamic SQL | .NET Fiddle
POCO Class Generator GenerateAllTables | .NET Fiddle
DataTable POCO Class Generator | .NET Fiddle
GetStart
👇First : Copy&Paste PocoClassGenerator.cs Code to your project or LINQPad.
or Install from NuGet
PM> install-package PocoClassGenerator
👇Second : Use Connection to call GenerateAllTables and then print it.
using (var connection = Connection)
{
Console.WriteLine(connection.GenerateAllTables());
}
Support Dapper Contrib POCO Class
Just call method with GeneratorBehavior.DapperContrib
using (var conn = GetConnection())
{
var result = conn.GenerateAllTables(GeneratorBehavior.DapperContrib);
Console.WriteLine(result);
}
The Online Demo : POCO Dapper Contrib Class Generator GenerateAllTables | .NET Fiddle
Generate Comment
using (var conn = GetConnection())
{
var result = conn.GenerateAllTables(GeneratorBehavior.Comment);
Console.WriteLine(result);
}
Generate View
using (var conn = GetConnection())
{
var result = conn.GenerateAllTables(GeneratorBehavior.View);
Console.WriteLine(result);
}
Generate View and Comment and Dapper.Contrib
using (var conn = GetConnection())
{
var result = conn.GenerateAllTables(GeneratorBehavior.View | GeneratorBehavior.Comment | GeneratorBehavior.DapperContrib);
Console.WriteLine(result);
}
Generate one class by sql
Generate one class
using (var connection = Connection)
{
var classCode = connection.GenerateClass("select * from Table");
Console.WriteLine(classCode);
}
Specify class name
using (var connection = Connection)
{
var classCode = connection.GenerateClass("with EMP as (select 1 ID,'WeiHan' Name,25 Age) select * from EMP", className: "EMP");
Console.WriteLine(classCode);
}
DataTablePocoClass
Code at DataTablePocoClassGenerator.cs
var dt = new DataTable();
dt.TableName = "TestTable";
dt.Columns.Add(new DataColumn() { ColumnName = "ID", DataType = typeof(string) });
var result = dt.GenerateClass();
var expect =
#"public class TestTable
{
public string ID { get; set; }
}";
Assert.Equal(expect, result);
I had exactly the same requirement to generate objects from a database while handling CRUD reliably and efficiently in Dapper and took a different approach of preparing a replacement for Dapper's own Dapper.Contrib with support of Entity Framework schema definition so that scaffolding a database (models, relations, keys) can be done using Entity Framework tools like described for example here, sample below:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef dbcontext scaffold "Server=.\;Database=AdventureWorksLT2012;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Model
Above dependencies can be removed from the project after scaffolding.
Currently Dapper.SqlGenerator is successfully working in production. It does not produce any overhead over Dapper in terms of performance, sometimes reducing time to generate a query by other means.
Keep in mind there are 2 separate nuget packages - Dapper.SqlGenerator for purely SQL Code generation from EF (Core) scaffolded models and Dapper.SqlGenerator.Async to run CRUD queries against the database using Dapper.
TLDR; You can use Entity Framework (Core) to scaffold model from database and use Dapper.SqlGenerator to generate CRUD queries on generated objects.
I've seen where people use a hybrid project, using EF to scaffold the database, but I had to dapperize the output from that. For the recommended tools, I'm sure they are good, but I shy away from installing special software, until I had a stab at writing my own solution.
That said, here's a small CLI program(for my needs) that may be useful. Disclaimer, I'm not a seasoned C# programmer, so forgive anything that may be off kilter.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using Dapper;
namespace Pocos
{
public class TAB {
public string TABLE_NAME { get; set; }
}
public class COL {
public string COLUMN_NAME { get; set; }
public int? ORIDINAL_POSITIONS { set; get; }
public string DATA_TYPE { get; set; }
public string CHARACTER_MAXIMUM_LENGTH { get; set; }
public string NUMERIC_PRECISION { get; set; }
public string NUMERIC_SCALE { get; set; }
}
class Program {
static void Main(string[] args) {
string sConnect = "Server=LT6-MARKL;Database=PKDEM815;UID=PKDEM815;Password=PKDEM815";
IEnumerable tables;
IEnumerable columns;
List lines;
using ( var conn = new SqlConnection(sConnect))
tables = conn.Query("SELECT * FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME");
// Roll through each table of the database and generate an .cs file, as a POCO
foreach (TAB t in tables.OrderBy(t => t.TABLE_NAME)) {
lines = new List();
lines.Add("using System;");
lines.Add("using System.Collections.Generic;");
lines.Add("using System.Configuration;");
lines.Add("using System.Data.SqlClient;");
lines.Add("using Dapper;");
lines.Add("using Dapper.Contrib.Extensions;");
lines.Add("");
lines.Add("namespace PKDataLayer.Models {");
lines.Add("");
lines.Add("\t[Table(\"" + t.TABLE_NAME + "\")]");
lines.Add("\tpublic class " + t.TABLE_NAME + " {");
lines.Add("");
using (var conn2 = new SqlConnection(sConnect)) {
columns = conn2.Query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '"+ t.TABLE_NAME +"' ORDER BY ORDINAL_POSITION");
foreach( COL c in columns) {
if (t.TABLE_NAME + "_KEY" == c.COLUMN_NAME || t.TABLE_NAME + "_SEQNUM" == c.COLUMN_NAME)
lines.Add("\t\t[Key]");
// SELECT DISTINCT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME IN ( SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES )
if (c.DATA_TYPE == "char" || c.DATA_TYPE == "varchar")
lines.Add("\t\tpublic string " + c.COLUMN_NAME + " { get; set; }");
if (c.DATA_TYPE == "int")
lines.Add("\t\tpublic int " + c.COLUMN_NAME + " { get; set; }");
if (c.DATA_TYPE == "datetime")
lines.Add("\t\tpublic DateTime? " + c.COLUMN_NAME + " { get; set; }");
if (c.DATA_TYPE == "decimal" || c.DATA_TYPE == "numeric")
lines.Add("\t\tpublic decimal? " + c.COLUMN_NAME + " { get; set; }");
}
}
lines.Add("\t}");
lines.Add("}");
Console.WriteLine("Creating POCO for " + t.TABLE_NAME);
using (TextWriter tw = new StreamWriter( t.TABLE_NAME + ".cs" ))
foreach (String s in lines)
tw.WriteLine(s);
}
}
}
}
This might not work with VS2010, but if you've been updating your Version this should work.
My way of generating Models from a Database is with Ef Core Power Tools, a little Add-On that uses Ef Core 6.
Go to Extensions in Visual Studio and install it. After that, you can right-click on your Project and select Reverse Engineer under EF Core Power Tools.
From there, you connect to the Database, select the Tables to be reverse-engineered and select EntityTypes only
You can be as specific as you want, e.g. specify the output path (DbModels in my case). Click on OK.
Then, your Models should pop up and you're free to use these Models in your Dapper-Code.
I'm the author of a POCO-Generator template called CodegenCS.POCO.
The link above contains C# and PowerShell Scripts which allow you to build complete POCOs (ready to use in Dapper) which also include override bool Equals(), override int GetHashCode(), and (for those who like it) it includes full ActiveRecord CRUD queries (Insert/Update).
Check out this example POCO from Northwind database. If you like it, it's very easy to use the templates:
Edit the connection string and paths in RefreshSqlServerSchema.csx and invoke it through PowerShell script RefreshSqlServerSchema.ps1
This will Extract the Schema of a SQL Server database into a JSON file
Edit the paths and the POCOs Namespace in GenerateSimplePOCOs.csx and invoke it through PowerShell script GenerateSimplePOCOs.ps1
This will Read the JSON Schema and build the POCOs.
The generator script is very simple to understand and customize.
So based on some SQL here and there. I've build a "simple" select that generate class(es) for table(s) or a schema(s)!
What's nice about it, is that it will:
Keep the column order
Adding namespaces
Add the [Table] Attributes on the class.
Add the [Key] on the primary key(s) (might not be supported by dapper.contrib if 2+ PK)
The function below can be used like so:
select *
from dbo.TableToClass('schema','null or table name') m
where m.TableName not in('unwantedtablename')
order by m.TableSchema asc
, m.TableName asc
, m.ClassOrder asc
, m.ColumnOrder asc;
When you copy paste from SSMS, it might remove the TAB. Here is the code:
CREATE or alter function dbo.TableToClass(
#schema varchar(250)
, #table varchar(250)
)
returns table
as
return
/*
--USE IT LIKE: the order by is necessary on the query
select *
from dbo.TableToClass('schemaName', 'null or table name') m
order by
m.tableSchema asc
, m.tableName asc
, m.ClassOrder asc
, m.columnOrder asc
*/
with typeConversion as(
Select
typeConversion.sqlType
,typeConversion.isNullable
,typeConversion.cSharpType
from
( values
('nvarchar', 'YES', 'string'), ('nvarchar','NO', 'string')
,('varchar', 'YES', 'string'), ('varchar', 'NO', 'string')
,('char', 'YES', 'string'), ('char', 'NO', 'string')
,('datetime', 'YES', 'DateTime?'), ('datetime', 'NO', 'DateTime')
,('datetime2', 'YES', 'DateTime?'), ('datetime2', 'NO', 'DateTime')
,('date', 'YES', 'DateTime?'), ('date', 'NO', 'DateTime')
,('datetimeoffset', 'YES', 'DateTimeOffset?'), ('datetimeoffset', 'NO', 'DateTimeOffset')
,('time', 'YES', 'TimeSpan?'), ('timestamp', 'NO', 'TimeSpan')
,('bigint', 'YES', 'long?'), ('bigint', 'NO', 'long')
,('int', 'YES', 'int?'), ('int', 'NO', 'int')
,('smallint', 'YES', 'Int16?'), ('smallint','NO', 'Int16')
,('decimal', 'YES', 'decimal?'), ('decimal', 'NO', 'decimal')
,('numeric', 'YES', 'decimal?'), ('numeric', 'NO', 'decimal')
,('money', 'YES', 'decimal?'), ('money', 'NO', 'decimal')
,('tinyint', 'YES', 'byte?'), ('tinyint', 'NO', 'byte')
,('varbinary', 'YES', 'byte[]'), ('varbinary', 'NO', 'byte[]?')
,('bit', 'YES', 'bool?'), ('bit', 'NO', 'bool')
,('xml', 'YES', 'string'), ('xml', 'NO', 'string')
) typeConversion(sqlType, isNullable, cSharpType)
), columnInfo as (
select
colInfo.TABLE_SCHEMA
, colInfo.TABLE_NAME
, concat(colInfo.TABLE_SCHEMA, '.', colInfo.TABLE_NAME) FullTableName
, colInfo.COLUMN_NAME
, colInfo.ORDINAL_POSITION
, typeConversion.sqlType
, typeConversion.csharpType
,case
(
Select top 1 pk.CONSTRAINT_TYPE
from INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS columnUsage
join INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS pk
--on pk.CONSTRAINT_TYPE = 'PRIMARY KEY'
on pk.TABLE_SCHEMA = colInfo.TABLE_SCHEMA
and pk.TABLE_NAME = colInfo.TABLE_NAME
and pk.CONSTRAINT_NAME = columnUsage.CONSTRAINT_NAME
where
columnUsage.TABLE_SCHEMA = colInfo.TABLE_SCHEMA
and columnUsage.TABLE_NAME = colInfo.TABLE_NAME
and columnUsage.COLUMN_NAME = colInfo.COLUMN_NAME
)
when 'PRIMARY KEY' then (
case (select COLUMNPROPERTY(OBJECT_ID(concat(colInfo.TABLE_SCHEMA ,'.',colInfo.TABLE_NAME)),colInfo.COLUMN_NAME,'isidentity'))
when 1 then 'PK IDENTITY'
else 'PK'
end
)
when 'FOREIGN KEY' then 'FK'
else 'COL'
end as ColumnType
from INFORMATION_SCHEMA.COLUMNS as colInfo
left join typeConversion on typeConversion.sqlType = colInfo.DATA_TYPE and typeConversion.isNullable = colInfo.IS_NULLABLE
where
/************ SET PARAMETER / CONDITION HERE **************/
( --SCHEMA
'True' = (
case
--when #schema is null then return 'True'
when colInfo.TABLE_SCHEMA = coalesce(#schema, 'dbo') then 'True'
else 'False'
end
)
And -- SET SCHEMA NAME HERE (might be dbo for default)
'True' = ( --Table
case
when #table is null then 'True'
when colInfo.TABLE_NAME = #table then 'True'
else 'False'
end
)
)
), classBuilder2_StartFile as (
select top 1
concat(
'using System;', char(10)
,'using Dapper;', char(10)
,'using Dapper.Contrib;', char(10)
,'using Dapper.Contrib.Extensions;', char(10)
, char(10)
,'namespace MYPROJECTNAMESPACE.',c.TABLE_SCHEMA, '.Models.Db; ', char(10)
) as txt
, 'Using & Namespace' as ClassPart
, 5 as ClassOrder
, c.TABLE_SCHEMA as tableSchema
from columnInfo c
), classBuilder2_StartClass as(
select distinct
concat(
char(10)
, '[Table("',c.FullTableName,'")]', char(10)
, 'public partial class ', c.TABLE_NAME, char(10)
, '{'
) as txt
, 'Class name' as ClassPart
, 17 as ClassOrder
, c.TABLE_NAME as tableName
, c.TABLE_SCHEMA as tableSchema
from columnInfo c
), classBuilder2_Properties as(
select
concat(
case c.ColumnType --Column Attribute for dapper.
when 'PK' then
concat(Char(9),'[ExplicitKey]', char(10)) --Dapper: After insert return 0
when 'PK IDENTITY'then
concat(Char(9),'[Key]', char(10)) -- Dapper: After inser return actual PK
else ''
end
, Char(9), char(9), 'public ', c.csharpType,' ', c.COLUMN_NAME, ' { get; set; }'
) as txt
, ORDINAL_POSITION as columnOrder
, 'Property' as ClassPart
, 30 as ClassOrder
, c.COLUMN_NAME as columnName
, c.TABLE_NAME as tableName
, c.TABLE_SCHEMA as tableSchema
from columnInfo c
), classBuilder2_EndClass as(
select distinct
concat(
char(9), '}'
) as txt
, 'End of C# Class' as ClassPart
, 111 as ClassOrder
, c.TABLE_NAME as tableName
, c.TABLE_SCHEMA as tableSchema
from columnInfo c
), classBuilder2_EndFile as(
select top 1
concat(
char(10),char(10)
) as txt
, 'End of C# Class' as ClassPart
, 120 as ClassOrder
, 'ZZZZZ' as tableName
, 'ZZZZZ' as tableSchema
from columnInfo c
), classBuilder_merge as(
select txt, ClassPart, ClassOrder, 'AAA_SCHEMA' as tableName, tableSchema, 'N/A' as columnName, 0 as columnOrder
from classBuilder2_StartFile
union all
select txt, ClassPart, ClassOrder, tableName, tableSchema, 'N/A' as columnName, 0 as columnOrder
from classBuilder2_StartClass
union all
select txt, ClassPart, ClassOrder, tableName, tableSchema, columnName, columnOrder
from classBuilder2_Properties
union all
select txt, ClassPart, ClassOrder, tableName, tableSchema, 'N/A'as columnNam, 0 as columnOrder
from classBuilder2_EndClass
union all
select txt, ClassPart, ClassOrder, tableName, tableSchema, 'N/A'as columnNam, 0 as columnOrder
from classBuilder2_EndFile
), finalSelect as(
--AFTER SQL Server 2016 (13.x) and later. If before that, remove CROSS APPLY STRING_SPLIT
select top 100 percent
lines.*
, m.tableSchema
, m.tableName
, m.ClassOrder
, m.columnOrder
from classBuilder_merge m
CROSS APPLY STRING_SPLIT(m.txt, char(10)) lines
order by --
m.tableSchema asc
, m.tableName asc
, m.ClassOrder asc
, m.columnOrder asc
)
select * from finalSelect;

ORA-00907: missing right parenthesis

SELECT DISTINCT( EMP.EMPLOYEEID ),
EMP.EMPLOYEECODE,
EMP.EMPLOYEENAME,
EMP.HOMEADDRESS,
DESIG.DESIGNATIONNAME
FROM HRM_EMPLOYEE EMP,
COM_DESIGNATION DESIG,
COM_DEPARTMENT DEPT,
COM_COMPANY COMP,
HRM_EMPLOYEEDEPARTMENTS EMPDEPT,
USR_USERS USRS
WHERE EMP.EMPLOYEEID = EMPDEPT.EMPLOYEEID AND
EMP.DESIGNATIONID = DESIG.DESIGNATIONID AND
DESIG.DEPARTMENTID = EMPDEPT.DEPARTMENTID AND
EMP.STATUS IN (SELECT STAT STAT
FROM
(
CASE
When (:status = 0) THEN
SELECT 1 STAT FROM dual
UNION ALL
SELECT 2 STAT FROM dual
else
Select :status STAT from dual
end
)
xx
)
Actually my need is: stow the records according to the parameter passing. if tat parameter i wish to show all records.
You cannot have a CASE statement as a table expression (unless perhaps if using nested table types). But why so complicated? Instead of this:
EMP.STATUS IN (SELECT STAT STAT
FROM
(
CASE
When (:status = 0) THEN
SELECT 1 STAT FROM dual
UNION ALL
SELECT 2 STAT FROM dual
else
Select :status STAT from dual
end
)
xx
)
Write this:
(EMP.STATUS IN (1, 2) AND :status = 0) OR
(EMP.STATUS = :status)
SELECT DISTINCT( EMP.EMPLOYEEID ),
EMP.EMPLOYEECODE,
EMP.EMPLOYEENAME,
EMP.HOMEADDRESS,
DESIG.DESIGNATIONNAME
FROM HRM_EMPLOYEE EMP,
COM_DESIGNATION DESIG,
COM_DEPARTMENT DEPT,
COM_COMPANY COMP,
HRM_EMPLOYEEDEPARTMENTS EMPDEPT,
USR_USERS USRS
WHERE EMP.EMPLOYEEID = EMPDEPT.EMPLOYEEID AND
EMP.DESIGNATIONID = DESIG.DESIGNATIONID AND
DESIG.DEPARTMENTID = EMPDEPT.DEPARTMENTID AND
(
(EMP.STATUS IN (1, 2) and :status = 0)
or :status <> 0 --This will not filter your status, as I expect you want it to do so
)

Resources