Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

passing a parameter into a view 1

Status
Not open for further replies.

DanC

Programmer
Jan 12, 2001
65
US
Is there any way to pass a parameter into a view? What I'm trying to do is create a view based on a certain state.

DECLARE @state VARCHAR(2)

SET @state = 'CA'

SELECT * FROM tier2v2
WHERE tier2v2.STATE = @state

works fine, but when I try this:

DECLARE @state VARCHAR(2)
SET @state = 'CA'

CREATE VIEW TEMP_TABLE AS

SELECT * FROM tier2v2
WHERE tier2v2.STATE = @state

I get errors. I know this is probably a simple question, but I did search the forum and couldn't find anything that applied.




 
Here u go.

DECLARE @state VARCHAR(2)
SET @state = 'CA'
declare @query varchar(1000)

set @query = "CREATE VIEW TEMP_TABLE AS SELECT * FROM tier2v2
WHERE tier2v2.STATE = '"+@state+"'"
print @query
exec (@query)
 
darn, didn't work for me. this is the error I got:

Server: Msg 207, Level 16, State 3, Line 5
Invalid column name 'CREATE VIEW TEMP_TABLE AS SELECT * FROM tier2v2
WHERE tier2v2.STATE = ''.
Server: Msg 207, Level 16, State 1, Line 5
Invalid column name '''.
 
use this statement before the procedure or view etc

SET QUOTED_IDENTIFIER OFF

 
I don't think the road you are travelling here is going to work. My feeling is that the DDL statement to construct the view is completely unaware of the variable @state.

And in a way, you might not be really achieving all that much anyway.

i.e. To say this

declare @state varchar(2)
set @state = 'CA'
Select from TempTable

is not really much improvement (even if it had worked) over

SELECT * FROM tier2v2
WHERE tier2v2.STATE = @state

So I don't think there's much solution here. You may as well just stick with that.

----------------------------------

Where you do find Views more commonly used is to save the trouble of passing the variable at all, like this:

CREATE VIEW vwCalifornia
As
SELECT * FROM tier2v2
WHERE tier2v2.STATE = 'CA'

Then users can do this:
Select * from vwCalifornia

However, this is not really what you wanted either.
---------------------
bperry
 
You cannot pass a parameter to a view. If you need to parametrize, create a stored procedure.

CREATE Procedure uspTier2v2ByState
@state char(2) AS

SELECT * FROM tier2v2
WHERE STATE = @state Terry L. Broadbent - DBA
Computing Links:
faq183-874 contains "Suggestions for Getting Quick and Appropriate Answers" to your questions.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top