How to insert a sql script in a table column?
I have a table column which has ntext datatype. I will have to insert the whole function or stored procedure in the column.
Giving an example : sp_helptext 'sp_TestProcedure' will return the complete syntax of a stored procedure. How to populate the stored procedure script in a Table.
I can change the data type either ntext or nvarchar(max). Actual question is , how to insert the script in a column ?
This is not an insert of stored procedure result. This script which i am looking for is to insert the actual stored procedure (or) function (or) view in a table
You could take a look at sys.sql_modules, which contains definitions (code) for database objects.
INSERT INTO [dbo].[some_table] ([schema_name], [object_name], [definition])
SELECT
OBJECT_SCHEMA_NAME([object_id]) [schema_name],
OBJECT_NAME([object_id]) [object_name],
[definition]
FROM sys.sql_modules
WHERE OBJECT_SCHEMA_NAME([object_id]) = 'dbo'
AND OBJECT_NAME([object_id]) = 'some_object'
Update: As others have commented, if the purpose is to maintain version history it may be more effective to use some other source code control solution. Also, if you want to track any time code in database objects change you could look into implementing a DDL trigger. Just searching "ddl trigger to track schema changes" produced some promising results.
Also, I just stumbled across OBJECT_DEFINITION(), which may be helpful:
SELECT OBJECT_DEFINITION(OBJECT_ID('dbo.spt_values'))
script is text. simply use the regular 'insert into' that sql server has.
when that script is inside a file, you need to read the contents of that file first. the method of doing that depends on the type of language you use - c, c#, java or python (whichever).
if you want to retrieve it, use the normal 'select' command.
however, I do not believe it's a good way of storing functions. being inside a file-system works (usually).
Related
I'm using SSMS and I have a User-Defined Data Type which was created in the early 2000 with a rule object attached to it.
Many tables and stored procedures use this User-Defined Data Type as a type. I want to alter these tables and stored procs to take out this UDT so I can replace them with check constraints, but I'm having trouble identifying all the tables and stored procs in which this UDT is used as a type.
I've been looking at old scripts and using sp_help table_name to seek out these instances, but I was wondering if there's a way to find all the tables/columns and stored procs which use a certain user-defined data type.
Thank you.
EDIT: I figured out how to find all the uses of user-defined data types on tables
SELECT TABLE_NAME, COLUMN_NAME, DOMAIN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DOMAIN_NAME = 'UDT_name'
For stored procedures, I removed my discovered method because NicVerAZ linked a better way to accomplish this below.
Refer to the article below on how to properly search for a string in a stored procedure definition:
Search text in stored procedure in SQL Server
As I posted in a comment above, ROUTINE_DEFINITION is an NVARCHAR(4000) and longer stored procedures have their definition truncated.
Your second method is not bad, it gets it done but yes your first is more correct.
I have a application thas sends an xml into my db2 stored procedure
In SQL Server the stored procedure is written like this:
DECLARE #startWithDiagnosisNumbers xml
SELECT #startWithDiagnosisNumbers = N'<Ids><id>G43</id><id>G44</id></Ids>'
DECLARE #TEMP_CXP_DiagnosisNumbers TABLE (ID nvarchar(50))
INSERT INTO #TEMP_CXP_DiagnosisNumbers (ID)
SELECT ParamValues.ID.value('.','NVARCHAR(50)')
FROM #startWithDiagnosisNumbers .nodes('/Ids/id') as ParamValues(ID)
How do I translate this over to db2?
I have tried this:
BEGIN
DECLARE startWithDiagnosisNumbers XML;
END
but get error message: "The data type for parameter or SQL variable"STARTWITHDIAGNOSISNUMBERS" is not supported in the routine, compound SQL statement, or parameter list of a cursor value constructor."
And I cant find how to translate the INSERT INTO.
I am very grateful for any help :-)
There are some limitations on the use of XML data type, as described in the manual. Make sure you have the latest fix pack for your version and try to write your code as a stored procedure instead of a simple compound SQL statement (a.k.a. anonymous block).
To extract data from the XML document in a table form you can use the XMLTABLE function -- check examples in the manual.
PS. Using SQL Server-centric approaches such as extensive use of temporary tables isn't necessarily the most efficient way of accomplish things in DB2.
Consider this:
CREATE PROCEDURE [dbo].[setIdentifier](#oldIdentifierName as varchar(50), #newIdentifierName as varchar(50))
AS
BEGIN
DECLARE #old_id as int;
DECLARE #new_id as int;
SET #old_id = (SELECT value FROM Configuration WHERE id = #oldIdentifierName);
SET #new_id = (SELECT value FROM Configuration WHERE id = #newIdentifierName);
IF #old_id IS NOT NULL AND #new_id IS NOT NULL
BEGIN
UPDATE Customer
SET type = #new_id
WHERE type = #old_id;
END;
END
[...]
EXECUTE dbo.setIdentifier '1', '2';
What this does is create a stored procedure that accepts two parameters which it then uses to update a Customer table.
The problem is that the entire script above runs within a schema other than "dbo". Let's just assume the schema is "company1". And when the stored procedure is called, I get an error from the SELECT statement, which says that the Configuration table cannot be found. I'm guessing this is because MS SQL by default looks for tables within the same schema as the location of the stored procedure, and not within the calling context.
My question is this:
Is there some option or parameter or switch of some kind that will
tell MS SQL to look for tables in the "caller's default schema" and
not within the schema that procedure itself is stored in?
If not,
what would you recommend? I don't really want to prefix the tables
with the schema name, because it would be kind of unflexible to do
that. So I'm thinking about using dynamic sql (and the schema_name()
function which returns the correct value even within the procedure),
but I am just not experienced enough with MS SQL to construct the
proper syntax.
It would be a tad more efficient to explicitly specify the schema name. And generally speaking, schema's are mainly used to divide a database into logical area's. I would not anticipate on tables schema-hopping often.
Regarding your question, you might want to have a look at the 'execute as' documentation on msdn, since it allows to explicitly control your execution context.
I ended up passing the schema name to my script as a property on the command line for the "sqlcmd" command. Like this:
C:/> sqlcmd -vSCHEMANAME=myschema -imysqlfile
In the SQL script I can then access this variable like this:
SELECT * from $(SCHEMANAME).myTable WHERE.... etc
Not quite as flexible as dynamic sql, but "good enough" as it were.
Thanks all for taking time to respond.
This question already has answers here:
SQL: how to predicate over stored procedure's result sets?
(3 answers)
Closed 6 years ago.
I currently have a stored procedure that runs a complex query and returns a data set. I'd like to cast this data set to a table (on which I can perform further queries) if at all possible. I know I can do this using a table-valued UDF but I'd prefer to avoid that at this point. Is there any way I can accomplish this task?
EDIT: OK... so the SProc I'm using (written by third party and I'm not supposed to change it) runs a fairly complex select statement to return a bunch of line item data about purchase orders. I can recreate it as a UDF but then I'd have to support the UDF and ensure it gets changed as and when our vendor changes their SProc. I'd like to further refine this line item info by a number of criteria such as (but not limited to) item numbers, vendor codes, cost centers, etc. All of this information is brought back by the original SProc and I just need to be able to manipulate it further. My thought process was that if I can somehow treat the results of the SProc as a table (or get them into a table format of some type) then I can run further queries against the original result set to limit by the criteria mentioned above. Please let me know if any further details are needed.
There's various means of sharing data between stored procedures - this link is pretty exhaustive.
But I'm curious why you want a table valued stored procedure (which doesn't exist in SQL Server) when there are table valued functions...
Cast Stored Procedure Result as a
Table?
Yes and this is used quite often. It simply needs one or more select statements:
Create Procedure #Foo
As
Select object_id, name
From sys.columns
That said, you cannot join to this resultset nor can you easily consume it from another stored proc (although there is a way). Given your edit, it appears the question is whether you can consume the results of a stored proc by another stored proc. Technically, yes. You can populate a temp table with the results of a proc. However, you must declare your temp variable or temp table with the same column structure as is returned by the first resultset of the stored proc.
Declare #Data Table ( object_id int, name nvarchar(128) )
Insert #Data
Exec #Foo
Select *
From #Data
(Or use the far more clever OPENROWSET solution as mentioned by Cade Roux and OMG Ponies)
Have you considered using table-valued parameters? They are new in SQL 2008.
-- Edit --
Nope, never mind, they're only good for passing data into stored procedures.
You could try using a View instead of a Stored Procedure. Store your complex query as part of the view, and you have the functionality to perform more queries on the view.
Can we see the values (rows and cells) in a table valued variable in SQL Server Management Studio (SSMS) during debug time? If yes, how?
DECLARE #v XML = (SELECT * FROM <tablename> FOR XML AUTO)
Insert the above statement at the point where you want to view the table's contents. The table's contents will be rendered as XML in the locals window, or you can add #v to the watches window.
That's not yet implemented according this Microsoft Connect link:
Microsoft Connect
This project https://github.com/FilipDeVos/sp_select has a stored procedure sp_select which allows for selecting from a temp table.
Usage:
exec sp_select 'tempDb..#myTempTable'
While debugging a stored procedure you can open a new tab and run this command to see the contents of the temp table.
In the Stored Procedure create a global temporary table ##temptable and write an insert query within your stored procedure which inserts the data in your table into this temporary table.
Once this is done you can check the content of the temporary table by opening a new query window.
Just use "select * from ##temptable"
If you are using SQL Server 2016 or newer, you can also select it as JSON result and display it in JSON Visualizer, it's much easier to read it than in XML and allows you to filter results.
DECLARE #v nvarchar(max) = (SELECT * FROM Suppliers FOR JSON AUTO)
I have come to the conclusion that this is not possible without any plugins.
SQL Server Profiler 2014 lists the content of table value parameter. Might work in previous versions too.
Enable SP:Starting or RPC:Completed event in Stored Procedures group and TextData column and when you click on entry in log you'll have the insert statements for table variable.
You can then copy the text and run in Management Studio.
Sample output:
declare #p1 dbo.TableType
insert into #p1 values(N'A',N'B')
insert into #p1 values(N'C',N'D')
exec uspWhatever #PARAM=#p1
Why not just select the Table and view the variable that way?
SELECT * FROM #d
Sorry guys, I'm a little late to the party but for anyone that stumbles across this question at a later date, I've found the easiest way to do this in a stored procedure is to:
Create a new query with any procedure parameters declared and initialised at the top.
Paste in the body of your procedure.
Add a good old fashioned select query immediately after your table variable is initialised with data.
If 3. is not the last statement in the procedure, set a breakpoint on the same line, start debugging and continue straight to your breakpoint.
Profit!!
messi19's answer should be the accepted one IMHO, since it is simpler than mine and does the job most of the time, but if you're like me and have a table variable inside a loop that you want to inspect, this does the job nicely without too much effort or external SSMS plugins.