In addition to Joe's answer:
It is important that you're using a Linq-to-SQL connection, because ExecuteQueryDynamic
is not available in the Entity Framework.
Here's how you can handle different data types as parameters (based on a Northwind database) in LinqPad 5:
void Main()
{
// Boolean
ExecuteQueryDynamic(@"DECLARE @Discontinued bit={0};
SELECT DISTINCT * FROM Products
WHERE Discontinued = @Discontinued", true).Dump();
// Int
ExecuteQueryDynamic(@"DECLARE @OrderId Int={0};
SELECT DISTINCT OrderId, CustomerId, ShipName FROM Orders
WHERE OrderID = @OrderId", 10248).Dump();
// String
ExecuteQueryDynamic(@"DECLARE @CustomerId nvarchar(max)={0};
SELECT DISTINCT * FROM Customers
WHERE CustomerId = @CustomerId", "VINET").Dump();
}
I recommend that you're using a DECLARE
statement for your SQL variables. This way, you can try it out first in T-SQL (or LinqPad SQL mode) with assigned fixed values - where you will receive meaningful error messages if the data types are not matching, then you can insert it into ExecuteQueryDynamic and insert {0}, {1}, {2} ...
for the first, second, third, ... parameter as follows:
ExecuteQueryDynamic(@"DECLARE @Discontinued bit={0}; DECLARE @ProductID Int={1};
DECLARE @CategoryID Int={2};
SELECT DISTINCT * FROM Products
WHERE Discontinued = @Discontinued AND ProductId = @ProductID
AND CategoryID = @CategoryID;
", true, 5, 2).Dump();
NOTE: ExecuteQueryDynamic does not support multiple resultsets. This means, only one SELECT statement is allowed, additional ones are being ignored.