Is it possible to set a variable for a stored procedure as column type? - sql

It seems like a simple enough event you just declare a variable you are passing to your stored procedure as column. I am needing to pass a column name to my stored procedure that will be used in my query. Is it possible to declare it so I can use it as a column name or is there some way I can convert say a string to column type?
where Line1AStatus = 1
I need to be able to pass to my stored procedure what that number is in Line Status. I have tried these methods so far. Thank you for your help.
where Line + #LineNum + AStatus = 1
where 'Line' + #LinNum + 'AStatus' = 1

not with standard SQL but you can with dynamic sql
DECLARE #SQL nvarchar(max)
SELECT #SQL = 'SELECT * FROM table where ''Line' + CAST(#LinNum AS NVARCHAR) + 'AStatus'' = 1'
exec sp_executeSQL #sql
Example of a while loop
DECLARE #SQL nvarchar(max), #LinNum int
SELECT #LinNum = 1
WHILE(#LinNum <= 5)
BEGIN
SELECT #SQL = 'SELECT * FROM table where ''Line' + CAST(#LinNum AS NVARCHAR) + 'AStatus'' = 1'
exec sp_executeSQL #sql
SELECT #LinNum = #LinNum + 1
END

Related

SQL Server Stored Procedure : Dynamic database in query

I have a variable which holds the database that I am working on. How can I add this variable in a static query?
This is what I want to achieve:
if exists(select * from #DestinationDB.[RaPa] where tid = #dyid)
begin
RAISERROR('Rapa exist',16,1)
end
I'm not sure if you meant without Dynamic SQL... but here is how you can accomplish this with dynamic SQL
declare #DestinationDB varchar(64)
declare #dyid int
declare #sql varchar(max)
set #DestinationDB = 'SomeDB'
set #dyid = 14
set #sql =
'if exists(select * from ' + quotename(#DestinationDB) + '.[RaPa] where tid = ' + cast(#dyid as varchar(16)) + ')
begin
RAISERROR(''Rapa exist'',16,1)
end'
print #sql
--exec(#sql)
Just uncomment the exec part when you are satisfied with the command.

How to form a table name from concatenating strings in Select Statement in SQL 2012

I want to achieve this -
SELECT * FROM A1234
I have the the ID 1234 saved in another table called Aliases which has two columns Alias,ID with one record like this.
Alias = TestTable, ID = 1234
So I am trying something like this
SELECT * FROM ('A'+ (SELECT ID FROM Aliases WHERE Alias = 'TestTable'))
Any help would be appreciated
You should use dynamic sql.
DECLARE #Q VARCHAR(MAX),#ID INT
SET #ID=(Select DISTINCT ID from Aliases where Alias = 'TestTable') -- CHECK TO RETURN JUST ON RESULT
SET #Q='SELECT * FROM A'+CAST(#ID AS VARCHAR(10))
EXEC(#Q)
You need dynamic SQL for this.
DECLARE #sql NVARCHAR(MAX);
SELECT TOP (1) #sql = N'SELECT * FROM A' + RTRIM(ID) + ';'
FROM dbo.Aliases WHERE Alias = 'TestTable';
EXEC sp_executesql #sql;
To build a set of statements that selects all of them, you can say:
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'';
SELECT #sql = #sql + N'
SELECT *, ''A' + RTRIM(ID) + ''' FROM A' + RTRIM(ID) + ';'
FROM dbo.Aliases;
PRINT #sql;
-- EXEC sp_executesql #sql;

Select from table with dynamic compute name

I want to write query in which name table will dynamicaly compute. I have code like this below. What should I put in 'magic code' region?
DECLARE #myTableName nvarchar(100) = 'sch'
+ CAST(#nowYear as VARCHAR(5))
+ 'Q'
+ CAST(#nowQuarter as VARCHAR(3))
+ '.[tVisits]'
-- magic code --
myTable = DoSomething(#aktTableName)
-- magic code --
SELECT * FROM myTable
I use MS SQL Server 2012
You need use the dynamic SQL -
DECLARE
#nowYear INT = 2013
, #nowQuarter INT = 1
DECLARE #myTableName NVARCHAR(100) = '[sch'
+ CAST(#nowYear AS VARCHAR(5))
+ 'Q'
+ CAST(#nowQuarter AS VARCHAR(3))
+ '].[tVisits]'
DECLARE #SQL NVARCHAR(MAX) = N'SELECT * FROM ' + #myTableName
EXEC sys.sp_executesql #SQL
Instead of SELECT * FROM myTable
You need to do something like
DECLARE #sql nvarchar(4000)
SELECT #sql = ' SELECT * FROM ' + #myTable -- #myTable is a string containing qualified table name
EXEC sp_executesql #sql
Note that sp_executesql allows for a parameterized query - check its documentation

SQL query not showing columns in DataSet in Visual Studio

I have a stored procedure in SQL Server 2008. I declare an #query param via DECLARE #query NVARCHAR(MAX), I then set this #query according to the type of data sent in and then I use exec [sys].[sp_executesql] #query to execute the stored procedure.
The problem I'm having is that I'm using a DataSet in Visual Studio, that links to this stored procedure (used on a report).
When I do my stored procedure in this manner (with the #query), then the dataset does not pick up the column data to show. I had to create the stored procedure this way (with #query), because I need the where clause to be different depending on the data sent in.
My code:
CREATE PROCEDURE [dbo].[p_Test_GetFooData]
#pName VARCHAR(250) = '',
#pID INT = NULL
AS
BEGIN
DECLARE #query NVARCHAR(MAX)
SET #query = 'SELECT FOO.FirstName, FOO.LastName
FROM Test.FooOne AS FOO'
IF ( #pName = '--- SELECT ---' )
BEGIN
SET #query = #query + ' WHERE FOO.ID = '
+ CONVERT(VARCHAR(50), #pID) + ''
END
ELSE
BEGIN
SET #query = #query + ' WHERE FOO.ID = '
+ CONVERT(VARCHAR(50), #pID) + ' AND
PP.FirstName + LIKE ''%' + #pName
+ '%'' '
END
EXEC [sys].[sp_executesql] #query
END
I have tested the query and it returns the correct data when I run the stored procedure. When I don't use SET #query = 'SELECT STATEMENT' EXEC #query then the dataset works as it should.
Any help will be appreciated.
Another option is to write the query in a different way eg.
SELECT FOO.FirstName,
FOO.LastName
FROM Test.FooOne AS FOO
WHERE FOO.ID = #pID
and PP.FirstName LIKE case when #pName = '--- Select ---' then PP.FirstName else '%' + #pName + '%' end
This will always compare Foo.ID to #pID
and will either compare pp.FirstName to itself (always returning true) or wil

Using Dynamic SQL in User Defined Function to return string (not modify data)

Our document storage application has a unique database for each of our clients which are almost identical to each other, but one table DocumentIndexes is unique for each client and can have any number of columns and types.
I am trying to create a generic function (within our "master" database called MYAPP_MASTER) that I can call and simply pass in a database name and a document ID value and get back the column names and values from from the specified database's DocumentIndexes table. Because I have to pass in the database name, I have to generate the selection SQL dynamically and call sp_executesql.
I have the following code which polls the INFORMATION_SCHEMA.COLUMNS table to determine the columns needed and it works just fine in a stored procedure, but I hate having to copy all this code in every stored procedure that needs these to retrieve these dynamic column values. I would rather have one function that returns the string value of these columns regardless of database and have the function exist once in our MYAPP_MASTER database. Again, this code works, but SQL won't allow me to put it into a function. Is there anyway around this?
USE MYAPP_MASTER
GO
DECLARE #DatabaseName varchar(255)
DECLARE #DocumentId int
SET #DatabaseName = 'SAMPLE_CLIENT_DB'
SET #DocumentId = 1234
DECLARE #DynamicIndexes nvarchar(max)
DECLARE #DynamicIndexesParam nvarchar(max)
DECLARE #DynamicIndexesSql nvarchar(max)
SET #DynamicIndexesParam = '#Indexes varchar(max) OUTPUT'
SET #DynamicIndexesSql = 'SELECT #Indexes = COALESCE(#Indexes + ''+ '''', '', '''') + CAST(COLUMN_NAME as varchar(max)) + '': '''''' + '' + CASE WHEN DI.'' + COLUMN_NAME + '' IS NOT NULL THEN CAST(DI.'' + COLUMN_NAME + '' as varchar(max)) ELSE '''''''' END '' FROM ' + #DatabaseName + '.INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''DocumentIndexes'' AND COLUMN_NAME <> ''DocumentID''; '
EXEC sp_executesql #DynamicIndexesSql, #DynamicIndexesParam, #Indexes = #DynamicIndexes OUTPUT
SET #DynamicIndexes = '''' + #DynamicIndexes
DECLARE #SelectionSql nvarchar(max)
SET #SelectionSql = 'SELECT ' + #DynamicIndexes + ' as DocumentIndexes FROM ' + #DatabaseName + '..Document D LEFT OUTER JOIN ' + #DatabaseName + '..DocumentIndexes DI ON D.DocumentId = DI.DocumentId WHERE D.DocumentID = ' + CAST(#DocumentId as varchar(10))
EXEC sp_executesql #SelectionSql
If the SAMPLE_CLIENT_DB datababase DocumentIndexes table has columns for Name, Office and Classification, this code will return a simple string that looks like the following:
Name: Foo, Office: Bar, Classification: 123
You can't run an Exec command inside a SQL function, but you could use a stored procedure with an output variable assuming the DocumentIndexes table is unique at the DocumentID level.
Create Proc DocID_DocIndexes #retval Varchar(Max) Output
As
...
(Your code logic minus last two lines)
...
-- Populate your dynamic SQL into a variable to assign it to the output variable
SET #SelectionSql = 'SELECT #result = ' + #DynamicIndexes + ' as DocumentIndexes FROM ' + #DatabaseName + '..Document D LEFT OUTER JOIN ' + #DatabaseName + '..DocumentIndexes DI ON D.DocumentId = DI.DocumentId WHERE D.DocumentID = ' + CAST(#DocumentId as varchar(10))
EXEC sp_executesql #SelectionSql, N'#result Varchar(Max) Output', #result = #retval Output
Return