Run SQL pre-defined function stored in table - sql

I have a table which stores a SQL predefined function, like CONVERT(VARCHAR(10), '2012-08-21 00:16:41.993', 101) in a row/column. While retrieving the result from table, it should run the function and give the final outcome as "2012-08-21", instead right now it returns the same function statement. I am running select (select RunDate from RunDate) and using SQL server database.
Kindly help!!

You need to use dynamic SQL for this. You can't just nest expressions and have SQL evaluate the output...
DECLARE #x TABLE(sql NVARCHAR(255));
INSERT #x(sql) SELECT N'CONVERT(VARCHAR(10), ''2012-08-21 00:16:41.993'', 101)';
DECLARE #sql NVARCHAR(MAX);
SELECT #sql = N'SELECT ' + sql FROM #x;
EXEC sp_executesql #sql;

It would look like this (adjust accordingly):
DECLARE #predef VARCHAR(1000);
DECLARE #sqlquery VARCHAR(1000);
SELECT #predef = (SELECT top 1 Value FROM Parameters Where Name = 'MYFUNC');
SET #sqlquery = 'select ' + #predef + ' from SomeTable';
EXECUTE ( #sqlquery );
One tip: here be dragons. Beware of SQL Injection.

Related

Insert data into a table from Open Query with variable

I am trying to using OPENQUERY to pull some data into a table. Here's what my code looks like:
DECLARE #TSQL VARCHAR(MAX)
DECLARE #CD VARCHAR(10) = 'XX'
DECLARE #OracleData TABLE (Cd VARCHAR(20), ApptDATE Datetime )
INSERT INTO #OracleData(Cd,ApptDATE )
SELECT #TSQL = 'SELECT * FROM OPENQUERY(LinkedServer,''Select p.Cd, p.AppDate
from ta.table1 p
where p.IdCode = ''''' + #CD + ''''''')'
EXEC (#TSQL)
I end up with the following error:
An INSERT statement cannot contain a SELECT statement that assigns
values to a variable.
When I attempt to run the EXEC(#TSQL) without the INSERT it works like a charm, but I am unable to do an insert.
Any ideas how I can possibly resolve this?
Thanks.
You are doing this the wrong way round.
Don't insert the #TSQL variable into your table, set the variable, then insert the results using INSERT...EXEC...
DECLARE #TSQL nvarchar(max) = '
SELECT *
FROM OPENQUERY(LinkedServer,
''Select p.Cd, p.AppDate
from ta.table1 p
where p.IdCode = ''''' + #CD + ''''''')
';
INSERT INTO #OracleData (Cd, ApptDATE)
EXEC (#TSQL);
I'm sure there is an excellent reason you are not just using a straight Linked Server query without dynamic SQL, but I can't think of one.

How to pass table name dynamically to the stored procedure or a simple SQL query, then store the results in a variable?

How to pass table name dynamically to the stored procedure or a simple SQL query, then store the results in a variable?
You may looking for something like this ?
USE [master]
GO
DECLARE #sql NVARCHAR(2000)
DECLARE #TableName NVARCHAR(100) ='sys.tables'
DECLARE #RecordCount INT
SET #sql = N' SELECT #RecordCountOut = COUNT(*)
FROM ' + #TableName + ' AS t'
EXEC sp_executesql #sql, N'#RecordCountOut INT OUTPUT', #RecordCountOut = #RecordCount OUTPUT
SELECT #RecordCount
You could stored your SQL query result in this way
DECLARE #Result NVARCHAR(MAX)
SELECT #Result = COLUMN FROM TableName
however, you could use print command to check what the query return
print #Result

Changing my statement to work in a SQL function

I wanted to create a view using my SQL statement but found out you can't use declare in a view. So I was trying to create a function so my view could just call it
This is the SQL statement
--Declare necessary variables
DECLARE #SQLQuery AS NVARCHAR(255)
DECLARE #Pivot AS NVARCHAR(255)
--Get unique values of pivot column
SELECT #Pivot = COALESCE(#Pivot + ',','') + QUOTENAME(Stage)
FROM
(SELECT DISTINCT Stage
FROM [dbo].[F_Work_Order_Summary]) AS Pivot
--Create the dynamic query with all the values for
--pivot column at runtime
SET #SQLQuery = N'SELECT *
FROM [dbo].[F_Work_Order_Summary]
PIVOT(SUM(Time_In_Stage)
FOR Stage IN (' + #Pivot + ')) AS P'
--Execute dynamic query
EXEC sp_executesql #SQLQuery
Was wonder if anyone could help or knows a better way to use this statement with a view.
Thanks

sql server select rows into string

I have the following query.
declare #column_names varchar(1000)
declare #result varchar(1000)
set #column_names='id,firstname,lastname,age,city,country'
set #result=''
select #result=#result+#column_names +','+from studenttable where id='1'
But this query returns id,firstname,lastname,age,city,country as result
and not like 1,john,j,21,newyork,us.
How to change query so that #result will contain actual entries in comma-separated form?
Please reply. Thanks.
To execute dynamic T-SQL statements use sp_executesql as:
EXECUTE sp_executesql
N'SELECT ' +#column_names +' FROM studenttable
WHERE id= #id',
N'#id tinyint',
#id= 1;

Stored procedure to find number of rows in a table

In a stored procedure I pass a table name as the input variable.
I want to return the number of rows of this table with that stored procedure.
I tried something like this but it did not work:
declare #maxRowCount bigint
exec('set '+ #maxRowCount + ' =(select COUNT(1) from ' + #tableName + ')')
This is SQL Server 2008.
You can try this
CREATE PROCEDURE dbo.sp_selectcount
#tablename NVARCHAR(200)
AS
DECLARE #cmd NVARCHAR (255)
SET #cmd = 'SELECT count(*) from ' + #tablename
EXEC sp_executesql #cmd
The following example should give you something to work with.
-- fully qualify your table name (this is probably an input value in your sproc?)
-- please note that I use system view master.sys.tables as an example table here
DECLARE #tablename NVARCHAR(MAX) = N'[master].[sys].[tables]';
-- build the sql statement that you will execute
DECLARE #sql NVARCHAR(MAX) = N'SELECT COUNT(*) FROM ' + #tablename;
-- create a variable to hold the number of rows later on
DECLARE #nrofrows BIGINT;
-- create a temp table to store the result of executing the sql statement
CREATE TABLE #temp (NrOfRows BIGINT);
-- insert the result of the execution of the sql statement into the temp table
INSERT INTO #temp
EXECUTE(#sql);
-- extract the number of rows from the temp table
SET #nrofrows = (SELECT NrOfRows FROM #temp);
-- check the result so you can test!
PRINT #nrofrows;
If you want good background information on dynamic SQL, check out Erland Sommarskogs article The Curse and Blessings of Dynamic SQL.
You should remove the quotes around #maxRowCount.
Try this:
declare #maxRowCount bigint
exec('set #maxRowCount =(select COUNT(*) from ' + #tableName + ')')
OR
exec('SELECT #maxRowCount = COUNT(*) from ' + #tableName)
Analysis:
With the query you tried, it will execute:
set blablabla = (select count(1) from MyTable)
By removing the quotes:
set #maxRowCount = (select count(*) from MyTable)
You can try this instead.
declare #maxRowCount bigint(5)
exec('SELECT COUNT(*) INTO #maxRowCount FROM ' + #tableName)