Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Please help.

I am trying to create a procedure similar to below code: (SSMS)

SQL
DECLARE @OldPK AS VARCHAR(50)
DECLARE @PK AS VARCHAR(50)
DECLARE @S AS NVARCHAR(MAX)
DECLARE @P AS NVARCHAR(MAX)

SET @PK = 'ModeName'
SET @S = N'SELECT @pOldPK = @pPK FROM Modes '
SET @P = N'@pPK VARCHAR(50),  @pOldPK VARCHAR(50) OUTPUT'
EXECUTE dbo.sp_executesql @S, @P,  @pPK = @PK, @pOldPK = @OldPK OUTPUT
SELECT @OldPK

When I try to debug and after the line

EXECUTE dbo.sp_executesql @S, @P,  @pPK = @PK, @pOldPK = @OldPK OUTPUT


it stops and generated an error
SQL
"Object reerence not set to an instance of an object"


Your valuable input is very much appreciated.

Thanks.
Posted
Updated 10-Apr-15 9:21am
v3
Comments
Sergey Alexandrovich Kryukov 8-Apr-15 14:32pm    
This is not in SQL. It looks like a .NET exception message. Are you using ADO.NET? You can find out in what line the exception is thrown, that would be enough to solve the problem.
—SA
Putchicks 8-Apr-15 14:46pm    
I tried to run the in SSMS - Thanks Sergey
ZurdoDev 8-Apr-15 15:19pm    
I'm with SA on this one. I've never seen Sql give that error message. In fact if I change "Modes" to a table in my db this code executes without error.

Your error must be coming from C#.
Putchicks 8-Apr-15 15:52pm    
Thank RyanDev. I rectified the error in codes but it doesn't give me what I want to have a dynamic column (injected by user). please see below changes:

DECLARE @OldPK AS VARCHAR(50)
DECLARE @S AS NVARCHAR(MAX)
DECLARE @P AS NVARCHAR(MAX)
DECLARE @pOldPK AS VARCHAR(50)

SET @S = N'SELECT @pOldPK = m.ModeName FROM Modes m'
SET @P = N'@pOldPK VARCHAR(50) OUTPUT'
EXECUTE dbo.sp_executesql @S, @P, @pOldPK OUTPUT
SELECT @pOldPK

and it gives me the value sample "XXXX" when executed...
ZurdoDev 8-Apr-15 15:54pm    
If you want to let the user pick which column then you just need to use a variable in place of m.ModeName. Right now, you're always selecting ModeName from Modes.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900