|
|
|||||||||
|
|||||||||
|
|||||||||
| |
||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
set variable in stored procedure
can I set a value to a variable when the table name and the column are variable? I tried this way and got an error...
select @cur_max_value = MAX(@cur_field) FROM @cur_table |
|
#2
|
|||
|
|||
|
Quote:
You could try making the right hand side a function and then using select @cur_max_value = SELECT * FROM dbo.myMAXfunction(@cur_field, @cur_table) I've used a sql_variant datatype below because I don't know what you might be maxxing, and you don't have to use a table function (i think) but it's the first thing I thought of. CREATE FUNCTION dbo.myMAXfunction ( @cur_field nvarchar(200), @cur_table nvarchar(200) ) RETURNS @myTable TABLE ( [maxcol] sql_variant ) AS BEGIN INSERT @myTable SELECT MAX(@cur_field) FROM @cur_table RETURN END |
|
#3
|
|||
|
|||
|
I tried to run the following function (in query analyzer):
Code:
CREATE FUNCTION GET_MAX_VALUE ( @cur_field AS VARCHAR(50), @cur_table AS VARCHAR(50) ) RETURNS @myTable TABLE ( [maxcol] INT ) AS BEGIN INSERT @myTable SELECT MAX(@cur_field) FROM @cur_table RETURN END But I'm getting this error: "Must declare the variable '@cur_table'." |
|
#4
|
|||
|
|||
|
remove the AS after each variable name and see what happens. I'd also recommend putting dbo. in front of all sps and udfs
CREATE FUNCTION dbo.GET_MAX_VALUE ( @cur_field VARCHAR(50), @cur_table VARCHAR(50) ) |
|
#5
|
|||
|
|||
|
Still doesn't work :-(
![]() |
|
#6
|
|||
|
|||
|
Try this
DECLARE @sQuery nvarchar(200) SET sQuery = 'SELECT MAX(' + @cur_field +') FROM ' + @cur_table EXEC (@sQuery) |
|
#7
|
||||
|
||||
|
Try this:
Code:
CREATE FUNCTION dbo.GET_MAX_VALUE ( DECLARE @cur_field VARCHAR(50), DECLARE @cur_table VARCHAR(50) )
__________________
Come JOIN the party!!! Quote of the Month: Retirement: Because you've given so much of yourself to the company that you don't have anything left we can use. Questions to Ponder: What do you do when you see an endangered animal eating an endangered plant? iif([sarcasm]=true,iif([you have to ask]=true,"didn't work","ha ha ha"),"not sarcasm") copyright© 2008 sbenj69 Last edited by mehere : August 3rd, 2005 at 12:19 PM. |
|
#8
|
|||
|
|||
|
Are you using the database with an application or a website? If so this becomes a lot easier because you can return the value back to the application and store it in a variable there. Otherwise I'm not sure it can be done using pure sql server.
|
![]() |
| Viewing: ASP Free Forums > Database > Microsoft SQL Server > set variable in stored procedure |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|