How to pass table name dynamically in T-SQL - sql

I want to write sample procedure to count the records present in specific tables, here i will fetch the table name s from the text file.
Fo this i just write sample procedure to fetch th table names from text file and storing in tem table but while i am assigning and passing the table name i am unable to do it can any one suggest how to do it by simple example

You can build dynamic sql using table name parameter and execte it using EXEC as shown below.
Create procedure Proc1
#TableName varchar(MAX)
as
..
...
DECLARE #sqltxt varchar(1000)
select #sqltxt = 'select count(*) from ' + quotename(#TableName)
exec (#sqltxt)
...
...

Related

How to create a simple stored procedure with table name as an input

I am using SQL Server 2017 and I would like to create a stored procedure with a single table name as an input variable. All I want the procedure to do is update that table in a variety of ways. This project will be done twice a year, and the columns will always be the same, so I would like to try this as a stored procedure, so I do not have to highlight several lines of code and executing each time.
Is there a simple way to pass a table name through a stored procedure which updates the table (adding columns, calculating columns, replacing nulls in columns etc). In a basic example, one task would be just replaces nulls with 0s in a column. I am not sure how to set this up though. DO I have to declare every column in the table too?
CREATE PROCEDURE updteleform
#tablename TABLE
AS
BEGIN
UPDATE #tablename
SET Recog = 0
WHERE Recog IS NULL
END
GO
I'm assuming you want to update a physical table. SQL Server table variables don't work that way, rather they are a way to pass a transient result set to a stored procedure. There is no persistence if your stored procedure does not do so.
If you are looking to update the same table, then just write the procedure to work on that table.
If you are looking to update multiple tables using the same script then you should change your procedure to accept a string parameter that would be the name of the table you want it to work on and then use dynamic SQL in your stored procedure.
Something like
CREATE PROCEDURE updteleform #tablename sysname
AS
BEGIN
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'
update ' + QUOTENAME(#tablename) + '
set Recog= 0
where Recog is null;';
EXEC sp_executesql #sql;
END
GO
And then call it with something like:
EXEC updteleform #tablename = 'table1';
EXEC updteleform #tablename = 'table2';
EXEC updteleform #tablename = 'table3';
...

How to divide the input of a variable when it reaches its maximum length

I am writing a procedure which takes the body of other procedures and
stores them locally in my device as a text file.
It works correctly except when I am using a large procedure in which case it will be truncated. Note am using nvarchar(max) .
Any suggestion to solve the problem?
This is part of procedure :
DECLARE #V_STRING NVARCHAR(MAX)=''
DECLARE #V_Table TABLE (ID INT IDENTITY(1,1),LINE NVARCHAR(MAX))
IF #V_TYPE ='P'--PROCEDURES
BEGIN
SET #V_PATH=#V_PATH+'4.PROCEDURES'
EXECUTE SP_CreateFolder #V_PATH,#P_DataBase
SET #V_TYPE='\CREATE PROCEDURES'+'.sql'
SET #V_STRING='USE ['+#P_NewDB+'];
GO
IF EXISTS (SELECT name from sys.objects where name='''+#P_ObjectName+''' AND TYPE=''P'')
BEGIN
DROP PROCEDURE ' +#P_ObjectName +'
END
GO'
END
SET #V_CheckType='USE '+#P_DataBase+'; EXECUTE SP_HELPTEXT '+#V_Objec --#v_object refer to the name of procedure and #P_DataBase refer to database which the procedure belong
INSERT INTO #V_Table (LINE)--get the body of given object and store in variable table by using sp_HELPTEXT dictionary
EXECUTE (#V_CheckType)
INSERT INTO #V_Table (LINE)
VALUES (' GO ')
SELECT #V_STRING=#V_STRING+LINE FROM #V_Table
Execute SP_WriteToFile #V_PATH , #V_STRING --this procedure will create a text file in the path just created
sp_helptext returns multiple rows of 255 characters each (if the definition is over 255 characters);
Try using sys.sql_modules or OBJECT_DEFINITION instead, the definitions will be in a single row then, and much easier to work with:
SET #V_STRING='USE ['+#P_NewDB+']';
SET #V_CheckType='USE '+#P_DataBase+'; select definition from sys.sql_modules where object_id = object_id('''+#V_Objec + ''')' --#v_object refer to the name of procedure and #P_DataBase refer to database which the procedure belong
INSERT INTO #V_Table (LINE)--get the body of given object and store in variable table by using sp_HELPTEXT dictionary
EXECUTE (#V_CheckType)
SELECT #V_STRING=#V_STRING+LINE + CHAR(10) + 'GO' FROM #V_Table
--SELECT #V_STRING
Execute SP_WriteToFile #V_PATH , #V_STRING

SQL column value to table name

In my SQL database, I would like to make a general purpose soft link table. Perhaps something similar the following:
create table soft_link(
id uniqueidentifier,
name varchar(255),
LINK uniqueidentifier,
TABLE varchar(255),
primary key(id));
Say I have object "b_object" in some other table in the database. The LINK column would be the the unique identifier of b_object, and TABLE would be the table in which b_object is stored within the database.
Now I want to make a single stored procedure "sp_ResolveSoftLink". This method will take an id of a soft link, look up the LINK and TABLE columns of the soft link, and then use the TABLE and LINK to query for b_object.
The following is NOT proper SQL syntax, but hopefully it helps illustrate my question. I want to combine these two queries into a single stored procedure and return the result of the second query:
select LINK, TABLE from soft_link where id = xxxxxx
select * from TABLE where id = LINK
-- return the result of the second select query
FUNDAMENTAL QUESTION: How/can I use the varchar return from one query to form another query in the same stored procedure in SQL?
You can create a Stored procedure like this.
Here, First you have to store value of LINK and Table in variable and then use these variable to form another Dynamic Query
CREATE PROC spName
#id INT
AS
BEGIN
Declare #LINKValue uniqueidentifier, #TABLE varchar(255),#SQL varchar(max)
SELECT #LINKValue = LINK , #TABLE = TABLE
FROM soft_link
WHERE soft_link id = #id
SET #SQL='SELECT * FROM';
SET #SQL = #SQL +' ' + #TABLE
SET #SQL = #SQL +' ' + 'WHERE ID =' +' ' + #LINKValue
PRINT #SQL -- SEE Here This is what you actually Want
--EXEC (#SQL) --Then Execute this
END

sql server - fill results from executed query string in a temp table dynamically

I'm writing a stored procedure. I have a string which contains an sql query. For example:
DECLARE #sql nvarchar(max)
SET #sql = (N'SELECT pkOrderID FROM Orders')
(Just to note: this isn't what the select statement looks like. This is just an example of what I mean) I then want to execute the string and put the result in a temporary table E.g. #tempTable. I know EXEC(#sql) exists but not sure if it will do me any good in this situation. The other twist is that I do not know the names of all the columns in the returned #sql so the temp table #tempTable needs to be created dyanmically based off the return from #sql. Thanks for any help.
I think you could use SELECT INTO to do what you want but it would mean updating your string:
DECLARE #sql nvarchar(max)
SET #sql = (N'SELECT frompkOrderID INTO #tmporders FROM Orders')
then you should be able to run EXEC #sql to create the table
more information about SELECT INTO here : http://msdn.microsoft.com/en-au/library/ms188029.aspx
There is no simple way to do this. The problem with #JanR's solution is that the #tmporders table will be out of scope to the script that calls your stored procedure (ie It will produce an error like "Invalid object name '#rtmporders'"
One alternative is to use a global temp table (eg ##tmporders).
So your SP might look like this:
CREATE PROCEDURE TestSP
AS
BEGIN
SELECT pkOrderID INTO ##tmporders FROM Orders
END
GO
And the calling script might be like:
EXEC TestSP
SELECT * FROM ##temporders

How to pass schema as parameter to a stored procedure in sql server?

I have a stored procedure to select a list of data based on two tables. The first table is a fixed one: CO.Country. But the second table can be one of a number of tables. The name of the table itself is the same: Location. But, the schema of the tables are different: ABD.Location, CGA.Location, GBN.Location.
The user will select the schema from the application, then the schema chosen will be passed to the stored procedure as a parameter.
But there's an error when I parse the stored procedure while creating it.
Is there anyway to pass the schema name as a parameter?
Use DynamicSql
Try like this
CREATE PROCEDURE proc_name
#schema VARCHAR(25)
AS
DECLARE #Query VARCHAR(1000)
SET #query='SELECT * FROM ' +#schema +'.Location'
EXECUTE(#query)