question

tpez avatar image
tpez asked

Adding a table name to a sql procedure as paramter

I am looking to use a parameter in a procedure function where I can execute it for any table, for example. :

CREATEProcedure selectALL @tableName varchar(50)

AS

SELECT*FROM @TableName whereTables= @TableName

GO;

EXEC selectALL(TableName)

I am using this as an example. I want to be able to use the procedure to select all from any table I want. In the EXEC statement, I want to be able to call it and name which table I want to "select *" from. Is there a way of doing this in SQL?

procedure
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
borispinsky avatar image
borispinsky answered

@tpez

CREATE PROCEDURE selectALL @tableName sysname AS declare @sql nvarchar(max) set @sql = 'select * from ['+@tableName+'] ' exec (@sql)

go

exec selectALL 'tblname'

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.