Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper return single value

Tags:

c#

dapper

t-sql

I want to perform this simple test to see whether a table exists. I thought it would be easy just to return an int value depending on whether the table exists.

Below is what I have tried and doesn't work:

result = connection.ExecuteScalar<int>(@"
IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = '@tableSchema' 
                 AND  TABLE_NAME = '@tableName'))
    RETURN 0;


RETURN 1;
", new { tableSchema, tableName });

Error Message:

A RETURN statement with a return value cannot be used in this context.

It's something really noddy...

like image 938
Callum Linington Avatar asked Oct 30 '25 08:10

Callum Linington


1 Answers

ExecuteScalar

executes the query, and returns the first column of the first row in the result set returned by the query.

It does not return the return value of your SQL statements. You could simply use

SELECT 1
FROM   INFORMATION_SCHEMA.TABLES 
WHERE  TABLE_SCHEMA = @tableSchema
AND    TABLE_NAME   = @tableName

Then you can use ExecuteScalar and it will return 1 if the table exists. Please note that I also corrected your parameters in the SQL statements. They must not be delimited by '.

like image 130
Dirk Avatar answered Nov 01 '25 00:11

Dirk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!