I can see this in a query within an application (I'm assuming where I have 'functionName' that it's actually a function:
functionName #oldServer='[*servername*]',#newServer='[*servername*]'
When I look for custom functions in the database that this is running against (by doing this):
USE *databaseName*
GO
SELECT
name AS function_name
,SCHEMA_NAME(schema_id) AS schema_name
,type_desc
FROM
sys.objects
WHERE
type_desc LIKE '%FUNCTION%';
GO
I don't find any function called 'functionName'. What am I not understanding?
Try
SELECT
*
FROM
INFORMATION_SCHEMA.ROUTINES
WHERE
ROUTINE_NAME LIKE '%function%'
An important thing to remember is whether you have a CASE SENSITIVE collation or a CASE INSENSITIVE collation. If you have the first then you need to ensure that query is using the correct case for the function name etc.
Here is an example I just created on my machine:
USE [tempdb]
GO
DROP FUNCTION [dbo].[TestFunction]
GO
CREATE FUNCTION [dbo].[TestFunction]
(
#Parameter1 INT,
#Parameter2 INT
)
RETURNS INT
AS
BEGIN
-- Declare the return variable here
DECLARE #ret INT
-- Add the T-SQL statements to compute the return value here
SELECT #ret = #Parameter1 + #Parameter2
-- Return the result of the function
RETURN #ret
END
GO
select dbo.TestFunction(1, 2);
SELECT
*
FROM
INFORMATION_SCHEMA.ROUTINES
WHERE
ROUTINE_NAME like '%function%'
The output is
Related
I need to alter a function only if it exists. I tried this:
IF EXISTS(SELECT * FROM Information_schema.Routines
WHERE Specific_schema = 'dbo'
AND SPECIFIC_NAME = 'fnTestFunc'
AND Routine_Type = 'FUNCTION')
BEGIN
ALTER FUNCTION [dbo].[fnTestFunc] (#input VARCHAR(3))
RETURNS VARCHAR(2)
AS
BEGIN
--something
END
END
But shows an error
ALTER FUNCTION must be the single query in the batch
Any idea what is the issue here?
You have to make sure it's compiled and executed in a separate batch. The easiest way here is via sp_executesql:
IF EXISTS(SELECT * FROM Information_schema.Routines WHERE Specific_schema = 'dbo' AND SPECIFIC_NAME = 'fnTestFunc' AND Routine_Type = 'FUNCTION')
BEGIN
EXEC sp_executesql N'ALTER FUNCTION [dbo].[fnTestFunc] (#input VARCHAR(3))
RETURNS VARCHAR(2)
AS BEGIN
--something
END'
END
This also avoids another problem - SQL Server wants to compile each batch before it starts executing it. But it'd fail to compile your original batch if fnTestFunc doesn't exist. You can't use a runtime check (the IF) to avoid a compile time error - unless you make sure, as above, that the compilation happens after the check is completed.
while creating or Altering a Function or stored procedure in SQL Server it's mandatory that the Create / Alter Statement should be the first in that batch.
In your scenario, you can try another approach.
Create a Dummy Function / Procedure in the first batch
Alter the Procedure/function with your actual logic
Since while altering functions, you can't modify the Return types of the Function, make sure to use the same return type while creating the Dummy function.
Use the Batch Separator GO so differentiate between batches
Example
IF OBJECT_ID('dbo.FnMyFunction') IS NULL
BEGIN
EXEC('CREATE FUNCTION dbo.FnMyFunction() RETURNS INT AS RETURN 0')
END
GO
ALTER FUNCTION dbo.FnMyFunction()
RETURNS INT
AS
BEGIN
<Your Code Goes here>
END
GO
If you have SQL Server 2016 SP1+, you can skip IF checks and it can be as simple as:
CREATE OR ALTER FUNCTION fnTest()
RETURNS INT
AS
BEGIN
RETURN (1);
END;
GO
https://blogs.msdn.microsoft.com/sqlserverstorageengine/2016/11/17/create-or-alter-another-great-language-enhancement-in-sql-server-2016-sp1/
How do I store a Query in SQL Server 2012 that can be inserted based on a key word?
select * from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME like '%%' order by TABLE_NAME
This Query Has to be inserted in query window when i type csearch and press ctrl+Space or tab replacing csearch
You can create SQL functions and stored procedures in your database. These functions can be called when needed.
CREATE FUNCTION CSEARCH
(
-- Add the parameters for the function here
<#Param1, sysname, #p1> <Data_Type_For_Param1, , int>
)
RETURNS <Function_Data_Type, ,int>
AS
BEGIN
-- Declare the return variable here
DECLARE <#ResultVar, sysname, #Result> <Function_Data_Type, ,int>
-- Add the T-SQL statements to compute the return value here
SELECT <#ResultVar, sysname, #Result> = <#Param1, sysname, #p1>
-- Return the result of the function
RETURN <#ResultVar, sysname, #Result>
END
GO
In this case, replace the SELECTwith your query and run this script.
It will be saved in your database and can be altered by replacing CREATE FUNCTIONwith ALTER FUNCTION.
To call this function, create a simple SQL Connection in your Code and select it like this:
SELECT CSEARCH(param1, param2, ...) AS Function
The returned value will be that one you declared inside your function.
You can create a procedure , and then assign it to a hotkey at SSMS.
IF EXISTS(SELECT TOP 1 1 FROM sys.objects WHERE name = 'sp_SelectAllTablesLike')
DROP PROCEDURE sp_SelectAllTablesLike
GO
CREATE PROCEDURE sp_SelectAllTablesLike
#TableName VARCHAR(256)
AS
BEGIN
SELECT * FROM INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME like '%' + #TableName + '%' ORDER BY TABLE_SCHEMA, TABLE_NAME
END
GO
(here a longer explanation regarding how to add a procedure to SSMS hotkeys https://www.sqlshack.com/custom-keyboard-shortcuts-in-sql-server-management-studio-ssms/)
Restart SSMS.
Then, every single time you press Ctrl+3 (or wherever you put it) it will execute that procedure. If you have a selection, automatically it will bind it with the input parameter.
The downside, is that you need to create the procedure at any DB you work with.
Is there any good way to do this, or am I just heading in the wrong direction? I would like to create a stored procedure inside an SQL script. I would like to have variables declared at the beginning of the script so that I can create the SPROCs to use in different contexts/servers.Here is what I would like to do (I know this obviously doesn't work, but I'm looking for any ideas of an alternative)..
DECLARE #golbalValue = 'SomeValue'
GO
CREATE PROCEDURE [dbo].[MyStoredProcedure](
AS
BEGIN
SELECT * FROM Mytable WHERE MyCol = #globalValue
END
GO
What you could do is use a scalar function for the variable
create function f ()
returns varchar(20)
as
begin
return 'some value'
end
go
then use it in your procedure
create proc p ()
as
begin
select *
from my_table
where col = f()
end
go
another possibility which is perhaps more appropriate is to use sqlcmd here's an example.
From what I understand, you need to create stored procedures with set value from your parameters. You don't want input parameters in the stored Procedures though. Second, you want to switch database contexts. So I think you'll need a tempTable for your parameters and some dynamic SQL. Try this out:
IF OBJECT_ID('tempdb..#globalParam') IS NOT NULL
DROP TABLE #globalParam;
IF OBJECT_ID('AdventureWorks2012.dbo.myTable') IS NOT NULL
DROP TABLE AdventureWorks2012.dbo.myTable
IF OBJECT_ID('Master..myTable') IS NOT NULL
DROP TABLE Master..mytable
--Create your data tables
SELECT 'SomeValue' AS col1 INTO AdventureWorks2012.dbo.myTable;
SELECT 1000 AS col1 INTO master.dbo.myTable;
CREATE TABLE #globalParam(
ParamName VARCHAR(100),
val SQL_VARIANT --SQL_Variant is designed to hold all data types.
);
--Here are your globalParams
DECLARE #globalParam1 VARCHAR(100) = 'SomeValue';
DECLARE #globalParam2 INT = 1000;
--Load your parameters into a table. Might have to cast some of your parameters to SQL_Variant
INSERT INTO #globalParam
VALUES ('globalParam1',#globalParam1),
('globalParam2',CAST(#globalParam2 AS sql_variant));
GO
--Switch database context
USE AdventureWorks2012
GO
--Variable to hold CREATE PROC
DECLARE #sql VARCHAR(MAX);
--Set #SQL with parameter value from #globalParam
SELECT #sql =
'CREATE PROCEDURE dbo.myStoredProc AS
BEGIN
SELECT * FROM myTable WHERE col1 = ''' + CAST(val AS VARCHAR(100)) + '''
END'
FROM #globalParam
WHERE ParamName = 'globalParam1'
--Execute to create the stored procedure
EXEC(#sql)
--Execute it to see if it works
EXEC dbo.myStoredProc
--Switch context. Repeat same steps
USE master
GO
DECLARE #sql VARCHAR(MAX);
SELECT #sql =
'CREATE PROCEDURE dbo.myStoredProc AS
BEGIN
SELECT * FROM myTable WHERE col1 = ''' + CAST(val AS VARCHAR(100)) + '''
END'
FROM #globalParam
WHERE ParamName = 'globalParam2'
EXEC(#sql)
EXEC dbo.myStoredProc
--Cleanup
DROP PROCEDURE dbo.myStoredProc;
USE AdventureWorks2012
GO
DROP PROCEDURE dbo.myStoredProc;
You cannot do what you want. T-SQL doesn't have the concept of global variables. One method is to store values in a "global" table and then reference them as needed. Something like:
create table GlobalParams (
name varchar(255) not null primary key,
value varchar(255) not null
);
create procedure . . .
begin
. . .
declare #value varchar(255);
select #value = value from Globalparams where name = 'name';
select *
from Mytable
where MyCol = #value;
. . .
end;
Note: this is a simplistic example that only allows variables whose type is a string.
You can also wrap the logic in a user-defined function, so the call looks like:
select *
from Mytable
where MyCol = udf_GlobalLookup('name');
It is rather rare to need global parameters that are shared among different stored procedures. Such a global context can be useful, at times, for complex systems. It is unlikely that you need all this machinery for a simple application. An alternative method, such as just passing the parameters in as arguments, is probably sufficient.
Not sure how to implement this, but I need a way to get the current list of parameters for a stored procedure as well as their passed in values (this code will be executed in the stored procedure itself).
I know I can use sys.parameters to get the parameter names, but how to get the actual values?
What I need to do with this is to make a char string of the form
#param_name1=#value1,#param_name2=#value2,...,#param_namen=#valuen
I have tried to use dynamic sql, but not having much joy with that.
Any ideas??
Edit:
Currently I am just going through all the parameters one-by-one to build the string. However I want a "better" way to do it, since there are quite a few parameters. And incase parameters are added later on (but the code to generate the string is not updated).
I tried using dynamic sql but gave up, since the sp_executesql sp requires parameters be passed into it...
You state '(this code will be executed in the stored procedure itself).' so assuming you are in the procedure you will already know the parameter names as you have to declare them when creating your procedure. Just do a select and put the names inside text fields
ALTER PROCEDURE procname
(
#param1 NVARCHAR(255)
,#param2 INT
...
)
SELECT [Parameters] = '#param1=' + #param1
+ ',#param2=' + CONVERT(NVARCHAR(MAX),#param2)...
The CONVERT is there as an example for non-char datatypes.
update
You will need to create a linked server that points to itself to use the OPENQUERY function.
USE [master]
GO
/****** Object: LinkedServer [.] Script Date: 04/03/2013 16:22:13 ******/
EXEC master.dbo.sp_addlinkedserver #server = N'.', #srvproduct=N'', #provider=N'SQLNCLI', #datasrc=N'.', #provstr=N'Integrated Security=SSPI'
/* For security reasons the linked server remote logins password is changed with ######## */
EXEC master.dbo.sp_addlinkedsrvlogin #rmtsrvname=N'.',#useself=N'True',#locallogin=NULL,#rmtuser=NULL,#rmtpassword=NULL
GO
Now you can do something like this cursor to get each parameter name and then use dynamic sql in OPENQUERY to get the value:
DECLARE curParms CURSOR FOR
SELECT
name
FROM sys.parameters
WHERE OBJECT_ID = OBJECT_ID('schema.procedurename')
ORDER BY parameter_id
OPEN curParms
FETCH curParms INTO #parmName
WHILE ##FETCH_STATUS <> -1
BEGIN
SELECT #parmName + '=' + (SELECT * FROM OPENQUERY('linkedservername','SELECT ' + #parmName))
FETCH curParms INTO #parmName
END
CLOSE curParms
DEALLOCATE curParms
Since SQL Server 2014 we have sys.dm_exec_input_buffer, it is a table valued function with an output column event_info that gives the full execution statement (including parameters).
We can parse the param values from sys.dm_exec_input_buffer and get the param names from sys.parameters and join them together to get the string you want.
For example:
create procedure [dbo].[get_proc_params_demo]
(
#number1 int,
#string1 varchar(50),
#calendar datetime,
#number2 int,
#string2 nvarchar(max)
)
as
begin
-- get the full execution statement
declare #statement nvarchar(max)
select #statement = event_info
from sys.dm_exec_input_buffer(##spid, current_request_id())
-- parse param values from the statement
declare #proc_name varchar(128) = object_name(##procid)
declare #param_idx int = charindex(#proc_name, #statement) + len(#proc_name)
declare #param_len int = len(#statement) - #param_idx
declare #params nvarchar(max) = right(#statement, #param_len)
-- create param values table
select value, row_number() over (order by current_timestamp) seq
into #params
from string_split(#params, ',')
-- get final string
declare #final nvarchar(max)
select #final = isnull(#final + ',','') + p1.name + '=' + ltrim(p2.value)
from sys.parameters p1
left join #params p2 on p2.seq = parameter_id
where object_id = ##procid
select #final params
end
To test it:
exec get_proc_params_demo 42, 'is the answer', '2019-06-19', 123456789, 'another string'
Returns the string you want:
#number1=42,#string1='is the answer',#calendar='2019-06-19',#number2=123456789,#string2='another string'
I have something similar wrapped as a UDF. I use it for error logging in catch blocks.
Let say I have a simple Stored Procedure:
ALTER PROCEDURE [dbo].[myProc]
AS
BEGIN
SELECT * FROM myTable
END
How can I do a WHERE statement in Microsoft SQL Server Management Studio to the stored procedure? Something like that:
SELECT * FROM myProc WHERE x = 'a'; -- But that doesn't work...
It sounds like you're trying to make a "dynamic" stored procedure.
Something you might want to do is:
1) Insert the contents of your stored procedure into a temporary table
2) Use dynamic sql to apply a where condition to that temporary table.
Something like:
declare #as_condition varchar(500); --Your condition
create table #a
(
id bigint
)
insert into #a
execute sproc
declare #ls_sql varchar(max);
set #ls_sql = "select * from #a where " + #as_condition;
execute (#ls_sql);
SQL Server allows you to use INSERT INTO to grab a stored procedure's output. For example, to grab all processes with SPID < 10, use:
create table #sp_who (
spid smallint,
ecid smallint,
status nchar(30),
loginame nchar(128),
hostname nchar(128),
blk char(5),
dbname nchar(128),
cmd nchar(16),
request int)
insert into #sp_who execute sp_who
select * from #sp_who where spid < 10
You can't add a WHERE clause to a stored procedure like this.
You should put the clause in the sproc, like this:
ALTER PROCEDURE [dbo].[myProc]
#X VARCHAR(10)
AS
BEGIN
SELECT * FROM myTable WHERE x=#X
END
GO
The syntax for calling a stored procedure is through the use of EXECUTE not SELECT(e.g.):
EXECUTE dbo.myProc 'a'
I think you can't do that.
The command to execute a stored procedure is EXECUTE.
See some more examples of the EXECUTE usage.
I think its better to use a view or a table valued function rather than the suggested approach. Both allow you to pass parameters to the function
If you want the WHERE clause to be something you can "turn off" you can do this, passing in a predetermined value (e.g. -1) if the WHERE limitation is to be bypassed:
ALTER PROCEDURE [dbo].[myProc]
#X VARCHAR(10)
AS
BEGIN
SELECT * FROM myTable WHERE x=#X or #X = -1
END
GO
You must declare a variable in the store procedure which will be necessary to pass to run the stored procedure. Here is an example. Keep this in mind: Before AS you can simply declare any variable by using the # character, but after the AS you must write Declare to declare any variable, e.g., Declare #name nvarchar (50).
ALTER PROCEDURE [dbo].[myProc]
#name varchar (50)
AS
BEGIN
SELECT * FROM myTable
where name= #name
END