I have an SQL command I am attempting to execute.
The syntax is as follows
Public Shared Function CanRaiseWorkOrder(connection As IDbConnection, ProductID As Guid) As Boolean
Using sqlCmd As IDbCommand = connection.CreateCommand
With sqlCmd
.CommandTimeout = 30
.CommandType = CommandType.Text
.CommandText = "DECLARE @CanRaiseWorkOrder BIT, @WorkOrderQtyCount INT, @ProductAvailCount INT SET @WorkOrderQtyCount = (SELECT SUM(Qty) FROM WorkOrder WHERE ProductID = @ProductID AND WorkOrder.Status <> 4) --4 = Voided SET @ProductAvailCount = (SELECT Qty FROM Product WHERE ProductID = @ProductID) IF @WorkOrderQtyCount < @ProductAvailCount BEGIN SET @CanRaiseWorkOrder = 1 END ELSE BEGIN SET @CanRaiseWorkOrder = 0 END SELECT @CanRaiseWorkOrder AS CanRaiseWorkOrder"
Dim params As New List(Of IDbDataParameter)({
ProductDAL.CreateTSqlParameter("@ProductID", DbType.Guid, ProductID)
})
.Parameters.AddRange(params)
Return .ExecuteScaler(Of Boolean)()
End With
End Using
End Function
As you will probably notice there is some customization there in regards to how the parameters are created and the command executed but you can assume those aspects of the system work as required (We have a significant amount of code that functions correctly using those methods).
I will probably get some people asking why this is not a stored procedure and the answer is “because my boss said so”.
I have run SQL profiler and here is the output that this query actually generates.
exec sp_executesql N'DECLARE @CanRaiseWorkOrder BIT, @WorkOrderQtyCount INT, @ProductAvailCount INT SET @WorkOrderQtyCount = (SELECT SUM(Qty) FROM WorkOrder WHERE ProductID = @ProductID AND WorkOrder.Status <> 4) --4 = Voided SET @ProductAvailCount = (SELECT Qty FROM Product WHERE ProductID = @ProductID) IF @WorkOrderQtyCount < @ProductAvailCount BEGIN SET @CanRaiseWorkOrder = 1 END ELSE BEGIN SET @CanRaiseWorkOrder = 0 END SELECT @CanRaiseWorkOrder',N'@ProductID uniqueidentifier',@ProductID='0908C780-763F-4CE6-B074-CEC01F4451B4'
Running the code in query analyser (when I originally created it) works fine but if I run the above query as outputted from the SQL command all I get is “Command(s) completed successfully.“
Any ideas?
Figure I’ll make it an answer, but also wanted to make sure I was accurate (considering how long I’ve been up now :grin:).
From what I can see (and this is probably due to condensing your statement for the sake of making it a one-liner in a code file) you have a comment declaration in the middle of your statement:
What’s happening is you’re executing only your DECLARE and first SET command (which are done without error) but the rest of your statement is being ignored because it follows the comment declaration (
--).Make sure if you do condense your query that you remove commented lines. Once they’re on one line, SQL doesn’t care and WILL ignore anything past the
--.