How to get sp_executesql to accept parameter values that are not nvarchar

时间:2015-05-12 23:18:12

标签: sql-server stored-procedures sql-server-2012 dynamic-sql sp-executesql

I'm trying to build a dynamic SQL statement that is within a stored procedure. Here is a simplified version of it:

    var query = PFQuery(className:"Kits")
query.getObjectInBackgroundWithId("eXKU5kwMzj") {
    (gameScore: PFObject?, error: NSError?) -> Void in
    if error == nil && gameScore != nil {
        println(gameScore)
        let iKitPrice = gameScore?.objectForKey("Price")

        //The UI should only be updated from main thread
        dispatch_async(dispatch_get_main_queue()) {
           self.yourLabel.text = "\(iKitPrice)"
        }

    } else {
        println(error)
    }

The problem I have is that CREATE PROC dbo.GetOrders @UserID INT = 2 AS DECLARE @SQLString NVARCHAR(MAX) SET @SQLString = N'( SELECT * FROM dbo.Orders WHERE UserID = '+@UserID+' ) EXEC sys.sp_executesql @SQLString only works with Unicode data. So I get a conversion error on the sp_executesql parameter that's an integer:

Conversion failed when converting the nvarchar value 'SELECT * FROM dbo.Orders WHERE UserID = '

I MUST have my parameters declared at the start of the stored procedure and for user's to supply those values. The examples I've seen so far of using @UserID are showing the parameters and their values as being defined at runtime of the sp_executesql. This won't work for me because I need to reuse the parameters in other areas of the same stored procedure.

How could I solve this without specifying all my parameters to be of type sp_executesql?

2 个答案:

答案 0 :(得分:1)

It's not clear why you are using dynamic SQL here at all but this is the correct approach.

Undefined

答案 1 :(得分:1)

try this...

Options +FollowSymLinks
    RewriteEngine On

RewriteRule ^post/([a-zA-Z0-9_-]+)/$ post.php?post_id=53&post_name=$1 [L]

Or simply use the following

CREATE PROC dbo.GetOrders
@UserID INT = 2
AS
BEGIN
  SET NOCOUNT ON;
  DECLARE @SQLString NVARCHAR(MAX);

    SET @SQLString = N' SELECT * FROM dbo.Orders ' 
                   + N' WHERE UserID = @UserID '


EXEC sp_executesql @SQLString
                   ,N'@UserID INT'
                   ,@UserID
END