How do I retrieve a particular value when the table name, column are given in a SQL Procedure
-
declare @id int execute getLastRaw 'subjectID','tblSubject', @id output print @id alter procedure getLastRaw @column char(20), @tbl Char(20), @return int output as declare @dynSQL varchar(100) select @dynSQL ='SELECT TOP 1 '+@return+'='+ @column + ' FROM ' + @tbl + ' ORDER BY ' + @column + ' DESC' exec(@dynsQL) I want to get the value which gets selected from the select statement. But it says: Msg 245, Level 16, State 1, Procedure getLastRaw, Line 5 Conversion failed when converting the varchar value 'SELECT TOP 1 ' to data type int.
-
Answer:
When you concatenate @return SQL Server tries to convert the whole expression to int because of http://msdn.microsoft.com/en-us/library/ms190309.aspx You can't assign @return outside or inside of the dynamic SQL because of scope: the stored proc and the dynamic SQL are different. Local variables are local to the scope only You'll have to use a temp table: this is per connection and available for inner scopes (dynamic SQL) ... declare @dynSQL varchar(100) select @dynSQL ='SELECT TOP 1 '+ @column + ' FROM ' + @tbl + ' ORDER BY ' + @column + ' DESC' CREATE TABLE #result (rtn int) INSERT #result (rtn) exec(@dynsQL) SELECT @return = rtn FROM #result GO Although, it is just as easy and more correct to use a proper SELECT... declare @id int SELECT @id = subjectID FROM tblSubject ORDER BY subjectID DESC print @id
Gihan at Stack Overflow Visit the source
Related Q & A:
- How do I retrieve a URL in Java?Best solution by Stack Overflow
- How do I get a nice face next to my name instead of a sillhouette?Best solution by Yahoo! Answers
- How do i make a signature for when i send an email?Best solution by Yahoo! Answers
- How can I retrieve a deleted pic/video from my digital camera?Best solution by easeus.com
- How can I retrieve a conversation?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.