views:

30

answers:

2

Is it possible to get input from a user for a variable?

For an example: How do i get the firstname of a user to use it in my script to select it from my employee table.

I now how i declare a variable but not how to get it typed in by the user of the script

+1  A: 
  SELECT @YourVariable = FirstName
  FROM Employee
  WHERE Id = @SomeId

You can use sqlcmd http://msdn.microsoft.com/en-gb/library/ms162773.aspx, so you can specify variables in command line

sqlcmd -iyourscript.sql -v yourvar=yourvalue

and in script

 SELECT @YourVariable = FirstName
  FROM Employee
  WHERE Id = ${yourvar}
Michael Pakhantsov
In this way i can select a firstname into @yourvariable.But i am looking for a direct input from the user without using a table
Harm
@Harm, What is mean 'direct input from user' in your context?
Michael Pakhantsov
It means that the user who is running the script has to use the keybord to type in his firstname followed by enter.Harm
Harm
@Harm, try sqlcmd.
Michael Pakhantsov
I'm still not sure that will do what the OP wants? According to this question http://stackoverflow.com/questions/3302225/sqlcmd-prompt-for-variable
Martin Smith
+1  A: 

You can do something like what you're asking with stored procedures. Start them like:

CREATE PROCEDURE [dbo].[NameOfStoredProcedure]
(
   @cTableName      varchar(75),    -- name of the table
   @iTopLevelId         int = 0     -- Id parameter
)
AS
etc

Then when executing the stored procedure from Management Studio a dialog box will appear requesting the parameters.

Here's a walkthrough of the process: http://www.mssqltips.com/tip.asp?tip=1375

PaulG
Hi I used the following:CREATE PROCEDURE testing( @cTableName varchar(75), -- name of the table @iTopLevelId int = 0 -- Id parameter ) AS print @cTableName print @iToplevelId EXECUTE testingBut i only get the folowing error message:Msg 201, Level 16, State 4, Procedure testing, Line 0Procedure or Function 'testing' expects parameter '@cTableName', which was not supplied.What is going wrong?Harm
Harm
@Harm. Instead of 'EXECUTE Testing', right click the stored procedure and select Execute
PaulG
Unfortunately I get the same error.Is it possible that I need other right in Sql Server
Harm
@Harm. Weird, I'm not sure. I added an edit which describes the process.
PaulG