SQL Server查询使用临时变量

时间:2018-12-03 10:43:07

标签: sql sql-server variables cursor

我想使用临时变量来使用此代码,请提出建议。

enter image description here

SELECT *
FROM Customers

DECLARE @name VARCHAR(50)
DECLARE @salary INT

CREATE TABLE #Result1 (Name VARCHAR(50), Salary INT)

DECLARE zxcv CURSOR FOR
    SELECT
        CASE
           WHEN LEN(Name) <= 5
              THEN CONCAT(Name, '_', LEN(Name))
              ELSE Name 
        END,
        Salary 
    FROM 
        Customers;

OPEN zxcv

FETCH NEXT FROM zxcv INTO @name, @salary;

WHILE @@FETCH_STATUS = 0 
BEGIN
    INSERT INTO #Result1 (Name, Salary)
    VALUES (@name, @salary);

    FETCH NEXT FROM zxcv INTO @name, @salary;
END

CLOSE zxcv;
DEALLOCATE zxcv;

SELECT * FROM #Result1;

3 个答案:

答案 0 :(得分:0)

尝试一下

SELECT ID,
      IIF(LEN(Name)<=5,Name+'_'+CAST(LEN(Name) AS VARCHAR(10)) ,Name) As Name,
      Age
 FROM
(
SELECT 1 ID,'Abccd' Name, 23 Age UNION ALL
SELECT 2 ID,'Abccderdf' Name, 42 Age UNION ALL
SELECT 3 ID,'Abccd' Name, 64 Age 

)dt

结果

ID  Name        Age
-------------------
1   Abccd_5     23
2   Abccderdf   42
3   Abccd_5     64

答案 1 :(得分:0)

尝试一下。

SELECT
    CASE 
       WHEN LEN(Name) <= 5 
          THEN Name + '_' + CAST(LEN(NAME) AS NVARCHAR(5))
          ELSE Name 
    END AS 'Name',
    Age
INTO 
    #Result1
FROM 
    Customers

SELECT * FROM #Result1

答案 2 :(得分:0)

I guess you want to use Table variables instead of temp tables. Here is your edited code:-

SELECT *
FROM Customers

DECLARE @name VARCHAR(50)
DECLARE @salary INT

declare  @Result1 table(Name VARCHAR(50), Salary INT)

DECLARE zxcv CURSOR FOR
    SELECT
        CASE
           WHEN LEN(Name) <= 5
              THEN CONCAT(Name, '_', LEN(Name))
              ELSE Name 
        END,
        Salary 
    FROM 
        Customers;

OPEN zxcv

FETCH NEXT FROM zxcv INTO @name, @salary;

WHILE @@FETCH_STATUS = 0 
BEGIN
    INSERT INTO @Result1 (Name, Salary)
    VALUES (@name, @salary);

    FETCH NEXT FROM zxcv INTO @name, @salary;
END

CLOSE zxcv;
DEALLOCATE zxcv;

SELECT * FROM @Result1;