Store a Query in SQL Server 2012 - sql-server-2012

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.

Related

how to pass table name as parameter to sql table valued function?

I want to pass the table name as a parameter to table_valued function in MS SQL Server
CREATE FUNCTION maxid
(
-- Add the parameters for the function here
#tblname sysname,
#feild nvarchar(max),
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
select ISNULL(max(#feild),0)+1 from #tblname
)
You cannot use dynamic SQL in table valued or any other TSQL function. However, the code you provide seems to be used to obtain the next value of some identifier or counter field. The way you want to do it is highly deprecated and leads to concurrency problems.
Indeed, SQL Server can do it using at least two standard methods:
using a sequences
creating an identity column
I have done it but with store procedure
CREATE procedure [dbo].[get_maxid]
#tblname nvarchar(max),
#col nvarchar(max)
as
Begin
declare #sql nvarchar(max);
set #sql='select ISNULL(MAX('+#col+'),0)+1 as id from '+ QUOTENAME( #tblname)
execute sp_executesql #sql
End
Now Execute Store Procedure
exec get_maxid #col='col_name',#tblname='tbl_name'

Is there a way to pass all the table names in a database as a parameter for the SP?

I am looking to run validation script across columns for all tables in a database in MS SQL SERVER . My query now is something like this:
CREATE PROCEDURE [dbo].[DDS1718_Validation]
AS
BEGIN
SET FMTONLY OFF
DECLARE #ActualTableName AS NVarchar(255)
SELECT #ActualTableName =QUOTENAME(TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
this however picks output for only one table.
Thank you.
You could use a table valued parameter. Before calling the Sp, populate the table valued parameter with all the table names and then call the sp and pass the parameter just like you would pass an int or a float parameter.
Here is more info : https://learn.microsoft.com/en-us/sql/relational-databases/tables/use-table-valued-parameters-database-engine?view=sql-server-2017
DECLARE #ActualTableName AS varchar(max)
SELECT #ActualTableName = COALESCE(#ActualTableName + ',', '') + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
SELECT #ActualTableName
Now you have all table names, send this #ActualTableName in your stored procedure.
In the stored procedure you can split this table names with ','.
split string in sql

Creating a stored procedure using variables

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.

Where is this function in SQL Server

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

How to query from a stored procedure in SQL Server?

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